root/src/map/pc.c

Revision 24, 216.6 kB (checked in by jinshiro, 17 years ago)
Line 
1// Copyright (c) Athena Dev Teams - Licensed under GNU GPL
2// For more information, see LICENCE in the main folder
3
4#include "../common/cbasetypes.h"
5#include "../common/core.h" // get_svn_revision()
6#include "../common/malloc.h"
7#include "../common/nullpo.h"
8#include "../common/showmsg.h"
9#include "../common/socket.h" // RFIFO*()
10#include "../common/strlib.h" // safestrncpy()
11#include "../common/timer.h"
12#include "../common/utils.h"
13
14#include "atcommand.h" // get_atcommand_level()
15#include "battle.h" // battle_config
16#include "chrif.h"
17#include "clif.h"
18#include "date.h" // is_day_of_*()
19#include "intif.h"
20#include "itemdb.h"
21#include "log.h"
22#include "mail.h"
23#include "map.h"
24#include "path.h"
25#include "mercenary.h" // merc_is_hom_active()
26#include "mob.h" // MAX_MOB_RACE_DB
27#include "npc.h" // fake_nd
28#include "pet.h" // pet_unlocktarget()
29#include "party.h" // party_search()
30#include "guild.h" // guild_search(), guild_request_info()
31#include "script.h" // script_config
32#include "skill.h"
33#include "status.h" // struct status_data
34#include "vending.h" // vending_closevending()
35#include "pc.h"
36#include "quest.h"
37
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <time.h>
42
43
44#define PVP_CALCRANK_INTERVAL 1000      // PVP‡ˆÊŒvŽZ‚ÌŠÔŠu
45static unsigned int exp_table[CLASS_COUNT][2][MAX_LEVEL];
46static unsigned int max_level[CLASS_COUNT][2];
47static short statp[MAX_LEVEL+1];
48
49// h-files are for declarations, not for implementations... [Shinomori]
50struct skill_tree_entry skill_tree[CLASS_COUNT][MAX_SKILL_TREE];
51// timer for night.day implementation
52int day_timer_tid;
53int night_timer_tid;
54
55struct fame_list smith_fame_list[MAX_FAME_LIST];
56struct fame_list chemist_fame_list[MAX_FAME_LIST];
57struct fame_list taekwon_fame_list[MAX_FAME_LIST];
58
59static unsigned short equip_pos[EQI_MAX]={EQP_ACC_L,EQP_ACC_R,EQP_SHOES,EQP_GARMENT,EQP_HEAD_LOW,EQP_HEAD_MID,EQP_HEAD_TOP,EQP_ARMOR,EQP_HAND_L,EQP_HAND_R,EQP_AMMO};
60
61static struct gm_account *gm_account = NULL;
62static int GM_num = 0;
63
64#define MOTD_LINE_SIZE 128
65char motd_text[MOTD_LINE_SIZE][256]; // Message of the day buffer [Valaris]
66
67struct duel duel_list[MAX_DUEL];
68int duel_count = 0;
69
70//Links related info to the sd->hate_mob[]/sd->feel_map[] entries
71const struct sg_data sg_info[3] = {
72                { SG_SUN_ANGER, SG_SUN_BLESS, SG_SUN_COMFORT, "PC_FEEL_SUN", "PC_HATE_MOB_SUN", is_day_of_sun },
73                { SG_MOON_ANGER, SG_MOON_BLESS, SG_MOON_COMFORT, "PC_FEEL_MOON", "PC_HATE_MOB_MOON", is_day_of_moon },
74                { SG_STAR_ANGER, SG_STAR_BLESS, SG_STAR_COMFORT, "PC_FEEL_STAR", "PC_HATE_MOB_STAR", is_day_of_star }
75        };
76
77//Converts a class to its array index for CLASS_COUNT defined arrays.
78//Note that it does not do a validity check for speed purposes, where parsing
79//player input make sure to use a pcdb_checkid first!
80int pc_class2idx(int class_) {
81        if (class_ >= JOB_NOVICE_HIGH)
82                return class_- JOB_NOVICE_HIGH+JOB_MAX_BASIC;
83        return class_;
84}
85
86int pc_isGM(struct map_session_data* sd)
87{
88        int i;
89        nullpo_retr(0, sd);
90
91        if( sd->bl.type != BL_PC )
92                return 99;
93
94        ARR_FIND( 0, GM_num, i, gm_account[i].account_id == sd->status.account_id );
95        return ( i < GM_num ) ? gm_account[i].level : 0;
96}
97
98int pc_set_gm_level(int account_id, int level)
99{
100    int i;
101
102        ARR_FIND( 0, GM_num, i, account_id == gm_account[i].account_id );
103        if( i < GM_num )
104        {
105                gm_account[i].level = level;
106        }
107        else
108        {
109            gm_account = (struct gm_account *) aRealloc(gm_account, (GM_num + 1) * sizeof(struct gm_account));
110            gm_account[GM_num].account_id = account_id;
111            gm_account[GM_num].level = level;
112            GM_num++;
113        }
114
115        return 0;
116}
117
118static int pc_invincible_timer(int tid, unsigned int tick, int id, intptr data)
119{
120        struct map_session_data *sd;
121
122        if( (sd=(struct map_session_data *)map_id2sd(id)) == NULL || sd->bl.type!=BL_PC )
123                return 1;
124
125        if(sd->invincible_timer != tid){
126                ShowError("invincible_timer %d != %d\n",sd->invincible_timer,tid);
127                return 0;
128        }
129        sd->invincible_timer=-1;
130        skill_unit_move(&sd->bl,tick,1);
131
132        return 0;
133}
134
135void pc_setinvincibletimer(struct map_session_data* sd, int val) 
136{
137        nullpo_retv(sd);
138
139        if( sd->invincible_timer != INVALID_TIMER )
140                delete_timer(sd->invincible_timer,pc_invincible_timer);
141        sd->invincible_timer = add_timer(gettick()+val,pc_invincible_timer,sd->bl.id,0);
142}
143
144void pc_delinvincibletimer(struct map_session_data* sd)
145{
146        nullpo_retv(sd);
147
148        if( sd->invincible_timer != INVALID_TIMER )
149        {
150                delete_timer(sd->invincible_timer,pc_invincible_timer);
151                sd->invincible_timer = INVALID_TIMER;
152                skill_unit_move(&sd->bl,gettick(),1);
153        }
154}
155
156static int pc_spiritball_timer(int tid, unsigned int tick, int id, intptr data)
157{
158        struct map_session_data *sd;
159
160        if( (sd=(struct map_session_data *)map_id2sd(id)) == NULL || sd->bl.type!=BL_PC )
161                return 1;
162
163        if(sd->spirit_timer[0] != tid){
164                ShowError("spirit_timer %d != %d\n",sd->spirit_timer[0],tid);
165                return 0;
166        }
167
168        if(sd->spiritball <= 0) {
169                ShowError("Spiritballs are already 0 when pc_spiritball_timer gets called");
170                sd->spiritball = 0;
171                return 0;
172        }
173
174        sd->spiritball--;
175        // I leave this here as bad example [Shinomori]
176        //memcpy( &sd->spirit_timer[0], &sd->spirit_timer[1], sizeof(sd->spirit_timer[0]) * sd->spiritball );
177        memmove( sd->spirit_timer+0, sd->spirit_timer+1, (sd->spiritball)*sizeof(int) );
178        sd->spirit_timer[sd->spiritball]=-1;
179
180        clif_spiritball(sd);
181
182        return 0;
183}
184
185int pc_addspiritball(struct map_session_data *sd,int interval,int max)
186{
187        nullpo_retr(0, sd);
188
189        if(max > MAX_SKILL_LEVEL)
190                max = MAX_SKILL_LEVEL;
191        if(sd->spiritball < 0)
192                sd->spiritball = 0;
193
194        if(sd->spiritball >= max) {
195                if(sd->spirit_timer[0] != -1)
196                        delete_timer(sd->spirit_timer[0],pc_spiritball_timer);
197                // I leave this here as bad example [Shinomori]
198                //memcpy( &sd->spirit_timer[0], &sd->spirit_timer[1], sizeof(sd->spirit_timer[0]) * (sd->spiritball - 1));
199                memmove( sd->spirit_timer+0, sd->spirit_timer+1, (sd->spiritball - 1)*sizeof(int) );
200                //sd->spirit_timer[sd->spiritball-1] = -1; // intentionally, but will be overwritten
201        } else
202                sd->spiritball++;
203
204        sd->spirit_timer[sd->spiritball-1] = add_timer(gettick()+interval,pc_spiritball_timer,sd->bl.id,0);
205        clif_spiritball(sd);
206
207        return 0;
208}
209
210int pc_delspiritball(struct map_session_data *sd,int count,int type)
211{
212        int i;
213
214        nullpo_retr(0, sd);
215
216        if(sd->spiritball <= 0) {
217                sd->spiritball = 0;
218                return 0;
219        }
220
221        if(count > sd->spiritball)
222                count = sd->spiritball;
223        sd->spiritball -= count;
224        if(count > MAX_SKILL_LEVEL)
225                count = MAX_SKILL_LEVEL;
226
227        for(i=0;i<count;i++) {
228                if(sd->spirit_timer[i] != -1) {
229                        delete_timer(sd->spirit_timer[i],pc_spiritball_timer);
230                        sd->spirit_timer[i] = -1;
231                }
232        }
233        for(i=count;i<MAX_SKILL_LEVEL;i++) {
234                sd->spirit_timer[i-count] = sd->spirit_timer[i];
235                sd->spirit_timer[i] = -1;
236        }
237
238        if(!type)
239                clif_spiritball(sd);
240
241        return 0;
242}
243
244// Increases a player's fame points and displays a notice to him
245void pc_addfame(struct map_session_data *sd,int count)
246{
247        nullpo_retv(sd);
248        sd->status.fame += count;
249        if(sd->status.fame > MAX_FAME)
250                sd->status.fame = MAX_FAME;
251        switch(sd->class_&MAPID_UPPERMASK){
252                case MAPID_BLACKSMITH: // Blacksmith
253                        clif_fame_blacksmith(sd,count);
254                        break;
255                case MAPID_ALCHEMIST: // Alchemist
256                        clif_fame_alchemist(sd,count);
257                        break;
258                case MAPID_TAEKWON: // Taekwon
259                        clif_fame_taekwon(sd,count);
260                        break; 
261        }
262        chrif_updatefamelist(sd);
263}
264
265// Check whether a player ID is in the fame rankers' list of its job, returns his/her position if so, 0 else
266unsigned char pc_famerank(int char_id, int job)
267{
268        int i;
269       
270        switch(job){
271                case MAPID_BLACKSMITH: // Blacksmith
272                    for(i = 0; i < MAX_FAME_LIST; i++){
273                                if(smith_fame_list[i].id == char_id)
274                                    return i + 1;
275                        }
276                        break;
277                case MAPID_ALCHEMIST: // Alchemist
278                        for(i = 0; i < MAX_FAME_LIST; i++){
279                                if(chemist_fame_list[i].id == char_id)
280                                        return i + 1;
281                        }
282                        break;
283                case MAPID_TAEKWON: // Taekwon
284                        for(i = 0; i < MAX_FAME_LIST; i++){
285                                if(taekwon_fame_list[i].id == char_id)
286                                        return i + 1;
287                        }
288                        break;
289        }
290
291        return 0;
292}
293
294int pc_setrestartvalue(struct map_session_data *sd,int type)
295{
296        struct status_data *status, *b_status;
297        nullpo_retr(0, sd);
298
299        b_status = &sd->base_status;
300        status = &sd->battle_status;
301
302        if (type&1)
303        {       //Normal resurrection
304                status->hp = 1; //Otherwise status_heal may fail if dead.
305                status_heal(&sd->bl, b_status->hp, b_status->sp>status->sp?b_status->sp-status->sp:0, 1);
306        } else { //Just for saving on the char-server (with values as if respawned)
307                sd->status.hp = b_status->hp;
308                sd->status.sp = (status->sp < b_status->sp)?b_status->sp:status->sp;
309        }
310        return 0;
311}
312
313/*==========================================
314        Determines if the GM can give / drop / trade / vend items
315    Args: GM Level (current player GM level)
316 *------------------------------------------*/
317bool pc_can_give_items(int level)
318{
319        return( level < battle_config.gm_cant_drop_min_lv || level > battle_config.gm_cant_drop_max_lv );
320}
321
322/*==========================================
323 * prepares character for saving.
324 *------------------------------------------*/
325int pc_makesavestatus(struct map_session_data *sd)
326{
327        nullpo_retr(0, sd);
328
329        if(!battle_config.save_clothcolor)
330                sd->status.clothes_color=0;
331
332        //Only copy the Cart/Peco/Falcon options, the rest are handled via
333        //status change load/saving. [Skotlex]
334        sd->status.option = sd->sc.option&(OPTION_CART|OPTION_FALCON|OPTION_RIDING);
335               
336        if (sd->sc.data[SC_JAILED])
337        {       //When Jailed, do not move last point.
338                if(pc_isdead(sd)){
339                        pc_setrestartvalue(sd,0);
340                } else {
341                        sd->status.hp = sd->battle_status.hp;
342                        sd->status.sp = sd->battle_status.sp;
343                }
344                sd->status.last_point.map = sd->mapindex;
345                sd->status.last_point.x = sd->bl.x;
346                sd->status.last_point.y = sd->bl.y;
347                return 0;
348        }
349
350        if(pc_isdead(sd)){
351                pc_setrestartvalue(sd,0);
352                memcpy(&sd->status.last_point,&sd->status.save_point,sizeof(sd->status.last_point));
353        } else {
354                sd->status.hp = sd->battle_status.hp;
355                sd->status.sp = sd->battle_status.sp;
356                sd->status.last_point.map = sd->mapindex;
357                sd->status.last_point.x = sd->bl.x;
358                sd->status.last_point.y = sd->bl.y;
359        }
360
361        if(map[sd->bl.m].flag.nosave){
362                struct map_data *m=&map[sd->bl.m];
363                if(m->save.map)
364                        memcpy(&sd->status.last_point,&m->save,sizeof(sd->status.last_point));
365                else
366                        memcpy(&sd->status.last_point,&sd->status.save_point,sizeof(sd->status.last_point));
367        }
368
369        return 0;
370}
371
372/*==========================================
373 * Ú?Žb̏‰Šú‰»
374 *------------------------------------------*/
375int pc_setnewpc(struct map_session_data *sd, int account_id, int char_id, int login_id1, unsigned int client_tick, int sex, int fd)
376{
377        nullpo_retr(0, sd);
378
379        sd->bl.id        = account_id;
380        sd->status.account_id   = account_id;
381        sd->status.char_id      = char_id;
382        sd->status.sex   = sex;
383        sd->login_id1    = login_id1;
384        sd->login_id2    = 0; // at this point, we can not know the value :(
385        sd->client_tick  = client_tick;
386        sd->state.active = 0; //to be set to 1 after player is fully authed and loaded.
387        sd->bl.type      = BL_PC;
388        sd->canlog_tick  = gettick();
389        //Required to prevent homunculus copuing a base speed of 0.
390        sd->battle_status.speed = sd->base_status.speed = DEFAULT_WALK_SPEED;
391        return 0;
392}
393
394int pc_equippoint(struct map_session_data *sd,int n)
395{
396        int ep = 0;
397
398        nullpo_retr(0, sd);
399
400        if(!sd->inventory_data[n])
401                return 0;
402
403        if (!itemdb_isequip2(sd->inventory_data[n]))
404                return 0; //Not equippable by players.
405       
406        ep = sd->inventory_data[n]->equip;
407        if(sd->inventory_data[n]->look == W_DAGGER      ||
408                sd->inventory_data[n]->look == W_1HSWORD ||
409                sd->inventory_data[n]->look == W_1HAXE) {
410                if(ep == EQP_HAND_R && (pc_checkskill(sd,AS_LEFT) > 0 || (sd->class_&MAPID_UPPERMASK) == MAPID_ASSASSIN))
411                        return EQP_ARMS;
412        }
413        return ep;
414}
415
416int pc_setinventorydata(struct map_session_data *sd)
417{
418        int i,id;
419
420        nullpo_retr(0, sd);
421
422        for(i=0;i<MAX_INVENTORY;i++) {
423                id = sd->status.inventory[i].nameid;
424                sd->inventory_data[i] = id?itemdb_search(id):NULL;
425        }
426        return 0;
427}
428
429int pc_calcweapontype(struct map_session_data *sd)
430{
431        nullpo_retr(0, sd);
432
433        // single-hand
434        if(sd->weapontype2 == W_FIST) {
435                sd->status.weapon = sd->weapontype1;
436                return 1;
437        }
438        if(sd->weapontype1 == W_FIST) {
439                sd->status.weapon = sd->weapontype2;
440                return 1;
441        }
442        // dual-wield
443        sd->status.weapon = 0;
444        switch (sd->weapontype1){
445        case W_DAGGER:
446                switch (sd->weapontype2) {
447                case W_DAGGER:  sd->status.weapon = W_DOUBLE_DD; break;
448                case W_1HSWORD: sd->status.weapon = W_DOUBLE_DS; break;
449                case W_1HAXE:   sd->status.weapon = W_DOUBLE_DA; break;
450                }
451                break;
452        case W_1HSWORD:
453                switch (sd->weapontype2) {
454                case W_DAGGER:  sd->status.weapon = W_DOUBLE_DS; break;
455                case W_1HSWORD: sd->status.weapon = W_DOUBLE_SS; break;
456                case W_1HAXE:   sd->status.weapon = W_DOUBLE_SA; break;
457                }
458                break;
459        case W_1HAXE:
460                switch (sd->weapontype2) {
461                case W_DAGGER:  sd->status.weapon = W_DOUBLE_DA; break;
462                case W_1HSWORD: sd->status.weapon = W_DOUBLE_SA; break;
463                case W_1HAXE:   sd->status.weapon = W_DOUBLE_AA; break;
464                }
465        }
466        // unknown, default to right hand type
467        if (!sd->status.weapon)
468                sd->status.weapon = sd->weapontype1;
469
470        return 2;
471}
472
473int pc_setequipindex(struct map_session_data *sd)
474{
475        int i,j;
476
477        nullpo_retr(0, sd);
478
479        for(i=0;i<EQI_MAX;i++)
480                sd->equip_index[i] = -1;
481
482        for(i=0;i<MAX_INVENTORY;i++) {
483                if(sd->status.inventory[i].nameid <= 0)
484                        continue;
485                if(sd->status.inventory[i].equip) {
486                        for(j=0;j<EQI_MAX;j++)
487                                if(sd->status.inventory[i].equip & equip_pos[j])
488                                        sd->equip_index[j] = i;
489
490                        if(sd->status.inventory[i].equip & EQP_HAND_R)
491                        {
492                                if(sd->inventory_data[i])
493                                        sd->weapontype1 = sd->inventory_data[i]->look;
494                                else
495                                        sd->weapontype1 = 0;
496                        }
497
498                        if( sd->status.inventory[i].equip & EQP_HAND_L )
499                        {
500                                if( sd->inventory_data[i] && sd->inventory_data[i]->type == 4 )
501                                        sd->weapontype2 = sd->inventory_data[i]->look;
502                                else
503                                        sd->weapontype2 = 0;
504                        }
505                }
506        }
507        pc_calcweapontype(sd);
508
509        return 0;
510}
511
512static int pc_isAllowedCardOn(struct map_session_data *sd,int s,int eqindex,int flag)
513{
514        int i;
515        struct item *item = &sd->status.inventory[eqindex];
516        struct item_data *data;
517        //Crafted/made/hatched items.
518        if (itemdb_isspecial(item->card[0]))
519                return 1;
520       
521        ARR_FIND( 0, s, i, item->card[i] && (data = itemdb_exists(item->card[i])) != NULL && data->flag.no_equip&flag );
522        return( i < s ) ? 0 : 1;
523}
524
525bool pc_isequipped(struct map_session_data *sd, int nameid)
526{
527        int i, j, index;
528
529        for( i = 0; i < EQI_MAX; i++ )
530        {
531                index = sd->equip_index[i];
532                if( index < 0 ) continue;
533
534                if( i == EQI_HAND_R && sd->equip_index[EQI_HAND_L] == index ) continue;
535                if( i == EQI_HEAD_MID && sd->equip_index[EQI_HEAD_LOW] == index ) continue;
536                if( i == EQI_HEAD_TOP && (sd->equip_index[EQI_HEAD_MID] == index || sd->equip_index[EQI_HEAD_LOW] == index) ) continue;
537       
538                if( !sd->inventory_data[index] ) continue;
539
540                if( sd->inventory_data[index]->nameid == nameid )
541                        return true;
542
543                for( j = 0; j < sd->inventory_data[index]->slot; j++ )
544                        if( sd->status.inventory[index].card[j] == nameid )
545                                return true;
546        }
547
548        return false;
549}
550
551bool pc_can_Adopt(struct map_session_data *p1_sd, struct map_session_data *p2_sd, struct map_session_data *b_sd )
552{
553        if( !p1_sd || !p2_sd || !b_sd )
554                return false;
555
556        if( b_sd->status.father || b_sd->status.mother || b_sd->adopt_invite )
557                return false; // already adopted baby / in adopt request
558
559        if( !p1_sd->status.partner_id || !p1_sd->status.party_id || p1_sd->status.party_id != b_sd->status.party_id )
560                return false; // You need to be married and in party with baby to adopt
561
562        if( p1_sd->status.partner_id != p2_sd->status.char_id || p2_sd->status.partner_id != p1_sd->status.char_id )
563                return false; // Not married, wrong married
564
565        if( p2_sd->status.party_id != p1_sd->status.party_id )
566                return false; // Both parents need to be in the same party
567
568        // Parents need to have their ring equipped
569        if( !pc_isequipped(p1_sd, WEDDING_RING_M) && !pc_isequipped(p1_sd, WEDDING_RING_F) )
570                return false; 
571
572        if( !pc_isequipped(p2_sd, WEDDING_RING_M) && !pc_isequipped(p2_sd, WEDDING_RING_F) )
573                return false;
574
575        // Already adopted a baby
576        if( p1_sd->status.child || p2_sd->status.child ) {
577                clif_Adopt_reply(p1_sd, 0);
578                return false;
579        }
580
581        // Parents need at least lvl 70 to adopt
582        if( p1_sd->status.base_level < 70 || p2_sd->status.base_level < 70 ) {
583                clif_Adopt_reply(p1_sd, 1);
584                return false;
585        }
586
587        if( b_sd->status.partner_id ) {
588                clif_Adopt_reply(p1_sd, 2);
589                return false;
590        }
591
592        if( !(b_sd->status.class_ >= JOB_NOVICE && b_sd->status.class_ <= JOB_THIEF) )
593                return false;
594
595        return true;
596}
597
598/*==========================================
599 * Adoption Process
600 *------------------------------------------*/
601bool pc_adoption(struct map_session_data *p1_sd, struct map_session_data *p2_sd, struct map_session_data *b_sd)
602{
603        int job, joblevel;
604        unsigned int jobexp;
605       
606        if( !pc_can_Adopt(p1_sd, p2_sd, b_sd) )
607                return false;
608
609        // Preserve current job levels and progress
610        joblevel = b_sd->status.job_level;
611        jobexp = b_sd->status.job_exp;
612
613        job = pc_mapid2jobid(b_sd->class_|JOBL_BABY, b_sd->status.sex);
614        if( job != -1 && !pc_jobchange(b_sd, job, 0) )
615        { // Success, proceed to configure parents and baby skills
616                p1_sd->status.child = b_sd->status.char_id;
617                p2_sd->status.child = b_sd->status.char_id;
618                b_sd->status.father = p1_sd->status.char_id;
619                b_sd->status.mother = p2_sd->status.char_id;
620
621                // Restore progress
622                b_sd->status.job_level = joblevel;
623                clif_updatestatus(b_sd, SP_JOBLEVEL);
624                b_sd->status.job_exp = jobexp;
625                clif_updatestatus(b_sd, SP_JOBEXP);
626
627                // Baby Skills
628                pc_skill(b_sd, WE_BABY, 1, 0);
629                pc_skill(b_sd, WE_CALLPARENT, 1, 0);
630
631                // Parents Skills
632                pc_skill(p1_sd, WE_CALLBABY, 1, 0);
633                pc_skill(p2_sd, WE_CALLBABY, 1, 0);
634               
635                return true;
636        }
637
638        return false; // Job Change Fail
639}
640
641int pc_isequip(struct map_session_data *sd,int n)
642{
643        struct item_data *item;
644        //?¶‚â—{Žq‚̏ꍇ‚ÌŒ³‚̐E‹Æ‚ðŽZo‚·‚é
645
646        nullpo_retr(0, sd);
647
648        item = sd->inventory_data[n];
649
650        if( battle_config.gm_allequip>0 && pc_isGM(sd)>=battle_config.gm_allequip )
651                return 1;
652
653        if(item == NULL)
654                return 0;
655        if(item->elv && sd->status.base_level < (unsigned int)item->elv)
656                return 0;
657        if(item->sex != 2 && sd->status.sex != item->sex)
658                return 0;
659        if(map[sd->bl.m].flag.pvp && ((item->flag.no_equip&1) || !pc_isAllowedCardOn(sd,item->slot,n,1)))
660                return 0;
661        if(map_flag_gvg(sd->bl.m) && ((item->flag.no_equip&2) || !pc_isAllowedCardOn(sd,item->slot,n,2)))
662                return 0; 
663        if(map[sd->bl.m].flag.restricted)
664        {
665                int flag =map[sd->bl.m].zone;
666                if (item->flag.no_equip&flag || !pc_isAllowedCardOn(sd,item->slot,n,flag))
667                        return 0;
668        }
669
670        if (sd->sc.count) {
671                       
672                if(item->equip & EQP_ARMS && item->type == IT_WEAPON && sd->sc.data[SC_STRIPWEAPON]) // Also works with left-hand weapons [DracoRPG]
673                        return 0;
674                if(item->equip & EQP_SHIELD && item->type == IT_ARMOR && sd->sc.data[SC_STRIPSHIELD])
675                        return 0;
676                if(item->equip & EQP_ARMOR && sd->sc.data[SC_STRIPARMOR])
677                        return 0;
678                if(item->equip & EQP_HELM && sd->sc.data[SC_STRIPHELM])
679                        return 0;
680
681                if (sd->sc.data[SC_SPIRIT] && sd->sc.data[SC_SPIRIT]->val2 == SL_SUPERNOVICE) {
682                        //Spirit of Super Novice equip bonuses. [Skotlex]
683                        if (sd->status.base_level > 90 && item->equip & EQP_HELM)
684                                return 1; //Can equip all helms
685
686                        if (sd->status.base_level > 96 && item->equip & EQP_ARMS && item->type == IT_WEAPON)
687                                switch(item->look) { //In weapons, the look determines type of weapon.
688                                        case W_DAGGER: //Level 4 Knives are equippable.. this means all knives, I'd guess?
689                                        case W_1HSWORD: //All 1H swords
690                                        case W_1HAXE: //All 1H Axes
691                                        case W_MACE: //All 1H Maces
692                                        case W_STAFF: //All 1H Staves
693                                                return 1;
694                                }
695                }
696        }
697        //Not equipable by class. [Skotlex]
698        if (!(1<<(sd->class_&MAPID_BASEMASK)&item->class_base[(sd->class_&JOBL_2_1)?1:((sd->class_&JOBL_2_2)?2:0)]))
699                return 0;
700       
701        //Not equipable by upper class. [Skotlex]
702        if(!(1<<((sd->class_&JOBL_UPPER)?1:((sd->class_&JOBL_BABY)?2:0))&item->class_upper))
703                return 0;
704
705        return 1;
706}
707
708/*==========================================
709 * session id‚É–â‘è–³‚µ
710 * charŽI‚©‚ç‘—‚ç‚ê‚Ä‚«‚œƒXƒe?ƒ^ƒX‚ðÝ’è
711 *------------------------------------------*/
712bool pc_authok(struct map_session_data *sd, int login_id2, time_t expiration_time, struct mmo_charstatus *st)
713{
714        int i;
715        unsigned long tick = gettick();
716
717        sd->login_id2 = login_id2;
718        memcpy(&sd->status, st, sizeof(*st));
719
720        if (st->sex != sd->status.sex) {
721                clif_authfail_fd(sd->fd, 0);
722                return false;
723        }
724
725        //Set the map-server used job id. [Skotlex]
726        i = pc_jobid2mapid(sd->status.class_);
727        if (i == -1) { //Invalid class?
728                ShowError("pc_authok: Invalid class %d for player %s (%d:%d). Class was changed to novice.\n", sd->status.class_, sd->status.name, sd->status.account_id, sd->status.char_id);
729                sd->status.class_ = JOB_NOVICE;
730                sd->class_ = MAPID_NOVICE;
731        } else
732                sd->class_ = i; 
733        //Initializations to null/0 unneeded since map_session_data was filled with 0 upon allocation.
734        if(!sd->status.hp) pc_setdead(sd);
735        sd->state.connect_new = 1;
736
737        sd->followtimer = -1; // [MouseJstr]
738        sd->invincible_timer = -1;
739        sd->npc_timer_id = -1;
740        sd->pvp_timer = -1;
741       
742        sd->canuseitem_tick = tick;
743        sd->cantalk_tick = tick;
744        sd->cansendmail_tick = tick;
745
746        for(i = 0; i < MAX_SKILL_LEVEL; i++)
747                sd->spirit_timer[i] = -1;
748
749        if (battle_config.item_auto_get)
750                sd->state.autoloot = 10000;
751
752        if (battle_config.disp_experience)
753                sd->state.showexp = 1;
754        if (battle_config.disp_zeny)
755                sd->state.showzeny = 1;
756//Checks the battleflags to see if player has selected to see summon's stats.
757//I see nothing wrong here.
758        //Vanaheim settings [Brainstorm]
759        if (battle_config.disp_summon_stats) // Battle Flag to Show Summoned Monster Stats [Brain]
760                sd->state.showsummon = 1;
761
762       
763        if (!(battle_config.display_skill_fail&2))
764                sd->state.showdelay = 1;
765               
766        // ƒAƒCƒeƒ€ƒ`ƒFƒbƒN
767        pc_setinventorydata(sd);
768        pc_checkitem(sd);
769       
770        status_change_init(&sd->bl);
771        if ((battle_config.atc_gmonly == 0 || pc_isGM(sd)) && (pc_isGM(sd) >= get_atcommand_level(atcommand_hide)))
772                sd->status.option &= (OPTION_MASK | OPTION_INVISIBLE);
773        else
774                sd->status.option &= OPTION_MASK;
775
776        sd->sc.option = sd->status.option; //This is the actual option used in battle.
777        //Set here because we need the inventory data for weapon sprite parsing.
778        status_set_viewdata(&sd->bl, sd->status.class_);
779        unit_dataset(&sd->bl);
780
781        sd->guild_x = -1;
782        sd->guild_y = -1;
783
784        // ƒCƒxƒ“ƒg?ŒW‚̏‰Šú‰»
785        for(i = 0; i < MAX_EVENTTIMER; i++)
786                sd->eventtimer[i] = -1;
787
788        for (i = 0; i < 3; i++)
789                sd->hate_mob[i] = -1;
790
791        // ˆÊ’u‚̐ݒè
792        if ((i=pc_setpos(sd,sd->status.last_point.map, sd->status.last_point.x, sd->status.last_point.y, 0)) != 0) {
793                ShowError ("Last_point_map %s - id %d not found (error code %d)\n", mapindex_id2name(sd->status.last_point.map), sd->status.last_point.map, i);
794
795                // try warping to a default map instead (church graveyard)
796                if (pc_setpos(sd, mapindex_name2id(MAP_PRONTERA), 273, 354, 0) != 0) {
797                        // if we fail again
798                        clif_authfail_fd(sd->fd, 0);
799                        return false;
800                }
801        }
802
803        clif_authok(sd);
804
805        //Prevent S. Novices from getting the no-death bonus just yet. [Skotlex]
806        sd->die_counter=-1;
807
808        {       //Add IP field
809                uint32 ip = session[sd->fd]->client_addr;
810                if (pc_isGM(sd))
811                        ShowInfo("GM '"CL_WHITE"%s"CL_RESET"' logged in."
812                                " (AID/CID: '"CL_WHITE"%d/%d"CL_RESET"',"
813                                " Packet Ver: '"CL_WHITE"%d"CL_RESET"', IP: '"CL_WHITE"%d.%d.%d.%d"CL_RESET"',"
814                                " GM Level '"CL_WHITE"%d"CL_RESET"').\n",
815                                sd->status.name, sd->status.account_id, sd->status.char_id,
816                                sd->packet_ver, CONVIP(ip), pc_isGM(sd));
817                else
818                        ShowInfo("'"CL_WHITE"%s"CL_RESET"' logged in."
819                                " (AID/CID: '"CL_WHITE"%d/%d"CL_RESET"',"
820                                " Packet Ver: '"CL_WHITE"%d"CL_RESET"', IP: '"CL_WHITE"%d.%d.%d.%d"CL_RESET"').\n",
821                                sd->status.name, sd->status.account_id, sd->status.char_id,
822                                sd->packet_ver, CONVIP(ip));
823        }
824       
825        // Send friends list
826        clif_friendslist_send(sd);
827
828        if (battle_config.display_version == 1){
829                char buf[256];
830                sprintf(buf, "eAthena SVN version: %s", get_svn_revision());
831                clif_displaymessage(sd->fd, buf);
832        }
833
834        // Message of the Day [Valaris]
835        for(i=0; motd_text[i][0] && i < MOTD_LINE_SIZE; i++) {
836                if (battle_config.motd_type)
837                        clif_disp_onlyself(sd,motd_text[i],strlen(motd_text[i]));
838                else
839                        clif_displaymessage(sd->fd, motd_text[i]);
840        }
841
842        // message of the limited time of the account
843        if (expiration_time != 0) { // don't display if it's unlimited or unknow value
844                char tmpstr[1024];
845                strftime(tmpstr, sizeof(tmpstr) - 1, msg_txt(501), localtime(&expiration_time)); // "Your account time limit is: %d-%m-%Y %H:%M:%S."
846                clif_wis_message(sd->fd, wisp_server_name, tmpstr, strlen(tmpstr)+1);
847        }
848
849        //Night message
850        if (night_flag)
851        {
852                char tmpstr[1024];
853                strcpy(tmpstr, msg_txt(500)); // Actually, it's the night...
854                clif_wis_message(sd->fd, wisp_server_name, tmpstr, strlen(tmpstr)+1);
855        }
856
857        // Request all registries (auth is considered completed whence they arrive)
858        intif_request_registry(sd,7);
859        return true;
860}
861
862/*==========================================
863 * Closes a connection because it failed to be authenticated from the char server.
864 *------------------------------------------*/
865void pc_authfail(struct map_session_data *sd)
866{
867        clif_authfail_fd(sd->fd, 0);
868        return;
869}
870
871//Attempts to set a mob.
872int pc_set_hate_mob(struct map_session_data *sd, int pos, struct block_list *bl)
873{
874        int class_;
875        if (!sd || !bl || pos < 0 || pos > 2)
876                return 0;
877        if (sd->hate_mob[pos] != -1)
878        {       //Can't change hate targets.
879                clif_hate_info(sd, pos, sd->hate_mob[pos], 0); //Display current
880                return 0;
881        }
882
883        class_ = status_get_class(bl);
884        if (!pcdb_checkid(class_)) {
885                unsigned int max_hp = status_get_max_hp(bl);
886                if ((pos == 1 && max_hp < 6000) || (pos == 2 && max_hp < 20000))
887                        return 0;
888                if (pos != status_get_size(bl))
889                        return 0; //Wrong size
890        }
891        sd->hate_mob[pos] = class_;
892        pc_setglobalreg(sd,sg_info[pos].hate_var,class_+1);
893        clif_hate_info(sd, pos, class_, 1);
894        return 1;
895}
896
897/*==========================================
898 * Invoked once after the char/account/account2 registry variables are received. [Skotlex]
899 *------------------------------------------*/
900int pc_reg_received(struct map_session_data *sd)
901{
902        int i,j;
903       
904        sd->change_level = pc_readglobalreg(sd,"jobchange_level");
905        sd->die_counter = pc_readglobalreg(sd,"PC_DIE_COUNTER");
906
907        // Cash shop
908        sd->cashPoints = pc_readaccountreg(sd,"#CASHPOINTS");
909        sd->kafraPoints = pc_readaccountreg(sd,"#KAFRAPOINTS");
910
911        if ((sd->class_&MAPID_BASEMASK)==MAPID_TAEKWON)
912        {       //Better check for class rather than skill to prevent "skill resets" from unsetting this
913                sd->mission_mobid = pc_readglobalreg(sd,"TK_MISSION_ID");
914                sd->mission_count = pc_readglobalreg(sd,"TK_MISSION_COUNT");
915        }
916
917        //SG map and mob read [Komurka]
918        for(i=0;i<3;i++) //for now - someone need to make reading from txt/sql
919        {
920                if ((j = pc_readglobalreg(sd,sg_info[i].feel_var))!=0) {
921                        sd->feel_map[i].index = j;
922                        sd->feel_map[i].m = map_mapindex2mapid(j);
923                } else {
924                        sd->feel_map[i].index = 0;
925                        sd->feel_map[i].m = -1;
926                }
927                sd->hate_mob[i] = pc_readglobalreg(sd,sg_info[i].hate_var)-1;
928        }
929
930        if ((i = pc_checkskill(sd,RG_PLAGIARISM)) > 0) {
931                sd->cloneskill_id = pc_readglobalreg(sd,"CLONE_SKILL");
932                if (sd->cloneskill_id > 0) {
933                        sd->status.skill[sd->cloneskill_id].id = sd->cloneskill_id;
934                        sd->status.skill[sd->cloneskill_id].lv = pc_readglobalreg(sd,"CLONE_SKILL_LV");
935                        if (i < sd->status.skill[sd->cloneskill_id].lv)
936                                sd->status.skill[sd->cloneskill_id].lv = i;
937                        sd->status.skill[sd->cloneskill_id].flag = 13;  //cloneskill flag                       
938                }
939        }
940
941        //Weird... maybe registries were reloaded?
942        if (sd->state.active)
943                return 0;
944        sd->state.active = 1;
945
946        if (sd->status.party_id)
947                party_member_joined(sd);
948        if (sd->status.guild_id)
949                guild_member_joined(sd);
950       
951        // pet
952        if (sd->status.pet_id > 0)
953                intif_request_petdata(sd->status.account_id, sd->status.char_id, sd->status.pet_id);
954
955        // Homunculus [albator]
956        if (sd->status.hom_id > 0)
957                intif_homunculus_requestload(sd->status.account_id, sd->status.hom_id);
958
959        map_addiddb(&sd->bl);
960        map_delnickdb(sd->status.char_id, sd->status.name);
961        if (!chrif_auth_finished(sd))
962                ShowError("pc_reg_received: Failed to properly remove player %d:%d from logging db!\n", sd->status.account_id, sd->status.char_id);
963
964        status_calc_pc(sd,1);
965        chrif_scdata_request(sd->status.account_id, sd->status.char_id);
966
967#ifndef TXT_ONLY
968        intif_Mail_requestinbox(sd->status.char_id, 0); // MAIL SYSTEM - Request Mail Inbox
969        intif_request_questlog(sd);
970#endif
971
972        if (!sd->state.connect_new && sd->fd)
973        {       //Character already loaded map! Gotta trigger LoadEndAck manually.
974                sd->state.connect_new = 1;
975                clif_parse_LoadEndAck(sd->fd, sd);
976        }
977        return 1;
978}
979
980static int pc_calc_skillpoint(struct map_session_data* sd)
981{
982        int  i,skill,inf2,skill_point=0;
983
984        nullpo_retr(0, sd);
985
986        for(i=1;i<MAX_SKILL;i++){
987                if( (skill = pc_checkskill(sd,i)) > 0) {
988                        inf2 = skill_get_inf2(i);
989                        if((!(inf2&INF2_QUEST_SKILL) || battle_config.quest_skill_learn) &&
990                                !(inf2&(INF2_WEDDING_SKILL|INF2_SPIRIT_SKILL)) //Do not count wedding/link skills. [Skotlex]
991                                ) {
992                                if(!sd->status.skill[i].flag)
993                                        skill_point += skill;
994                                else if(sd->status.skill[i].flag > 2 && sd->status.skill[i].flag != 13) {
995                                        skill_point += (sd->status.skill[i].flag - 2);
996                                }
997                        }
998                }
999        }
1000
1001        return skill_point;
1002}
1003
1004
1005/*==========================================
1006 * ?‚Š‚ç‚ê‚éƒXƒLƒ‹‚ÌŒvŽZ
1007 *------------------------------------------*/
1008int pc_calc_skilltree(struct map_session_data *sd)
1009{
1010        int i,id=0,flag;
1011        int c=0;
1012
1013        nullpo_retr(0, sd);
1014        i = pc_calc_skilltree_normalize_job(sd);
1015        c = pc_mapid2jobid(i, sd->status.sex);
1016        if (c == -1) { //Unable to normalize job??
1017                ShowError("pc_calc_skilltree: Unable to normalize job %d for character %s (%d:%d)\n", i, sd->status.name, sd->status.account_id, sd->status.char_id);
1018                return 1;
1019        }
1020        c = pc_class2idx(c);
1021        for(i=0;i<MAX_SKILL;i++){ 
1022                if (sd->status.skill[i].flag != 13) //Don't touch plagiarized skills
1023                        sd->status.skill[i].id=0; //First clear skills.
1024        }
1025
1026        for(i=0;i<MAX_SKILL;i++){ 
1027                if (sd->status.skill[i].flag && sd->status.skill[i].flag != 13){ //Restore original level of skills after deleting earned skills.       
1028                        sd->status.skill[i].lv=(sd->status.skill[i].flag==1)?0:sd->status.skill[i].flag-2;
1029                        sd->status.skill[i].flag=0;
1030                }
1031                if(sd->sc.count && sd->sc.data[SC_SPIRIT] && sd->sc.data[SC_SPIRIT]->val2 == SL_BARDDANCER && i >= DC_HUMMING && i<= DC_SERVICEFORYOU)
1032                { //Enable Bard/Dancer spirit linked skills.
1033                        if (sd->status.sex) { //Link dancer skills to bard.
1034                                sd->status.skill[i].id=i;
1035                                sd->status.skill[i].lv=sd->status.skill[i-8].lv; // Set the level to the same as the linking skill
1036                                sd->status.skill[i].flag=1; // Tag it as a non-savable, non-uppable, bonus skill
1037                        } else { //Link bard skills to dancer.
1038                                sd->status.skill[i-8].id=i-8;
1039                                sd->status.skill[i-8].lv=sd->status.skill[i].lv; // Set the level to the same as the linking skill
1040                                sd->status.skill[i-8].flag=1; // Tag it as a non-savable, non-uppable, bonus skill
1041                        }
1042                }
1043        }
1044
1045        if (battle_config.gm_allskill > 0 && pc_isGM(sd) >= battle_config.gm_allskill){
1046                for(i=0;i<MAX_SKILL;i++){
1047                        if (skill_get_inf2(i)&(INF2_NPC_SKILL|INF2_GUILD_SKILL)) //Only skills you can't have are npc/guild ones
1048                                continue;
1049                        if (skill_get_max(i) > 0)
1050                                sd->status.skill[i].id=i;
1051                }
1052                return 0;
1053        }
1054
1055        do {
1056                flag = 0;
1057                for(i = 0; i < MAX_SKILL_TREE && (id = skill_tree[c][i].id) > 0; i++) {
1058                        int j, f, k, inf2;
1059
1060                        if(sd->status.skill[id].id)
1061                                continue; //Skill already known.
1062
1063                        f = 1;
1064                        if(!battle_config.skillfree) {
1065                                for(j = 0; j < 5; j++) {
1066                                        if((k=skill_tree[c][i].need[j].id))
1067                                        {
1068                                                if (!sd->status.skill[k].id || sd->status.skill[k].flag == 13)
1069                                                        k = 0; //Not learned.
1070                                                else if (sd->status.skill[k].flag) //Real lerned level
1071                                                        k = sd->status.skill[skill_tree[c][i].need[j].id].flag-2;
1072                                                else
1073                                                        k = pc_checkskill(sd,k);
1074                                                if (k < skill_tree[c][i].need[j].lv)
1075                                                {
1076                                                        f=0;
1077                                                        break;
1078                                                }
1079                                        }
1080                                }
1081                                if (sd->status.job_level < skill_tree[c][i].joblv)
1082                                        f = 0; // job level requirement wasn't satisfied
1083                        }
1084
1085                        if (f) {
1086                                inf2 = skill_get_inf2(id);
1087
1088                                if(!sd->status.skill[id].lv && (
1089                                        (inf2&INF2_QUEST_SKILL && !battle_config.quest_skill_learn) ||
1090                                        inf2&INF2_WEDDING_SKILL ||
1091                                        (inf2&INF2_SPIRIT_SKILL && !sd->sc.data[SC_SPIRIT])
1092                                ))
1093                                        continue; //Cannot be learned via normal means. Note this check DOES allows raising already known skills.
1094
1095                                sd->status.skill[id].id = id;
1096
1097                                if(inf2&INF2_SPIRIT_SKILL)
1098                                {       //Spirit skills cannot be learned, they will only show up on your tree when you get buffed.
1099                                        sd->status.skill[id].lv = 1; // need to manually specify a skill level
1100                                        sd->status.skill[id].flag = 1; //So it is not saved, and tagged as a "bonus" skill.
1101                                }
1102                                flag = 1; // skill list has changed, perform another pass
1103                        }
1104                }
1105        } while(flag);
1106
1107        if ((sd->class_&MAPID_UPPERMASK) == MAPID_TAEKWON && sd->status.base_level >= 90 && pc_famerank(sd->status.char_id, MAPID_TAEKWON)) {
1108                //Grant all Taekwon Tree, but only as bonus skills in case they drop from ranking. [Skotlex]
1109                for(i=0;i < MAX_SKILL_TREE && (id=skill_tree[c][i].id)>0;i++){
1110                        if ((skill_get_inf2(id)&(INF2_QUEST_SKILL|INF2_WEDDING_SKILL)))
1111                                continue; //Do not include Quest/Wedding skills.
1112                        if(sd->status.skill[id].id==0 ){
1113                                sd->status.skill[id].id=id;
1114                                sd->status.skill[id].flag=1; //So it is not saved, and tagged as a "bonus" skill.
1115                        } else
1116                                sd->status.skill[id].flag=sd->status.skill[id].lv+2; 
1117                        sd->status.skill[id].lv= skill_tree_get_max(id, sd->status.class_);
1118                }
1119        }
1120
1121        return 0;
1122}
1123
1124//Checks if you can learn a new skill after having leveled up a skill.
1125static void pc_check_skilltree(struct map_session_data *sd, int skill)
1126{
1127        int i,id=0,flag;
1128        int c=0;
1129
1130        if(battle_config.skillfree)
1131                return; //Function serves no purpose if this is set
1132       
1133        i = pc_calc_skilltree_normalize_job(sd);
1134        c = pc_mapid2jobid(i, sd->status.sex);
1135        if (c == -1) { //Unable to normalize job??
1136                ShowError("pc_check_skilltree: Unable to normalize job %d for character %s (%d:%d)\n", i, sd->status.name, sd->status.account_id, sd->status.char_id);
1137                return;
1138        }
1139        c = pc_class2idx(c);
1140        do {
1141                flag=0;
1142                for(i=0;i < MAX_SKILL_TREE && (id=skill_tree[c][i].id)>0;i++){
1143                        int j,f=1, k;
1144
1145                        if(sd->status.skill[id].id) //Already learned
1146                                continue;
1147                       
1148                        for(j=0;j<5;j++) {
1149                                if((k=skill_tree[c][i].need[j].id))
1150                                {
1151                                        if (!sd->status.skill[k].id || sd->status.skill[k].flag == 13)
1152                                                k = 0; //Not learned.
1153                                        else if (sd->status.skill[k].flag) //Real lerned level
1154                                                k = sd->status.skill[skill_tree[c][i].need[j].id].flag-2;
1155                                        else
1156                                                k = pc_checkskill(sd,k);
1157                                        if (k < skill_tree[c][i].need[j].lv)
1158                                        {
1159                                                f=0;
1160                                                break;
1161                                        }
1162                                }
1163                        }
1164                        if (!f)
1165                                continue;
1166                        if (sd->status.job_level < skill_tree[c][i].joblv)
1167                                continue;
1168                       
1169                        j = skill_get_inf2(id);
1170                        if(!sd->status.skill[id].lv && (
1171                                (j&INF2_QUEST_SKILL && !battle_config.quest_skill_learn) ||
1172                                j&INF2_WEDDING_SKILL ||
1173                                (j&INF2_SPIRIT_SKILL && !sd->sc.data[SC_SPIRIT])
1174                        ))
1175                                continue; //Cannot be learned via normal means.
1176
1177                        sd->status.skill[id].id=id;
1178                        flag=1;
1179                }
1180        } while(flag);
1181}
1182
1183// Make sure all the skills are in the correct condition
1184// before persisting to the backend.. [MouseJstr]
1185int pc_clean_skilltree(struct map_session_data *sd)
1186{
1187        int i;
1188        for (i = 0; i < MAX_SKILL; i++){
1189                if (sd->status.skill[i].flag == 13 || sd->status.skill[i].flag == 1)
1190                {
1191                        sd->status.skill[i].id = 0;
1192                        sd->status.skill[i].lv = 0;
1193                        sd->status.skill[i].flag = 0;
1194                } else if (sd->status.skill[i].flag){
1195                        sd->status.skill[i].lv = sd->status.skill[i].flag-2;
1196                        sd->status.skill[i].flag = 0;
1197                }
1198        }
1199
1200        return 0;
1201}
1202
1203int pc_calc_skilltree_normalize_job(struct map_session_data *sd)
1204{
1205        int skill_point;
1206        int c = sd->class_;
1207       
1208        if (!battle_config.skillup_limit)
1209                return c;
1210       
1211        skill_point = pc_calc_skillpoint(sd);
1212        if(pc_checkskill(sd, NV_BASIC) < 9) //Consider Novice Tree when you don't have NV_BASIC maxed.
1213                c = MAPID_NOVICE;
1214        else
1215        //Do not send S. Novices to first class (Novice)
1216        if ((sd->class_&JOBL_2) && (sd->class_&MAPID_UPPERMASK) != MAPID_SUPER_NOVICE &&
1217                sd->status.skill_point >= (int)sd->status.job_level &&
1218                ((sd->change_level > 0 && skill_point < sd->change_level+8) || skill_point < 58)) {
1219                //Send it to first class.
1220                c &= MAPID_BASEMASK;
1221        }
1222        if (sd->class_&JOBL_UPPER) //Convert to Upper
1223                c |= JOBL_UPPER;
1224        else if (sd->class_&JOBL_BABY) //Convert to Baby
1225                c |= JOBL_BABY;
1226
1227        return c;
1228}
1229
1230/*==========================================
1231 * Updates the weight status
1232 *------------------------------------------
1233 * 1: overweight 50%
1234 * 2: overweight 90%
1235 * It's assumed that SC_WEIGHT50 and SC_WEIGHT90 are only started/stopped here.
1236 */
1237int pc_updateweightstatus(struct map_session_data *sd)
1238{
1239        int old_overweight;
1240        int new_overweight;
1241
1242        nullpo_retr(1, sd);
1243
1244        old_overweight = (sd->sc.data[SC_WEIGHT90]) ? 2 : (sd->sc.data[SC_WEIGHT50]) ? 1 : 0;
1245        new_overweight = (pc_is90overweight(sd)) ? 2 : (pc_is50overweight(sd)) ? 1 : 0;
1246
1247        if( old_overweight == new_overweight )
1248                return 0; // no change
1249
1250        // stop old status change
1251        if( old_overweight == 1 )
1252                status_change_end(&sd->bl, SC_WEIGHT50, -1);
1253        else if( old_overweight == 2 )
1254                status_change_end(&sd->bl, SC_WEIGHT90, -1);
1255
1256        // start new status change
1257        if( new_overweight == 1 )
1258                sc_start(&sd->bl, SC_WEIGHT50, 100, 0, 0);
1259        else if( new_overweight == 2 )
1260                sc_start(&sd->bl, SC_WEIGHT90, 100, 0, 0);
1261
1262        // update overweight status
1263        sd->regen.state.overweight = new_overweight;
1264
1265        return 0;
1266}
1267
1268int pc_disguise(struct map_session_data *sd, int class_)
1269{
1270        if (!class_ && !sd->disguise)
1271                return 0;
1272        if (class_ && sd->disguise == class_)
1273                return 0;
1274
1275        if(sd->sc.option&OPTION_INVISIBLE)
1276        {       //Character is invisible. Stealth class-change. [Skotlex]
1277                sd->disguise = class_; //viewdata is set on uncloaking.
1278                return 2;
1279        }
1280
1281        if (sd->bl.prev != NULL) {
1282                pc_stop_walking(sd, 0);
1283                clif_clearunit_area(&sd->bl, 0);
1284        }
1285
1286        if (!class_) {
1287                sd->disguise = 0;
1288                class_ = sd->status.class_;
1289        } else
1290                sd->disguise=class_;
1291
1292        status_set_viewdata(&sd->bl, class_);
1293        clif_changeoption(&sd->bl);
1294
1295        if (sd->bl.prev != NULL) {
1296                clif_spawn(&sd->bl);
1297                if (class_ == sd->status.class_ && pc_iscarton(sd))
1298                {       //It seems the cart info is lost on undisguise.
1299                        clif_cartlist(sd);
1300                        clif_updatestatus(sd,SP_CARTINFO);
1301                }
1302        }
1303        return 1;
1304}
1305
1306int pc_autoscript_add(struct s_autoscript *scripts, int max, short rate, short flag, struct script_code *script)
1307{
1308        int i;
1309        ARR_FIND(0, max, i, scripts[i].script == NULL);
1310        if (i == max) {
1311                ShowWarning("pc_autoscript_bonus: Reached max (%d) number of autoscripts per character!\n", max);
1312                return 0;
1313        }
1314        scripts[i].script = script;
1315        scripts[i].rate = rate;
1316        //Auto-update flag value.
1317        if (!(flag&BF_RANGEMASK)) flag|=BF_SHORT|BF_LONG; //No range defined? Use both.
1318        if (!(flag&BF_WEAPONMASK)) flag|=BF_WEAPON; //No attack type defined? Use weapon.
1319        if (!(flag&BF_SKILLMASK)) {
1320                if (flag&(BF_MAGIC|BF_MISC)) flag|=BF_SKILL; //These two would never trigger without BF_SKILL
1321                if (flag&BF_WEAPON) flag|=BF_NORMAL;
1322        }
1323        scripts[i].flag = flag;
1324        return 1;
1325}
1326
1327void pc_autoscript_clear(struct s_autoscript *scripts, int max)
1328{
1329        int i;
1330        for (i = 0; i < max && scripts[i].script; i++)
1331                script_free_code(scripts[i].script);
1332        memset(scripts, 0, i*sizeof(struct s_autoscript));
1333}
1334
1335static int pc_bonus_autospell_del(struct s_autospell* spell, int max, short id, short lv, short rate, short card_id)
1336{
1337        int i, j;
1338        for(i=max-1; i>=0 && !spell[i].id; i--);
1339        if (i<0) return 0; //Nothing to substract from.
1340
1341        j = i;
1342        for(; i>=0 && rate>0; i--)
1343        {
1344                if (spell[i].id != id || spell[i].lv != lv) continue;
1345                if (rate >= spell[i].rate) {
1346                        rate-= spell[i].rate;
1347                        spell[i].rate = 0;
1348                        memmove(&spell[i], &spell[j], sizeof(struct s_autospell));
1349                        memset(&spell[j], 0, sizeof(struct s_autospell));
1350                        j--;
1351                } else {
1352                        spell[i].rate -= rate;
1353                        rate = 0;
1354                }
1355        }
1356        if (rate > 0 && ++j < max)
1357        {        //Tag this as "pending" autospell to remove.
1358                spell[j].id = id;
1359                spell[j].lv = lv;
1360                spell[j].rate = -rate;
1361                spell[j].card_id = card_id;
1362        }
1363        return rate;
1364}
1365
1366static int pc_bonus_autospell(struct s_autospell *spell, int max, short id, short lv, short rate, short flag, short card_id)
1367{
1368        int i;
1369        if (rate < 0) return //Remove the autobonus.
1370                pc_bonus_autospell_del(spell, max, id, lv, -rate, card_id);
1371
1372        for (i = 0; i < max && spell[i].id; i++) {
1373                if ((spell[i].card_id == card_id || spell[i].rate < 0) &&
1374                        spell[i].id == id && spell[i].lv == lv)
1375                {
1376                        if (!battle_config.autospell_stacking && spell[i].rate > 0)
1377                                return 0;
1378                        rate += spell[i].rate;
1379                        break;
1380                }
1381        }
1382        if (i == max) {
1383                ShowWarning("pc_bonus: Reached max (%d) number of autospells per character!\n", max);
1384                return 0;
1385        }
1386        spell[i].id = id;
1387        spell[i].lv = lv;
1388        spell[i].rate = rate;
1389        //Auto-update flag value.
1390        if (!(flag&BF_RANGEMASK)) flag|=BF_SHORT|BF_LONG; //No range defined? Use both.
1391        if (!(flag&BF_WEAPONMASK)) flag|=BF_WEAPON; //No attack type defined? Use weapon.
1392        if (!(flag&BF_SKILLMASK)) {
1393                if (flag&(BF_MAGIC|BF_MISC)) flag|=BF_SKILL; //These two would never trigger without BF_SKILL
1394                if (flag&BF_WEAPON) flag|=BF_NORMAL; //By default autospells should only trigger on normal weapon attacks.
1395        }
1396        spell[i].flag|= flag;
1397        spell[i].card_id = card_id;
1398        return 1;
1399}
1400
1401static int pc_bonus_addeff(struct s_addeffect* effect, int max, enum sc_type id, short rate, short arrow_rate, unsigned char flag)
1402{
1403        int i;
1404        if (!(flag&(ATF_SHORT|ATF_LONG)))
1405                flag|=ATF_SHORT|ATF_LONG; //Default range: both
1406        if (!(flag&(ATF_TARGET|ATF_SELF)))
1407                flag|=ATF_TARGET; //Default target: enemy.
1408
1409        for (i = 0; i < max && effect[i].flag; i++) {
1410                if (effect[i].id == id && effect[i].flag == flag)
1411                {
1412                        effect[i].rate += rate;
1413                        effect[i].arrow_rate += arrow_rate;
1414                        return 1;
1415                }
1416        }
1417        if (i == max) {
1418                ShowWarning("pc_bonus: Reached max (%d) number of add effects per character!\n", max);
1419                return 0;
1420        }
1421        effect[i].id = id;
1422        effect[i].rate = rate;
1423        effect[i].arrow_rate = arrow_rate;
1424        effect[i].flag = flag;
1425        return 1;
1426}
1427
1428static int pc_bonus_item_drop(struct s_add_drop *drop, const short max, short id, short group, int race, int rate)
1429{
1430        int i;
1431        //Apply config rate adjustment settings.
1432        if (rate >= 0) { //Absolute drop.
1433                if (battle_config.item_rate_adddrop != 100)
1434                        rate = rate*battle_config.item_rate_adddrop/100;
1435                if (rate < battle_config.item_drop_adddrop_min)
1436                        rate = battle_config.item_drop_adddrop_min;
1437                else if (rate > battle_config.item_drop_adddrop_max)
1438                        rate = battle_config.item_drop_adddrop_max;
1439        } else { //Relative drop, max/min limits are applied at drop time.
1440                if (battle_config.item_rate_adddrop != 100)
1441                        rate = rate*battle_config.item_rate_adddrop/100;
1442                if (rate > -1)
1443                        rate = -1;
1444        }
1445        for(i = 0; i < max && (drop[i].id || drop[i].group); i++) {
1446                if(
1447                        (id && drop[i].id == id) ||
1448                        (group && drop[i].group == group)
1449                ) {
1450                        drop[i].race |= race;
1451                        if(drop[i].rate > 0 && rate > 0)
1452                        {       //Both are absolute rates.
1453                                if (drop[i].rate < rate)
1454                                        drop[i].rate = rate;
1455                        } else
1456                        if(drop[i].rate < 0 && rate < 0) {
1457                                //Both are relative rates.
1458                                if (drop[i].rate > rate)
1459                                        drop[i].rate = rate;
1460                        } else if (rate < 0) //Give preference to relative rate.
1461                                        drop[i].rate = rate;
1462                        return 1;
1463                }
1464        }
1465        if(i == max) {
1466                ShowWarning("pc_bonus: Reached max (%d) number of added drops per character!\n", max);
1467                return 0;
1468        }
1469        drop[i].id = id;
1470        drop[i].group = group;
1471        drop[i].race |= race;
1472        drop[i].rate = rate;
1473        return 1;
1474}
1475
1476/*==========================================
1477 * ? ”õ•i‚É‚æ‚é”\—Í“™‚̃{?ƒiƒXÝ’è
1478 *------------------------------------------*/
1479int pc_bonus(struct map_session_data *sd,int type,int val)
1480{
1481        struct status_data *status;
1482        int bonus;
1483        nullpo_retr(0, sd);
1484
1485        status = &sd->base_status;
1486
1487        switch(type){
1488        case SP_STR:
1489        case SP_AGI:
1490        case SP_VIT:
1491        case SP_INT:
1492        case SP_DEX:
1493        case SP_LUK:
1494                if(sd->state.lr_flag != 2)
1495                        sd->param_bonus[type-SP_STR]+=val;
1496                break;
1497        case SP_ATK1:
1498                if(!sd->state.lr_flag) {
1499                        bonus = status->rhw.atk + val;
1500                        status->rhw.atk = cap_value(bonus, 0, USHRT_MAX);
1501                }
1502                else if(sd->state.lr_flag == 1) {
1503                        bonus = status->lhw.atk + val;
1504                        status->lhw.atk =  cap_value(bonus, 0, USHRT_MAX);
1505                }
1506                break;
1507        case SP_ATK2:
1508                if(!sd->state.lr_flag) {
1509                        bonus = status->rhw.atk2 + val;
1510                        status->rhw.atk2 = cap_value(bonus, 0, USHRT_MAX);
1511                }
1512                else if(sd->state.lr_flag == 1) {
1513                        bonus = status->lhw.atk2 + val;
1514                        status->lhw.atk2 =  cap_value(bonus, 0, USHRT_MAX);
1515                }
1516                break;
1517        case SP_BASE_ATK:
1518                if(sd->state.lr_flag != 2) {
1519                        bonus = status->batk + val;
1520                        status->batk = cap_value(bonus, 0, USHRT_MAX);
1521                }
1522                break;
1523        case SP_DEF1:
1524                if(sd->state.lr_flag != 2) {
1525                        bonus = status->def + val;
1526                        status->def = cap_value(bonus, CHAR_MIN, CHAR_MAX);
1527                }
1528                break;
1529        case SP_DEF2:
1530                if(sd->state.lr_flag != 2) {
1531                        bonus = status->def2 + val;
1532                        status->def2 = cap_value(bonus, SHRT_MIN, SHRT_MAX);
1533                }
1534                break;
1535        case SP_MDEF1:
1536                if(sd->state.lr_flag != 2) {
1537                        bonus = status->mdef + val;
1538                        status->mdef = cap_value(bonus, CHAR_MIN, CHAR_MAX);
1539                }
1540                break;
1541        case SP_MDEF2:
1542                if(sd->state.lr_flag != 2) {
1543                        bonus = status->mdef2 + val;
1544                        status->mdef2 = cap_value(bonus, SHRT_MIN, SHRT_MAX);
1545                }
1546                break;
1547        case SP_HIT:
1548                if(sd->state.lr_flag != 2) {
1549                        bonus = status->hit + val;
1550                        status->hit = cap_value(bonus, SHRT_MIN, SHRT_MAX);
1551                } else
1552                        sd->arrow_hit+=val;
1553                break;
1554        case SP_FLEE1:
1555                if(sd->state.lr_flag != 2) {
1556                        bonus = status->flee + val;
1557                        status->flee = cap_value(bonus, SHRT_MIN, SHRT_MAX);
1558                }
1559                break;
1560        case SP_FLEE2:
1561                if(sd->state.lr_flag != 2) {
1562                        bonus = status->flee2 + val*10;
1563                        status->flee2 = cap_value(bonus, SHRT_MIN, SHRT_MAX);
1564                }
1565                break;
1566        case SP_CRITICAL:
1567                if(sd->state.lr_flag != 2) {
1568                        bonus = status->cri + val*10;
1569                        status->cri = cap_value(bonus, SHRT_MIN, SHRT_MAX);
1570                } else
1571                        sd->arrow_cri += val*10;
1572                break;
1573        case SP_ATKELE:
1574                if(val >= ELE_MAX) {
1575                        ShowError("pc_bonus: SP_ATKELE: Invalid element %d\n", val);
1576                        break;
1577                }
1578                switch (sd->state.lr_flag)
1579                {
1580                case 2:
1581                        switch (sd->status.weapon) {
1582                                case W_BOW:
1583                                case W_REVOLVER:
1584                                case W_RIFLE:
1585                                case W_GATLING:
1586                                case W_SHOTGUN:
1587                                case W_GRENADE:
1588                                        //Become weapon element.
1589                                        status->rhw.ele=val;
1590                                        break;
1591                                default: //Become arrow element.
1592                                        sd->arrow_ele=val;
1593                                        break;
1594                        }
1595                        break;
1596                case 1:
1597                        status->lhw.ele=val;
1598                        break;
1599                default:
1600                        status->rhw.ele=val;
1601                        break;
1602                }
1603                break;
1604        case SP_DEFELE:
1605                if(val >= ELE_MAX) {
1606                        ShowError("pc_bonus: SP_DEFELE: Invalid element %d\n", val);
1607                        break;
1608                }
1609                if(sd->state.lr_flag != 2)
1610                        status->def_ele=val;
1611                break;
1612        case SP_MAXHP:
1613                if(sd->state.lr_flag == 2)
1614                        break;
1615                val += (int)status->max_hp;
1616                //Negative bonuses will underflow, this will be handled in status_calc_pc through casting
1617                //If this is called outside of status_calc_pc, you'd better pray they do not underflow and end with UINT_MAX max_hp.
1618                status->max_hp = (unsigned int)val;
1619                break;
1620        case SP_MAXSP:
1621                if(sd->state.lr_flag == 2) 
1622                        break;
1623                val += (int)status->max_sp;
1624                status->max_sp = (unsigned int)val;
1625                break;
1626        case SP_CASTRATE:
1627                if(sd->state.lr_flag != 2)
1628                        sd->castrate+=val;
1629                break;
1630        case SP_MAXHPRATE:
1631                if(sd->state.lr_flag != 2)
1632                        sd->hprate+=val;
1633                break;
1634        case SP_MAXSPRATE:
1635                if(sd->state.lr_flag != 2)
1636                        sd->sprate+=val;
1637                break;
1638        case SP_SPRATE:
1639                if(sd->state.lr_flag != 2)
1640                        sd->dsprate+=val;
1641                break;
1642        case SP_ATTACKRANGE:
1643                switch (sd->state.lr_flag) {
1644                case 2:
1645                        switch (sd->status.weapon) {
1646                                case W_BOW:
1647                                case W_REVOLVER:
1648                                case W_RIFLE:
1649                                case W_GATLING:
1650                                case W_SHOTGUN:
1651                                case W_GRENADE:
1652                                        status->rhw.range += val;
1653                        }
1654                        break;
1655                case 1:
1656                        status->lhw.range += val;
1657                        break;
1658                default:
1659                        status->rhw.range += val;
1660                        break;
1661                }
1662                break;
1663        case SP_SPEED_RATE:     //Non stackable increase
1664                if(sd->state.lr_flag != 2)
1665                        sd->speed_rate = min(sd->speed_rate, -val);
1666                break;
1667        case SP_SPEED_ADDRATE:  //Stackable increase
1668                if(sd->state.lr_flag != 2)
1669                        sd->speed_add_rate -= val;
1670                break;
1671        case SP_ASPD:   //Raw increase
1672                if(sd->state.lr_flag != 2)
1673                        sd->aspd_add -= 10*val;
1674                break;
1675        case SP_ASPD_RATE:      //Stackable increase - Made it linear as per rodatazone
1676                if(sd->state.lr_flag != 2)
1677                        status->aspd_rate -= 10*val;
1678                break;
1679        case SP_HP_RECOV_RATE:
1680                if(sd->state.lr_flag != 2)
1681                        sd->hprecov_rate += val;
1682                break;
1683        case SP_SP_RECOV_RATE:
1684                if(sd->state.lr_flag != 2)
1685                        sd->sprecov_rate += val;
1686                break;
1687        case SP_CRITICAL_DEF:
1688                if(sd->state.lr_flag != 2)
1689                        sd->critical_def += val;
1690                break;
1691        case SP_NEAR_ATK_DEF:
1692                if(sd->state.lr_flag != 2)
1693                        sd->near_attack_def_rate += val;
1694                break;
1695        case SP_LONG_ATK_DEF:
1696                if(sd->state.lr_flag != 2)
1697                        sd->long_attack_def_rate += val;
1698                break;
1699        case SP_DOUBLE_RATE:
1700                if(sd->state.lr_flag == 0 && sd->double_rate < val)
1701                        sd->double_rate = val;
1702                break;
1703        case SP_DOUBLE_ADD_RATE:
1704                if(sd->state.lr_flag == 0)
1705                        sd->double_add_rate += val;
1706                break;
1707        case SP_MATK_RATE:
1708                if(sd->state.lr_flag != 2)
1709                        sd->matk_rate += val;
1710                break;
1711        case SP_IGNORE_DEF_ELE:
1712                if(val >= ELE_MAX) {
1713                        ShowError("pc_bonus: SP_IGNORE_DEF_ELE: Invalid element %d\n", val);
1714                        break;
1715                }
1716                if(!sd->state.lr_flag)
1717                        sd->right_weapon.ignore_def_ele |= 1<<val;
1718                else if(sd->state.lr_flag == 1)
1719                        sd->left_weapon.ignore_def_ele |= 1<<val;
1720                break;
1721        case SP_IGNORE_DEF_RACE:
1722                if(!sd->state.lr_flag)
1723                        sd->right_weapon.ignore_def_race |= 1<<val;
1724                else if(sd->state.lr_flag == 1)
1725                        sd->left_weapon.ignore_def_race |= 1<<val;
1726                break;
1727        case SP_ATK_RATE:
1728                if(sd->state.lr_flag != 2)
1729                        sd->atk_rate += val;
1730                break;
1731        case SP_MAGIC_ATK_DEF:
1732                if(sd->state.lr_flag != 2)
1733                        sd->magic_def_rate += val;
1734                break;
1735        case SP_MISC_ATK_DEF:
1736                if(sd->state.lr_flag != 2)
1737                        sd->misc_def_rate += val;
1738                break;
1739        case SP_IGNORE_MDEF_RATE:
1740                if(sd->state.lr_flag != 2) {
1741                        sd->ignore_mdef[RC_NONBOSS] += val;
1742                        sd->ignore_mdef[RC_BOSS] += val;
1743                }
1744                break;
1745        case SP_IGNORE_MDEF_ELE:
1746                if(val >= ELE_MAX) {
1747                        ShowError("pc_bonus: SP_IGNORE_MDEF_ELE: Invalid element %d\n", val);
1748                        break;
1749                }
1750                if(sd->state.lr_flag != 2)
1751                        sd->ignore_mdef_ele |= 1<<val;
1752                break;
1753        case SP_IGNORE_MDEF_RACE:
1754                if(sd->state.lr_flag != 2)
1755                        sd->ignore_mdef_race |= 1<<val;
1756                break;
1757        case SP_PERFECT_HIT_RATE:
1758                if(sd->state.lr_flag != 2 && sd->perfect_hit < val)
1759                        sd->perfect_hit = val;
1760                break;
1761        case SP_PERFECT_HIT_ADD_RATE:
1762                if(sd->state.lr_flag != 2)
1763                        sd->perfect_hit_add += val;
1764                break;
1765        case SP_CRITICAL_RATE:
1766                if(sd->state.lr_flag != 2)
1767                        sd->critical_rate+=val;
1768                break;
1769        case SP_DEF_RATIO_ATK_ELE:
1770                if(val >= ELE_MAX) {
1771                        ShowError("pc_bonus: SP_DEF_RATIO_ATK_ELE: Invalid element %d\n", val);
1772                        break;
1773                }
1774                if(!sd->state.lr_flag)
1775                        sd->right_weapon.def_ratio_atk_ele |= 1<<val;
1776                else if(sd->state.lr_flag == 1)
1777                        sd->left_weapon.def_ratio_atk_ele |= 1<<val;
1778                break;
1779        case SP_DEF_RATIO_ATK_RACE:
1780                if(val >= RC_MAX) {
1781                        ShowError("pc_bonus: SP_DEF_RATIO_ATK_RACE: Invalid race %d\n", val);
1782                        break;
1783                }
1784                if(!sd->state.lr_flag)
1785                        sd->right_weapon.def_ratio_atk_race |= 1<<val;
1786                else if(sd->state.lr_flag == 1)
1787                        sd->left_weapon.def_ratio_atk_race |= 1<<val;
1788                break;
1789        case SP_HIT_RATE:
1790                if(sd->state.lr_flag != 2)
1791                        sd->hit_rate += val;
1792                break;
1793        case SP_FLEE_RATE:
1794                if(sd->state.lr_flag != 2)
1795                        sd->flee_rate += val;
1796                break;
1797        case SP_FLEE2_RATE:
1798                if(sd->state.lr_flag != 2)
1799                        sd->flee2_rate += val;
1800                break;
1801        case SP_DEF_RATE:
1802                if(sd->state.lr_flag != 2)
1803                        sd->def_rate += val;
1804                break;
1805        case SP_DEF2_RATE:
1806                if(sd->state.lr_flag != 2)
1807                        sd->def2_rate += val;
1808                break;
1809        case SP_MDEF_RATE:
1810                if(sd->state.lr_flag != 2)
1811                        sd->mdef_rate += val;
1812                break;
1813        case SP_MDEF2_RATE:
1814                if(sd->state.lr_flag != 2)
1815                        sd->mdef2_rate += val;
1816                break;
1817        case SP_RESTART_FULL_RECOVER:
1818                if(sd->state.lr_flag != 2)
1819                        sd->special_state.restart_full_recover = 1;
1820                break;
1821        case SP_NO_CASTCANCEL:
1822                if(sd->state.lr_flag != 2)
1823                        sd->special_state.no_castcancel = 1;
1824                break;
1825        case SP_NO_CASTCANCEL2:
1826                if(sd->state.lr_flag != 2)
1827                        sd->special_state.no_castcancel2 = 1;
1828                break;
1829        case SP_NO_SIZEFIX:
1830                if(sd->state.lr_flag != 2)
1831                        sd->special_state.no_sizefix = 1;
1832                break;
1833        case SP_NO_MAGIC_DAMAGE:
1834                if(sd->state.lr_flag == 2)
1835                        break;
1836                val+= sd->special_state.no_magic_damage;
1837                sd->special_state.no_magic_damage = cap_value(val,0,100);
1838                break;
1839        case SP_NO_WEAPON_DAMAGE:
1840                if(sd->state.lr_flag == 2)
1841                        break;
1842                val+= sd->special_state.no_weapon_damage;
1843                sd->special_state.no_weapon_damage = cap_value(val,0,100);
1844                break;
1845        case SP_NO_MISC_DAMAGE:
1846                if(sd->state.lr_flag == 2)
1847                        break;
1848                val+= sd->special_state.no_misc_damage;
1849                sd->special_state.no_misc_damage = cap_value(val,0,100);
1850                break;
1851        case SP_NO_GEMSTONE:
1852                if(sd->state.lr_flag != 2)
1853                        sd->special_state.no_gemstone = 1;
1854                break;
1855        case SP_INTRAVISION: // Maya Purple Card effect allowing to see Hiding/Cloaking people [DracoRPG]
1856                if(sd->state.lr_flag != 2) {
1857                        sd->special_state.intravision = 1;
1858                        clif_status_load(&sd->bl, SI_INTRAVISION, 1);
1859                }
1860                break;
1861        case SP_NO_KNOCKBACK:
1862                if(sd->state.lr_flag != 2)
1863                        sd->special_state.no_knockback = 1;
1864                break;
1865        case SP_SPLASH_RANGE:
1866                if(sd->state.lr_flag != 2 && sd->splash_range < val)
1867                        sd->splash_range = val;
1868                break;
1869        case SP_SPLASH_ADD_RANGE:
1870                if(sd->state.lr_flag != 2)
1871                        sd->splash_add_range += val;
1872                break;
1873        case SP_SHORT_WEAPON_DAMAGE_RETURN:
1874                if(sd->state.lr_flag != 2)
1875                        sd->short_weapon_damage_return += val;
1876                break;
1877        case SP_LONG_WEAPON_DAMAGE_RETURN:
1878                if(sd->state.lr_flag != 2)
1879                        sd->long_weapon_damage_return += val;
1880                break;
1881        case SP_MAGIC_DAMAGE_RETURN: //AppleGirl Was Here
1882                if(sd->state.lr_flag != 2)
1883                        sd->magic_damage_return += val;
1884                break;
1885        case SP_ALL_STATS:      // [Valaris]
1886                if(sd->state.lr_flag!=2) {
1887                        sd->param_bonus[SP_STR-SP_STR]+=val;
1888                        sd->param_bonus[SP_AGI-SP_STR]+=val;
1889                        sd->param_bonus[SP_VIT-SP_STR]+=val;
1890                        sd->param_bonus[SP_INT-SP_STR]+=val;
1891                        sd->param_bonus[SP_DEX-SP_STR]+=val;
1892                        sd->param_bonus[SP_LUK-SP_STR]+=val;
1893                }
1894                break;
1895        case SP_AGI_VIT:        // [Valaris]
1896                if(sd->state.lr_flag!=2) {
1897                        sd->param_bonus[SP_AGI-SP_STR]+=val;
1898                        sd->param_bonus[SP_VIT-SP_STR]+=val;
1899                }
1900                break;
1901        case SP_AGI_DEX_STR:    // [Valaris]
1902                if(sd->state.lr_flag!=2) {
1903                        sd->param_bonus[SP_AGI-SP_STR]+=val;
1904                        sd->param_bonus[SP_DEX-SP_STR]+=val;
1905                        sd->param_bonus[SP_STR-SP_STR]+=val;
1906                }
1907                break;
1908        case SP_PERFECT_HIDE: // [Valaris]
1909                if(sd->state.lr_flag!=2)
1910                        sd->special_state.perfect_hiding=1;
1911                break;
1912        case SP_UNBREAKABLE:
1913                if(sd->state.lr_flag!=2)
1914                        sd->unbreakable += val;
1915                break;
1916        case SP_UNBREAKABLE_WEAPON:
1917                if(sd->state.lr_flag != 2)
1918                        sd->unbreakable_equip |= EQP_WEAPON;
1919                break;
1920        case SP_UNBREAKABLE_ARMOR:
1921                if(sd->state.lr_flag != 2)
1922                        sd->unbreakable_equip |= EQP_ARMOR;
1923                break;
1924        case SP_UNBREAKABLE_HELM:
1925                if(sd->state.lr_flag != 2)
1926                        sd->unbreakable_equip |= EQP_HELM;
1927                break;
1928        case SP_UNBREAKABLE_SHIELD:
1929                if(sd->state.lr_flag != 2)
1930                        sd->unbreakable_equip |= EQP_SHIELD;
1931                break;
1932        case SP_CLASSCHANGE: // [Valaris]
1933                if(sd->state.lr_flag !=2)
1934                        sd->classchange=val;
1935                break;
1936        case SP_LONG_ATK_RATE:
1937                if(sd->state.lr_flag != 2)      //[Lupus] it should stack, too. As any other cards rate bonuses
1938                        sd->long_attack_atk_rate+=val;
1939                break;
1940        case SP_BREAK_WEAPON_RATE:
1941                if(sd->state.lr_flag != 2)
1942                        sd->break_weapon_rate+=val;
1943                break;
1944        case SP_BREAK_ARMOR_RATE:
1945                if(sd->state.lr_flag != 2)
1946                        sd->break_armor_rate+=val;
1947                break;
1948        case SP_ADD_STEAL_RATE:
1949                if(sd->state.lr_flag != 2)
1950                        sd->add_steal_rate+=val;
1951                break;
1952        case SP_DELAYRATE:
1953                if(sd->state.lr_flag != 2)
1954                        sd->delayrate+=val;
1955                break;
1956        case SP_CRIT_ATK_RATE:
1957                if(sd->state.lr_flag != 2)
1958                        sd->crit_atk_rate += val;
1959                break;
1960        case SP_NO_REGEN:
1961                if(sd->state.lr_flag != 2)
1962                        sd->regen.state.block|=val;
1963                break;
1964        case SP_UNSTRIPABLE_WEAPON:
1965                if(sd->state.lr_flag != 2)
1966                        sd->unstripable_equip |= EQP_WEAPON;
1967                break;
1968        case SP_UNSTRIPABLE:
1969        case SP_UNSTRIPABLE_ARMOR:
1970                if(sd->state.lr_flag != 2)
1971                        sd->unstripable_equip |= EQP_ARMOR;
1972                break;
1973        case SP_UNSTRIPABLE_HELM:
1974                if(sd->state.lr_flag != 2)
1975                        sd->unstripable_equip |= EQP_HELM;
1976                break;
1977        case SP_UNSTRIPABLE_SHIELD:
1978                if(sd->state.lr_flag != 2)
1979                        sd->unstripable_equip |= EQP_SHIELD;
1980                break;
1981        case SP_HP_DRAIN_VALUE:
1982                if(!sd->state.lr_flag) {
1983                        sd->right_weapon.hp_drain[RC_NONBOSS].value += val;
1984                        sd->right_weapon.hp_drain[RC_BOSS].value += val;
1985                }
1986                else if(sd->state.lr_flag == 1) {
1987                        sd->right_weapon.hp_drain[RC_NONBOSS].value += val;
1988                        sd->right_weapon.hp_drain[RC_BOSS].value += val;
1989                }
1990                break;
1991        case SP_SP_DRAIN_VALUE:
1992                if(!sd->state.lr_flag) {
1993                        sd->right_weapon.sp_drain[RC_NONBOSS].value += val;
1994                        sd->right_weapon.sp_drain[RC_BOSS].value += val;
1995                }
1996                else if(sd->state.lr_flag == 1) {
1997                        sd->left_weapon.sp_drain[RC_NONBOSS].value += val;
1998                        sd->left_weapon.sp_drain[RC_BOSS].value += val;
1999                }
2000                break;
2001        case SP_SP_GAIN_VALUE:
2002                if(!sd->state.lr_flag)
2003                        sd->sp_gain_value += val;
2004                break;
2005        case SP_HP_GAIN_VALUE:
2006                if(!sd->state.lr_flag)
2007                        sd->hp_gain_value += val;
2008                break;
2009        default:
2010                ShowWarning("pc_bonus: unknown type %d %d !\n",type,val);
2011                break;
2012        }
2013        return 0;
2014}
2015
2016/*==========================================
2017 * ? ”õ•i‚É‚æ‚é”\—Í“™‚̃{?ƒiƒXÝ’è
2018 *------------------------------------------*/
2019int pc_bonus2(struct map_session_data *sd,int type,int type2,int val)
2020{
2021        int i;
2022
2023        nullpo_retr(0, sd);
2024
2025        switch(type){
2026        case SP_ADDELE:
2027                if(type2 >= ELE_MAX) {
2028                        ShowError("pc_bonus2: SP_ADDELE: Invalid element %d\n", type2);
2029                        break;
2030                }
2031                if(!sd->state.lr_flag)
2032                        sd->right_weapon.addele[type2]+=val;
2033                else if(sd->state.lr_flag == 1)
2034                        sd->left_weapon.addele[type2]+=val;
2035                else if(sd->state.lr_flag == 2)
2036                        sd->arrow_addele[type2]+=val;
2037                break;
2038        case SP_ADDRACE:
2039                if(!sd->state.lr_flag)
2040                        sd->right_weapon.addrace[type2]+=val;
2041                else if(sd->state.lr_flag == 1)
2042                        sd->left_weapon.addrace[type2]+=val;
2043                else if(sd->state.lr_flag == 2)
2044                        sd->arrow_addrace[type2]+=val;
2045                break;
2046        case SP_ADDSIZE:
2047                if(!sd->state.lr_flag)
2048                        sd->right_weapon.addsize[type2]+=val;
2049                else if(sd->state.lr_flag == 1)
2050                        sd->left_weapon.addsize[type2]+=val;
2051                else if(sd->state.lr_flag == 2)
2052                        sd->arrow_addsize[type2]+=val;
2053                break;
2054        case SP_SUBELE:
2055                if(type2 >= ELE_MAX) {
2056                        ShowError("pc_bonus2: SP_SUBELE: Invalid element %d\n", type2);
2057                        break;
2058                }
2059                if(sd->state.lr_flag != 2)
2060                        sd->subele[type2]+=val;
2061                break;
2062        case SP_SUBRACE:
2063                if(sd->state.lr_flag != 2)
2064                        sd->subrace[type2]+=val;
2065                break;
2066        case SP_ADDEFF:
2067                if (type2 > SC_MAX) {
2068                        ShowWarning("pc_bonus2 (Add Effect): %d is not supported.\n", type2);
2069                        break;
2070                }
2071                pc_bonus_addeff(sd->addeff, ARRAYLENGTH(sd->addeff), (sc_type)type2,
2072                        sd->state.lr_flag!=2?val:0, sd->state.lr_flag==2?val:0, 0);
2073                break;
2074        case SP_ADDEFF2:
2075                if (type2 > SC_MAX) {
2076                        ShowWarning("pc_bonus2 (Add Effect2): %d is not supported.\n", type2);
2077                        break;
2078                }
2079                pc_bonus_addeff(sd->addeff, ARRAYLENGTH(sd->addeff), (sc_type)type2,
2080                        sd->state.lr_flag!=2?val:0, sd->state.lr_flag==2?val:0, ATF_SELF);
2081                break;
2082        case SP_RESEFF:
2083                if (type2 < SC_COMMON_MIN || type2 > SC_COMMON_MAX) {
2084                        ShowWarning("pc_bonus2 (Resist Effect): %d is not supported.\n", type2);
2085                        break;
2086                }
2087                if(sd->state.lr_flag == 2)
2088                        break;
2089                i = sd->reseff[type2-SC_COMMON_MIN]+val;
2090                sd->reseff[type2-SC_COMMON_MIN]= cap_value(i, 0, 10000);
2091                break;
2092        case SP_MAGIC_ADDELE:
2093                if(type2 >= ELE_MAX) {
2094                        ShowError("pc_bonus2: SP_MAGIC_ADDELE: Invalid element %d\n", type2);
2095                        break;
2096                }
2097                if(sd->state.lr_flag != 2)
2098                        sd->magic_addele[type2]+=val;
2099                break;
2100        case SP_MAGIC_ADDRACE:
2101                if(sd->state.lr_flag != 2)
2102                        sd->magic_addrace[type2]+=val;
2103                break;
2104        case SP_MAGIC_ADDSIZE:
2105                if(sd->state.lr_flag != 2)
2106                        sd->magic_addsize[type2]+=val;
2107                break;
2108        case SP_ADD_DAMAGE_CLASS:
2109                switch (sd->state.lr_flag) {
2110                case 0: //Right hand
2111                        ARR_FIND(0, ARRAYLENGTH(sd->right_weapon.add_dmg), i, sd->right_weapon.add_dmg[i].rate == 0 || sd->right_weapon.add_dmg[i].class_ == type2);
2112                        if (i == ARRAYLENGTH(sd->right_weapon.add_dmg))
2113                        {
2114                                ShowWarning("pc_bonus2: Reached max (%d) number of add Class dmg bonuses per character!\n", ARRAYLENGTH(sd->right_weapon.add_dmg));
2115                                break;
2116                        }
2117                        sd->right_weapon.add_dmg[i].class_ = type2;
2118                        sd->right_weapon.add_dmg[i].rate += val;
2119                        if (!sd->right_weapon.add_dmg[i].rate) //Shift the rest of elements up.
2120                                memmove(&sd->right_weapon.add_dmg[i], &sd->right_weapon.add_dmg[i+1], sizeof(sd->right_weapon.add_dmg) - (i+1)*sizeof(sd->right_weapon.add_dmg[0]));
2121                        break;
2122                case 1: //Left hand
2123                        ARR_FIND(0, ARRAYLENGTH(sd->left_weapon.add_dmg), i, sd->left_weapon.add_dmg[i].rate == 0 || sd->left_weapon.add_dmg[i].class_ == type2);
2124                        if (i == ARRAYLENGTH(sd->left_weapon.add_dmg))
2125                        {
2126                                ShowWarning("pc_bonus2: Reached max (%d) number of add Class dmg bonuses per character!\n", ARRAYLENGTH(sd->left_weapon.add_dmg));
2127                                break;
2128                        }
2129                        sd->left_weapon.add_dmg[i].class_ = type2;
2130                        sd->left_weapon.add_dmg[i].rate += val;
2131                        if (!sd->left_weapon.add_dmg[i].rate) //Shift the rest of elements up.
2132                                memmove(&sd->left_weapon.add_dmg[i], &sd->left_weapon.add_dmg[i+1], sizeof(sd->left_weapon.add_dmg) - (i+1)*sizeof(sd->left_weapon.add_dmg[0]));
2133                        break;
2134                }
2135                break;
2136        case SP_ADD_MAGIC_DAMAGE_CLASS:
2137                if(sd->state.lr_flag == 2)
2138                        break;
2139                ARR_FIND(0, ARRAYLENGTH(sd->add_mdmg), i, sd->add_mdmg[i].rate == 0 || sd->add_mdmg[i].class_ == type2);
2140                if (i == ARRAYLENGTH(sd->add_mdmg))
2141                {
2142                        ShowWarning("pc_bonus2: Reached max (%d) number of add Class magic dmg bonuses per character!\n", ARRAYLENGTH(sd->add_mdmg));
2143                        break;
2144                }
2145                sd->add_mdmg[i].class_ = type2;
2146                sd->add_mdmg[i].rate += val;
2147                if (!sd->add_mdmg[i].rate) //Shift the rest of elements up.
2148                        memmove(&sd->add_mdmg[i], &sd->add_mdmg[i+1], sizeof(sd->add_mdmg) - (i+1)*sizeof(sd->add_mdmg[0]));
2149                break;
2150        case SP_ADD_DEF_CLASS:
2151                if(sd->state.lr_flag == 2)
2152                        break;
2153                ARR_FIND(0, ARRAYLENGTH(sd->add_def), i, sd->add_def[i].rate == 0 || sd->add_def[i].class_ == type2);
2154                if (i == ARRAYLENGTH(sd->add_def))
2155                {
2156                        ShowWarning("pc_bonus2: Reached max (%d) number of add Class def bonuses per character!\n", ARRAYLENGTH(sd->add_def));
2157                        break;
2158                }
2159                sd->add_def[i].class_ = type2;
2160                sd->add_def[i].rate += val;
2161                if (!sd->add_def[i].rate) //Shift the rest of elements up.
2162                        memmove(&sd->add_def[i], &sd->add_def[i+1], sizeof(sd->add_def) - (i+1)*sizeof(sd->add_def[0]));
2163                break;
2164        case SP_ADD_MDEF_CLASS:
2165                if(sd->state.lr_flag == 2)
2166                        break;
2167                ARR_FIND(0, ARRAYLENGTH(sd->add_mdef), i, sd->add_mdef[i].rate == 0 || sd->add_mdef[i].class_ == type2);
2168                if (i == ARRAYLENGTH(sd->add_mdef))
2169                {
2170                        ShowWarning("pc_bonus2: Reached max (%d) number of add Class mdef bonuses per character!\n", ARRAYLENGTH(sd->add_mdef));
2171                        break;
2172                }
2173                sd->add_mdef[i].class_ = type2;
2174                sd->add_mdef[i].rate += val;
2175                if (!sd->add_mdef[i].rate) //Shift the rest of elements up.
2176                        memmove(&sd->add_mdef[i], &sd->add_mdef[i+1], sizeof(sd->add_mdef) - (i+1)*sizeof(sd->add_mdef[0]));
2177                break;
2178        case SP_HP_DRAIN_RATE:
2179                if(!sd->state.lr_flag) {
2180                        sd->right_weapon.hp_drain[RC_NONBOSS].rate += type2;
2181                        sd->right_weapon.hp_drain[RC_NONBOSS].per += val;
2182                        sd->right_weapon.hp_drain[RC_BOSS].rate += type2;
2183                        sd->right_weapon.hp_drain[RC_BOSS].per += val;
2184                }
2185                else if(sd->state.lr_flag == 1) {
2186                        sd->left_weapon.hp_drain[RC_NONBOSS].rate += type2;
2187                        sd->left_weapon.hp_drain[RC_NONBOSS].per += val;
2188                        sd->left_weapon.hp_drain[RC_BOSS].rate += type2;
2189                        sd->left_weapon.hp_drain[RC_BOSS].per += val;
2190                }
2191                break;
2192        case SP_HP_DRAIN_VALUE:
2193                if(!sd->state.lr_flag) {
2194                        sd->right_weapon.hp_drain[RC_NONBOSS].value += type2;
2195                        sd->right_weapon.hp_drain[RC_NONBOSS].type = val;
2196                        sd->right_weapon.hp_drain[RC_BOSS].value += type2;
2197                        sd->right_weapon.hp_drain[RC_BOSS].type = val;
2198                }
2199                else if(sd->state.lr_flag == 1) {
2200                        sd->left_weapon.hp_drain[RC_NONBOSS].value += type2;
2201                        sd->left_weapon.hp_drain[RC_NONBOSS].type = val;
2202                        sd->left_weapon.hp_drain[RC_BOSS].value += type2;
2203                        sd->left_weapon.hp_drain[RC_BOSS].type = val;
2204                }
2205                break;
2206        case SP_SP_DRAIN_RATE:
2207                if(!sd->state.lr_flag) {
2208                        sd->right_weapon.sp_drain[RC_NONBOSS].rate += type2;
2209                        sd->right_weapon.sp_drain[RC_NONBOSS].per += val;
2210                        sd->right_weapon.sp_drain[RC_BOSS].rate += type2;
2211                        sd->right_weapon.sp_drain[RC_BOSS].per += val;
2212                }
2213                else if(sd->state.lr_flag == 1) {
2214                        sd->left_weapon.sp_drain[RC_NONBOSS].rate += type2;
2215                        sd->left_weapon.sp_drain[RC_NONBOSS].per += val;
2216                        sd->left_weapon.sp_drain[RC_BOSS].rate += type2;
2217                        sd->left_weapon.sp_drain[RC_BOSS].per += val;
2218                }
2219                break;
2220        case SP_SP_DRAIN_VALUE:
2221                if(!sd->state.lr_flag) {
2222                        sd->right_weapon.sp_drain[RC_NONBOSS].value += type2;
2223                        sd->right_weapon.sp_drain[RC_NONBOSS].type = val;
2224                        sd->right_weapon.sp_drain[RC_BOSS].value += type2;
2225                        sd->right_weapon.sp_drain[RC_BOSS].type = val;
2226                }
2227                else if(sd->state.lr_flag == 1) {
2228                        sd->left_weapon.sp_drain[RC_NONBOSS].value += type2;
2229                        sd->left_weapon.sp_drain[RC_NONBOSS].type = val;
2230                        sd->left_weapon.sp_drain[RC_BOSS].value += type2;
2231                        sd->left_weapon.sp_drain[RC_BOSS].type = val;
2232                }
2233                break;
2234        case SP_SP_VANISH_RATE:
2235                if(sd->state.lr_flag != 2) {
2236                        sd->sp_vanish_rate += type2;
2237                        sd->sp_vanish_per += val;
2238                }
2239                break;
2240        case SP_GET_ZENY_NUM:
2241                if(sd->state.lr_flag != 2 && sd->get_zeny_rate < val)
2242                {
2243                        sd->get_zeny_rate = val;
2244                        sd->get_zeny_num = type2;
2245                }
2246                break;
2247        case SP_ADD_GET_ZENY_NUM:
2248                if(sd->state.lr_flag != 2)
2249                {
2250                        sd->get_zeny_rate += val;
2251                        sd->get_zeny_num += type2;
2252                }
2253                break;
2254        case SP_WEAPON_COMA_ELE:
2255                if(type2 >= ELE_MAX) {
2256                        ShowError("pc_bonus2: SP_WEAPON_COMA_ELE: Invalid element %d\n", type2);
2257                        break;
2258                }
2259                if(sd->state.lr_flag == 2)
2260                        break;
2261                sd->weapon_coma_ele[type2] += val;
2262                sd->special_state.bonus_coma = 1;
2263                break;
2264        case SP_WEAPON_COMA_RACE:
2265                if(sd->state.lr_flag == 2)
2266                        break;
2267                sd->weapon_coma_race[type2] += val;
2268                sd->special_state.bonus_coma = 1;
2269                break;
2270        case SP_RANDOM_ATTACK_INCREASE: // [Valaris]
2271                if(sd->state.lr_flag !=2){
2272                        sd->random_attack_increase_add = type2;
2273                        sd->random_attack_increase_per += val;
2274                }
2275                break;
2276        case SP_WEAPON_ATK:
2277                if(sd->state.lr_flag != 2)
2278                        sd->weapon_atk[type2]+=val;
2279                break;
2280        case SP_WEAPON_ATK_RATE:
2281                if(sd->state.lr_flag != 2)
2282                        sd->weapon_atk_rate[type2]+=val;
2283                break;
2284        case SP_CRITICAL_ADDRACE:
2285                if(sd->state.lr_flag != 2)
2286                        sd->critaddrace[type2] += val*10;
2287                break;
2288        case SP_ADDEFF_WHENHIT:
2289                if (type2 > SC_MAX) {
2290                        ShowWarning("pc_bonus2 (Add Effect when hit): %d is not supported.\n", type2);
2291                        break;
2292                }
2293                if(sd->state.lr_flag != 2)
2294                        pc_bonus_addeff(sd->addeff2, ARRAYLENGTH(sd->addeff2), (sc_type)type2, val, 0, 0);
2295                break;
2296        case SP_SKILL_ATK:
2297                if(sd->state.lr_flag == 2)
2298                        break;
2299                ARR_FIND(0, ARRAYLENGTH(sd->skillatk), i, sd->skillatk[i].id == 0 || sd->skillatk[i].id == type2);
2300                if (i == ARRAYLENGTH(sd->skillatk))
2301                {       //Better mention this so the array length can be updated. [Skotlex]
2302                        ShowDebug("run_script: bonus2 bSkillAtk reached it's limit (%d skills per character), bonus skill %d (+%d%%) lost.\n", ARRAYLENGTH(sd->skillatk), type2, val);
2303                        break;
2304                }
2305                if (sd->skillatk[i].id == type2)
2306                        sd->skillatk[i].val += val;
2307                else {
2308                        sd->skillatk[i].id = type2;
2309                        sd->skillatk[i].val = val;
2310                }
2311                break;
2312        case SP_SKILL_HEAL:
2313                if(sd->state.lr_flag == 2)
2314                        break;
2315                ARR_FIND(0, ARRAYLENGTH(sd->skillheal), i, sd->skillheal[i].id == 0 || sd->skillheal[i].id == type2);
2316                if (i == ARRAYLENGTH(sd->skillheal))
2317                {       //Better mention this so the array length can be updated. [Skotlex]
2318                        ShowDebug("run_script: bonus2 bSkillHeal reached it's limit (%d skills per character), bonus skill %d (+%d%%) lost.\n", ARRAYLENGTH(sd->skillheal), type2, val);
2319                        break;
2320                }
2321                if (sd->skillheal[i].id == type2)
2322                        sd->skillheal[i].val += val;
2323                else {
2324                        sd->skillheal[i].id = type2;
2325                        sd->skillheal[i].val = val;
2326                }
2327                break;
2328        case SP_ADD_SKILL_BLOW:
2329                if(sd->state.lr_flag == 2)
2330                        break;
2331                ARR_FIND(0, ARRAYLENGTH(sd->skillblown), i, sd->skillblown[i].id == 0 || sd->skillblown[i].id == type2);
2332                if (i == ARRAYLENGTH(sd->skillblown))
2333                {       //Better mention this so the array length can be updated. [Skotlex]
2334                        ShowDebug("run_script: bonus2 bSkillBlown reached it's limit (%d skills per character), bonus skill %d (+%d%%) lost.\n", ARRAYLENGTH(sd->skillblown), type2, val);
2335                        break;
2336                }
2337                if(sd->skillblown[i].id == type2)
2338                        sd->skillblown[i].val += val;
2339                else {
2340                        sd->skillblown[i].id = type2;
2341                        sd->skillblown[i].val = val;
2342                }
2343                break;
2344
2345        case SP_CASTRATE:
2346                if(sd->state.lr_flag == 2)
2347                        break;
2348                ARR_FIND(0, ARRAYLENGTH(sd->skillcast), i, sd->skillcast[i].id == 0 || sd->skillcast[i].id == type2);
2349                if (i == ARRAYLENGTH(sd->skillcast))
2350                {       //Better mention this so the array length can be updated. [Skotlex]
2351                        ShowDebug("run_script: bonus2 bCastRate reached it's limit (%d skills per character), bonus skill %d (+%d%%) lost.\n", ARRAYLENGTH(sd->skillcast), type2, val);
2352                        break;
2353                }
2354                if(sd->skillcast[i].id == type2)
2355                        sd->skillcast[i].val += val;
2356                else {
2357                        sd->skillcast[i].id = type2;
2358                        sd->skillcast[i].val = val;
2359                }
2360                break;
2361
2362        case SP_HP_LOSS_RATE:
2363                if(sd->state.lr_flag != 2) {
2364                        sd->hp_loss.value = type2;
2365                        sd->hp_loss.rate = val;
2366                }
2367                break;
2368        case SP_HP_REGEN_RATE:
2369                if(sd->state.lr_flag != 2) {
2370                        sd->hp_regen.value = type2;
2371                        sd->hp_regen.rate = val;
2372                }
2373                break;
2374        case SP_ADDRACE2:
2375                if (!(type2 > 0 && type2 < MAX_MOB_RACE_DB))
2376                        break;
2377                if(sd->state.lr_flag != 2)
2378                        sd->right_weapon.addrace2[type2] += val;
2379                else
2380                        sd->left_weapon.addrace2[type2] += val;
2381                break;
2382        case SP_SUBSIZE:
2383                if(sd->state.lr_flag != 2)
2384                        sd->subsize[type2]+=val;
2385                break;
2386        case SP_SUBRACE2:
2387                if(sd->state.lr_flag != 2)
2388                        sd->subrace2[type2]+=val;
2389                break;
2390        case SP_ADD_ITEM_HEAL_RATE:
2391                if(sd->state.lr_flag == 2)
2392                        break;
2393                if (type2 < MAX_ITEMGROUP) {    //Group bonus
2394                        sd->itemgrouphealrate[type2] += val;
2395                        break;
2396                }
2397                //Standard item bonus.
2398                for(i=0; i < ARRAYLENGTH(sd->itemhealrate) && sd->itemhealrate[i].nameid && sd->itemhealrate[i].nameid != type2; i++);
2399                if(i == ARRAYLENGTH(sd->itemhealrate)) {
2400                        ShowWarning("pc_bonus2: Reached max (%d) number of item heal bonuses per character!\n", ARRAYLENGTH(sd->itemhealrate));
2401                        break;
2402                }
2403                sd->itemhealrate[i].nameid = type2;
2404                sd->itemhealrate[i].rate += val;
2405                break;
2406        case SP_EXP_ADDRACE:
2407                if(sd->state.lr_flag != 2)
2408                        sd->expaddrace[type2]+=val;
2409                break;
2410        case SP_SP_GAIN_RACE:
2411                if(sd->state.lr_flag != 2)
2412                        sd->sp_gain_race[type2]+=val;
2413                break;
2414        case SP_ADD_MONSTER_DROP_ITEM:
2415                if (sd->state.lr_flag != 2)
2416                        pc_bonus_item_drop(sd->add_drop, ARRAYLENGTH(sd->add_drop), type2, 0, (1<<RC_BOSS)|(1<<RC_NONBOSS), val);
2417                break;
2418        case SP_ADD_MONSTER_DROP_ITEMGROUP:
2419                if (sd->state.lr_flag != 2)
2420                        pc_bonus_item_drop(sd->add_drop, ARRAYLENGTH(sd->add_drop), 0, type2, (1<<RC_BOSS)|(1<<RC_NONBOSS), val);
2421                break;
2422        case SP_SP_LOSS_RATE:
2423                if(sd->state.lr_flag != 2) {
2424                        sd->sp_loss.value = type2;
2425                        sd->sp_loss.rate = val;
2426                }
2427                break;
2428        case SP_SP_REGEN_RATE:
2429                if(sd->state.lr_flag != 2) {
2430                        sd->sp_regen.value = type2;
2431                        sd->sp_regen.rate = val;
2432                }
2433                break;
2434        case SP_HP_DRAIN_VALUE_RACE:
2435                if(!sd->state.lr_flag) {
2436                        sd->right_weapon.hp_drain[type2].value += val;
2437                }
2438                else if(sd->state.lr_flag == 1) {
2439                        sd->left_weapon.hp_drain[type2].value += val;
2440                }
2441                break;
2442        case SP_SP_DRAIN_VALUE_RACE:
2443                if(!sd->state.lr_flag) {
2444                        sd->right_weapon.sp_drain[type2].value += val;
2445                }
2446                else if(sd->state.lr_flag == 1) {
2447                        sd->left_weapon.sp_drain[type2].value += val;
2448                }
2449                break;
2450        case SP_IGNORE_MDEF_RATE:
2451                if(sd->state.lr_flag != 2)
2452                        sd->ignore_mdef[type2] += val;
2453                break;
2454
2455        default:
2456                ShowWarning("pc_bonus2: unknown type %d %d %d!\n",type,type2,val);
2457                break;
2458        }
2459        return 0;
2460}
2461
2462int pc_bonus3(struct map_session_data *sd,int type,int type2,int type3,int val)
2463{
2464        nullpo_retr(0, sd);
2465
2466        switch(type){
2467        case SP_ADD_MONSTER_DROP_ITEM:
2468                if(sd->state.lr_flag != 2)
2469                        pc_bonus_item_drop(sd->add_drop, ARRAYLENGTH(sd->add_drop), type2, 0, 1<<type3, val);
2470                break;
2471        case SP_AUTOSPELL:
2472                if(sd->state.lr_flag != 2)
2473                {
2474                        int target = skill_get_inf(type2); //Support or Self (non-auto-target) skills should pick self.
2475                        target = target&INF_SUPPORT_SKILL || (target&INF_SELF_SKILL && !(skill_get_inf2(type2)&INF2_NO_TARGET_SELF));
2476                        pc_bonus_autospell(sd->autospell, ARRAYLENGTH(sd->autospell),
2477                                target?-type2:type2, type3, val, 0, current_equip_card_id);
2478                }
2479                break;
2480        case SP_AUTOSPELL_WHENHIT:
2481                if(sd->state.lr_flag != 2)
2482                {
2483                        int target = skill_get_inf(type2); //Support or Self (non-auto-target) skills should pick self.
2484                        target = target&INF_SUPPORT_SKILL || (target&INF_SELF_SKILL && !(skill_get_inf2(type2)&INF2_NO_TARGET_SELF));
2485                        pc_bonus_autospell(sd->autospell2, ARRAYLENGTH(sd->autospell2),
2486                                target?-type2:type2, type3, val, 0, current_equip_card_id);
2487                }
2488                break;
2489        case SP_SP_DRAIN_RATE:
2490                if(!sd->state.lr_flag) {
2491                        sd->right_weapon.sp_drain[RC_NONBOSS].rate += type2;
2492                        sd->right_weapon.sp_drain[RC_NONBOSS].per += type3;
2493                        sd->right_weapon.sp_drain[RC_NONBOSS].type = val;
2494                        sd->right_weapon.sp_drain[RC_BOSS].rate += type2;
2495                        sd->right_weapon.sp_drain[RC_BOSS].per += type3;
2496                        sd->right_weapon.sp_drain[RC_BOSS].type = val;
2497
2498                }
2499                else if(sd->state.lr_flag == 1) {
2500                        sd->left_weapon.sp_drain[RC_NONBOSS].rate += type2;
2501                        sd->left_weapon.sp_drain[RC_NONBOSS].per += type3;
2502                        sd->left_weapon.sp_drain[RC_NONBOSS].type = val;
2503                        sd->left_weapon.sp_drain[RC_BOSS].rate += type2;
2504                        sd->left_weapon.sp_drain[RC_BOSS].per += type3;
2505                        sd->left_weapon.sp_drain[RC_BOSS].type = val;
2506                }
2507                break;
2508        case SP_HP_DRAIN_RATE_RACE:
2509                if(!sd->state.lr_flag) {
2510                        sd->right_weapon.hp_drain[type2].rate += type3;
2511                        sd->right_weapon.hp_drain[type2].per += val;
2512                }
2513                else if(sd->state.lr_flag == 1) {
2514                        sd->left_weapon.hp_drain[type2].rate += type3;
2515                        sd->left_weapon.hp_drain[type2].per += val;
2516                }
2517                break;
2518        case SP_SP_DRAIN_RATE_RACE:
2519                if(!sd->state.lr_flag) {
2520                        sd->right_weapon.sp_drain[type2].rate += type3;
2521                        sd->right_weapon.sp_drain[type2].per += val;
2522                }
2523                else if(sd->state.lr_flag == 1) {
2524                        sd->left_weapon.sp_drain[type2].rate += type3;
2525                        sd->left_weapon.sp_drain[type2].per += val;
2526                }
2527                break;
2528        case SP_ADD_MONSTER_DROP_ITEMGROUP:
2529                if (sd->state.lr_flag != 2)
2530                        pc_bonus_item_drop(sd->add_drop, ARRAYLENGTH(sd->add_drop), 0, type2, 1<<type3, val);
2531                break;
2532
2533        case SP_ADDEFF:
2534                if (type2 > SC_MAX) {
2535                        ShowWarning("pc_bonus3 (Add Effect): %d is not supported.\n", type2);
2536                        break;
2537                }
2538                pc_bonus_addeff(sd->addeff, ARRAYLENGTH(sd->addeff), (sc_type)type2,
2539                        sd->state.lr_flag!=2?type3:0, sd->state.lr_flag==2?type3:0, val);
2540                break;
2541
2542        case SP_ADDEFF_WHENHIT:
2543                if (type2 > SC_MAX) {
2544                        ShowWarning("pc_bonus3 (Add Effect when hit): %d is not supported.\n", type2);
2545                        break;
2546                }
2547                if(sd->state.lr_flag != 2)
2548                        pc_bonus_addeff(sd->addeff2, ARRAYLENGTH(sd->addeff2), (sc_type)type2, type3, 0, val);
2549                break;
2550
2551        default:
2552                ShowWarning("pc_bonus3: unknown type %d %d %d %d!\n",type,type2,type3,val);
2553                break;
2554        }
2555
2556        return 0;
2557}
2558
2559int pc_bonus4(struct map_session_data *sd,int type,int type2,int type3,int type4,int val)
2560{
2561        nullpo_retr(0, sd);
2562
2563        switch(type){
2564        case SP_AUTOSPELL:
2565                if(sd->state.lr_flag != 2)
2566                        pc_bonus_autospell(sd->autospell, ARRAYLENGTH(sd->autospell), (val&1?type2:-type2), (val&2?-type3:type3), type4, 0, current_equip_card_id);
2567                break;
2568
2569        case SP_AUTOSPELL_WHENHIT:
2570                if(sd->state.lr_flag != 2)
2571                        pc_bonus_autospell(sd->autospell2, ARRAYLENGTH(sd->autospell2), (val&1?type2:-type2), (val&2?-type3:type3), type4, 0, current_equip_card_id);
2572                break;
2573        default:
2574                ShowWarning("pc_bonus4: unknown type %d %d %d %d %d!\n",type,type2,type3,type4,val);
2575                break;
2576        }
2577
2578        return 0;
2579}
2580
2581int pc_bonus5(struct map_session_data *sd,int type,int type2,int type3,int type4,int type5,int val)
2582{
2583        nullpo_retr(0, sd);
2584
2585        switch(type){
2586        case SP_AUTOSPELL:
2587                if(sd->state.lr_flag != 2)
2588                        pc_bonus_autospell(sd->autospell, ARRAYLENGTH(sd->autospell), (val&1?type2:-type2), (val&2?-type3:type3), type4, type5, current_equip_card_id);
2589                break;
2590
2591        case SP_AUTOSPELL_WHENHIT:
2592                if(sd->state.lr_flag != 2)
2593                        pc_bonus_autospell(sd->autospell2, ARRAYLENGTH(sd->autospell2), (val&1?type2:-type2), (val&2?-type3:type3), type4, type5, current_equip_card_id);
2594                break;
2595        default:
2596                ShowWarning("pc_bonus5: unknown type %d %d %d %d %d %d!\n",type,type2,type3,type4,type5,val);
2597                break;
2598        }
2599
2600        return 0;
2601}
2602
2603/*==========================================
2604 *      Grants a player a given skill. Flag values are:
2605 *      0 - Grant skill unconditionally and forever (only this one invokes status_calc_pc,
2606 *          as the other two are assumed to be invoked from within it)
2607 *      1 - Grant an item skill (temporary)
2608 *      2 - Like 1, except the level granted can stack with previously learned level.
2609 *------------------------------------------*/
2610int pc_skill(TBL_PC* sd, int id, int level, int flag)
2611{
2612        nullpo_retr(0, sd);
2613
2614        if( id <= 0 || id >= MAX_SKILL || skill_db[id].name == NULL) {
2615                ShowError("pc_skill: Skill with id %d does not exist in the skill database\n", id);
2616                return 0;
2617        }
2618        if( level > MAX_SKILL_LEVEL ) {
2619                ShowError("pc_skill: Skill level %d too high. Max lv supported is %d\n", level, MAX_SKILL_LEVEL);
2620                return 0;
2621        }
2622
2623        switch( flag ){
2624        case 0: //Set skill data overwriting whatever was there before.
2625                sd->status.skill[id].id   = id;
2626                sd->status.skill[id].lv   = level;
2627                sd->status.skill[id].flag = 0;
2628                if( !level ) //Remove skill.
2629                        sd->status.skill[id].id = 0;
2630                if( !skill_get_inf(id) ) //Only recalculate for passive skills.
2631                        status_calc_pc(sd, 0);
2632                clif_skillinfoblock(sd);
2633        break;
2634        case 2: //Add skill bonus on top of what you had.
2635                if( sd->status.skill[id].id == id ){
2636                        if( !sd->status.skill[id].flag ) // Store previous level.
2637                                sd->status.skill[id].flag = sd->status.skill[id].lv + 2;
2638                } else {
2639                        sd->status.skill[id].id   = id;
2640                        sd->status.skill[id].flag = 1; //Set that this is a bonus skill.
2641                }
2642                sd->status.skill[id].lv += level;
2643        break;
2644        case 1: //Item bonus skill.
2645                if( sd->status.skill[id].lv >= level )
2646                        return 0;
2647                if( sd->status.skill[id].id == id ){
2648                        if( !sd->status.skill[id].flag ) //Non-granted skill, store it's level.
2649                                sd->status.skill[id].flag = sd->status.skill[id].lv + 2;
2650                } else {
2651                        sd->status.skill[id].id   = id;
2652                        sd->status.skill[id].flag = 1;
2653                }
2654                sd->status.skill[id].lv = level;
2655        break;
2656        default: //Unknown flag?
2657                return 0;
2658        }
2659        return 1;
2660}
2661/*==========================================
2662 * ƒJ?ƒh?“ü
2663 *------------------------------------------*/
2664int pc_insert_card(struct map_session_data *sd,int idx_card,int idx_equip)
2665{
2666        int i, ep;
2667        int nameid, cardid;
2668
2669        nullpo_retr(0, sd);
2670
2671        if(idx_card < 0 || idx_card >= MAX_INVENTORY || !sd->inventory_data[idx_card])
2672                return 0; //Invalid card index.
2673                       
2674        if(idx_equip < 0 || idx_equip >= MAX_INVENTORY || !sd->inventory_data[idx_equip])
2675                return 0; //Invalid item index.
2676       
2677        nameid=sd->status.inventory[idx_equip].nameid;
2678        cardid=sd->status.inventory[idx_card].nameid;
2679        ep=sd->inventory_data[idx_card]->equip;
2680
2681        //Check validity
2682        if( nameid <= 0 || cardid <= 0 ||
2683                sd->status.inventory[idx_equip].amount < 1 || //These two should never be required due to pc_delitem zero'ing the data.
2684                sd->status.inventory[idx_card].amount < 1 ||
2685                (sd->inventory_data[idx_equip]->type!=IT_WEAPON && sd->inventory_data[idx_equip]->type!=IT_ARMOR)||
2686                sd->inventory_data[idx_card]->type!=IT_CARD || // Prevent Hack [Ancyker]
2687                sd->status.inventory[idx_equip].identify==0 ||
2688                itemdb_isspecial(sd->status.inventory[idx_equip].card[0]) ||
2689                !(sd->inventory_data[idx_equip]->equip&ep) ||
2690                (sd->inventory_data[idx_equip]->type==IT_WEAPON && ep==EQP_SHIELD) || //Card shield attempted to place on left-hand weapon.
2691                sd->status.inventory[idx_equip].equip){
2692
2693                clif_insert_card(sd,idx_equip,idx_card,1);
2694                return 0;
2695        }
2696        for(i=0;i<sd->inventory_data[idx_equip]->slot;i++){
2697                if( sd->status.inventory[idx_equip].card[i] == 0)
2698                {       //Free slot found.
2699                        sd->status.inventory[idx_equip].card[i]=cardid;
2700                        clif_insert_card(sd,idx_equip,idx_card,0);
2701                        pc_delitem(sd,idx_card,1,1);
2702                        return 0;
2703                }
2704        }
2705        clif_insert_card(sd,idx_equip,idx_card,1);
2706        return 0;
2707}
2708
2709//
2710// ƒAƒCƒeƒ€•š
2711//
2712
2713/*==========================================
2714 * ƒXƒLƒ‹‚É‚æ‚锃‚¢’lC³
2715 *------------------------------------------*/
2716int pc_modifybuyvalue(struct map_session_data *sd,int orig_value)
2717{
2718        int skill,val = orig_value,rate1 = 0,rate2 = 0;
2719        if((skill=pc_checkskill(sd,MC_DISCOUNT))>0)     // ƒfƒBƒXƒJƒEƒ“ƒg
2720                rate1 = 5+skill*2-((skill==10)? 1:0);
2721        if((skill=pc_checkskill(sd,RG_COMPULSION))>0)   // ƒRƒ€ƒpƒ‹ƒVƒ‡ƒ“ƒfƒBƒXƒJƒEƒ“ƒg
2722                rate2 = 5+skill*4;
2723        if(rate1 < rate2) rate1 = rate2;
2724        if(rate1)
2725                val = (int)((double)orig_value*(double)(100-rate1)/100.);
2726        if(val < 0) val = 0;
2727        if(orig_value > 0 && val < 1) val = 1;
2728
2729        return val;
2730}
2731
2732/*==========================================
2733 * ƒXƒLƒ‹‚É‚æ‚é?‚è’lC³
2734 *------------------------------------------*/
2735int pc_modifysellvalue(struct map_session_data *sd,int orig_value)
2736{
2737        int skill,val = orig_value,rate = 0;
2738        if((skill=pc_checkskill(sd,MC_OVERCHARGE))>0)   // ƒI?ƒo?ƒ`ƒƒ?ƒW
2739                rate = 5+skill*2-((skill==10)? 1:0);
2740        if(rate)
2741                val = (int)((double)orig_value*(double)(100+rate)/100.);
2742        if(val < 0) val = 0;
2743        if(orig_value > 0 && val < 1) val = 1;
2744
2745        return val;
2746}
2747
2748/*==========================================
2749 * ƒAƒCƒeƒ€‚𔃂Á‚œŽbɁAV‚µ‚¢ƒAƒCƒeƒ€—“‚ðŽg‚€‚©A
2750 * 3–œŒÂ§ŒÀ‚É‚©‚©‚é‚©Šm”F
2751 *------------------------------------------*/
2752int pc_checkadditem(struct map_session_data *sd,int nameid,int amount)
2753{
2754        int i;
2755
2756        nullpo_retr(0, sd);
2757
2758        if(!itemdb_isstackable(nameid))
2759                return ADDITEM_NEW;
2760
2761        for(i=0;i<MAX_INVENTORY;i++){
2762                if(sd->status.inventory[i].nameid==nameid){
2763                        if(sd->status.inventory[i].amount+amount > MAX_AMOUNT)
2764                                return ADDITEM_OVERAMOUNT;
2765                        return ADDITEM_EXIST;
2766                }
2767        }
2768
2769        if(amount > MAX_AMOUNT)
2770                return ADDITEM_OVERAMOUNT;
2771        return ADDITEM_NEW;
2772}
2773
2774/*==========================================
2775 * ‹ó‚«ƒAƒCƒeƒ€—“‚ÌŒÂ?
2776 *------------------------------------------*/
2777int pc_inventoryblank(struct map_session_data *sd)
2778{
2779        int i,b;
2780
2781        nullpo_retr(0, sd);
2782
2783        for(i=0,b=0;i<MAX_INVENTORY;i++){
2784                if(sd->status.inventory[i].nameid==0)
2785                        b++;
2786        }
2787
2788        return b;
2789}
2790
2791/*==========================================
2792 * ‚š‹à‚ð?‚€
2793 *------------------------------------------*/
2794int pc_payzeny(struct map_session_data *sd,int zeny)
2795{
2796        nullpo_retr(0, sd);
2797
2798        if( zeny < 0 )
2799                return pc_getzeny(sd, -zeny);
2800
2801        if( sd->status.zeny < zeny )
2802                return 1; //Not enough.
2803
2804        sd->status.zeny -= zeny;
2805        clif_updatestatus(sd,SP_ZENY);
2806
2807        return 0;
2808}
2809/*==========================================
2810 * Cash Shop
2811 *------------------------------------------*/
2812
2813void pc_paycash(struct map_session_data *sd, int price, int points)
2814{
2815        char output[128];
2816        int cash = price - points;
2817        nullpo_retv(sd);
2818
2819        pc_setaccountreg(sd,"#CASHPOINTS",sd->cashPoints - cash);
2820        pc_setaccountreg(sd,"#KAFRAPOINTS",sd->kafraPoints - points);
2821        sprintf(output, "Used %d kafra points and %d cash points. %d kafra and %d cash points remaining.", points, cash, sd->kafraPoints, sd->cashPoints);
2822        clif_disp_onlyself(sd, output, strlen(output));
2823}
2824
2825void pc_getcash(struct map_session_data *sd, int cash, int points)
2826{
2827        char output[128];
2828        nullpo_retv(sd);
2829
2830        if( cash > 0 )
2831        {
2832                pc_setaccountreg(sd,"#CASHPOINTS",sd->cashPoints + cash);
2833
2834                sprintf(output, "Gained %d cash points. Total %d points", cash, sd->cashPoints);
2835                clif_disp_onlyself(sd, output, strlen(output));
2836        }
2837
2838        if( points > 0 )
2839        {
2840                pc_setaccountreg(sd,"#KAFRAPOINTS",sd->kafraPoints + points);
2841
2842                sprintf(output, "Gained %d kafra points. Total %d points", points, sd->kafraPoints);
2843                clif_disp_onlyself(sd, output, strlen(output));
2844        }
2845}
2846
2847/*==========================================
2848 * ‚š‹à‚𓟂é
2849 *------------------------------------------*/
2850int pc_getzeny(struct map_session_data *sd,int zeny)
2851{
2852        nullpo_retr(0, sd);
2853
2854        if( zeny < 0 )
2855                return pc_payzeny(sd, -zeny);
2856
2857        if( zeny > MAX_ZENY - sd->status.zeny )
2858                zeny = MAX_ZENY - sd->status.zeny;
2859
2860        sd->status.zeny += zeny;
2861        clif_updatestatus(sd,SP_ZENY);
2862
2863        if( zeny > 0 && sd->state.showzeny )
2864        {
2865                char output[255];
2866                sprintf(output, "Gained %dz.", zeny);
2867                clif_disp_onlyself(sd,output,strlen(output));
2868        }
2869
2870        return 0;
2871}
2872
2873/*==========================================
2874 * ƒAƒCƒeƒ€‚ð’T‚µ‚āAƒCƒ“ƒfƒbƒNƒX‚ð•Ô‚·
2875 *------------------------------------------*/
2876int pc_search_inventory(struct map_session_data *sd,int item_id)
2877{
2878        int i;
2879        nullpo_retr(-1, sd);
2880
2881        ARR_FIND( 0, MAX_INVENTORY, i, sd->status.inventory[i].nameid == item_id && (sd->status.inventory[i].amount > 0 || item_id == 0) );
2882        return ( i < MAX_INVENTORY ) ? i : -1;
2883}
2884
2885/*==========================================
2886 * ƒAƒCƒeƒ€’ljÁBŒÂ?‚Ì‚Ýitem\‘¢?‚Ì?Žš‚𖳎‹
2887 *------------------------------------------*/
2888int pc_additem(struct map_session_data *sd,struct item *item_data,int amount)
2889{
2890        struct item_data *data;
2891        int i;
2892        unsigned int w;
2893
2894        nullpo_retr(1, sd);
2895        nullpo_retr(1, item_data);
2896
2897        if(item_data->nameid <= 0 || amount <= 0)
2898                return 1;
2899        if(amount > MAX_AMOUNT)
2900                return 5;
2901       
2902        data = itemdb_search(item_data->nameid);
2903        w = data->weight*amount;
2904        if(sd->weight + w > sd->max_weight)
2905                return 2;
2906
2907        i = MAX_INVENTORY;
2908
2909        if (itemdb_isstackable2(data))
2910        { //Stackable
2911                for (i = 0; i < MAX_INVENTORY; i++)
2912                {
2913                        if(sd->status.inventory[i].nameid == item_data->nameid &&
2914                                memcmp(&sd->status.inventory[i].card,&item_data->card,
2915                                        sizeof(item_data->card))==0)
2916                        {
2917                                if (amount > MAX_AMOUNT - sd->status.inventory[i].amount)
2918                                        return 5;
2919                                sd->status.inventory[i].amount += amount;
2920                                clif_additem(sd,i,amount,0);
2921                                break;
2922                        }
2923                }
2924        }
2925        if (i >= MAX_INVENTORY){
2926                i = pc_search_inventory(sd,0);
2927                if(i<0) return 4;
2928                memcpy(&sd->status.inventory[i], item_data, sizeof(sd->status.inventory[0]));
2929                // clear equips field first, just in case
2930                if (item_data->equip)
2931                        sd->status.inventory[i].equip = 0;
2932
2933                sd->status.inventory[i].amount = amount;
2934                sd->inventory_data[i] = data;
2935                clif_additem(sd,i,amount,0);
2936        }
2937
2938        sd->weight += w;
2939        clif_updatestatus(sd,SP_WEIGHT);
2940        //Auto-equip
2941        if(data->flag.autoequip) pc_equipitem(sd, i, data->equip);
2942        return 0;
2943}
2944
2945/*==========================================
2946 * ƒAƒCƒeƒ€‚ðŒž‚ç‚·
2947 *------------------------------------------*/
2948int pc_delitem(struct map_session_data *sd,int n,int amount,int type)
2949{
2950        nullpo_retr(1, sd);
2951
2952        if(sd->status.inventory[n].nameid==0 || amount <= 0 || sd->status.inventory[n].amount<amount || sd->inventory_data[n] == NULL)
2953                return 1;
2954
2955        sd->status.inventory[n].amount -= amount;
2956        sd->weight -= sd->inventory_data[n]->weight*amount ;
2957        if(sd->status.inventory[n].amount<=0){
2958                if(sd->status.inventory[n].equip)
2959                        pc_unequipitem(sd,n,3);
2960                memset(&sd->status.inventory[n],0,sizeof(sd->status.inventory[0]));
2961                sd->inventory_data[n] = NULL;
2962        }
2963        if(!(type&1))
2964                clif_delitem(sd,n,amount);
2965        if(!(type&2))
2966                clif_updatestatus(sd,SP_WEIGHT);
2967
2968        return 0;
2969}
2970
2971/*==========================================
2972 * ƒAƒCƒeƒ€‚ð—Ž‚·
2973 *------------------------------------------*/
2974int pc_dropitem(struct map_session_data *sd,int n,int amount)
2975{
2976        nullpo_retr(1, sd);
2977
2978        if(n < 0 || n >= MAX_INVENTORY)
2979                return 0;
2980
2981        if(amount <= 0)
2982                return 0;
2983
2984        if(sd->status.inventory[n].nameid <= 0 ||
2985                sd->status.inventory[n].amount <= 0 ||
2986                sd->status.inventory[n].amount < amount ||
2987                sd->state.trading || sd->vender_id != 0 ||
2988                !sd->inventory_data[n] //pc_delitem would fail on this case.
2989                )
2990                return 0;
2991
2992        if (map[sd->bl.m].flag.nodrop) {
2993                clif_displaymessage (sd->fd, msg_txt(271));
2994                return 0; //Can't drop items in nodrop mapflag maps.
2995        }
2996       
2997        if (!pc_candrop(sd,&sd->status.inventory[n])) {
2998                clif_displaymessage (sd->fd, msg_txt(263));
2999                return 0;
3000        }
3001       
3002        //Logs items, dropped by (P)layers [Lupus]
3003        if(log_config.enable_logs&0x8)
3004                log_pick_pc(sd, "P", sd->status.inventory[n].nameid, -amount, (struct item*)&sd->status.inventory[n]);
3005        //Logs
3006
3007        if (!map_addflooritem(&sd->status.inventory[n], amount, sd->bl.m, sd->bl.x, sd->bl.y, 0, 0, 0, 2))
3008                return 0;
3009       
3010        pc_delitem(sd, n, amount, 0);
3011        return 1;
3012}
3013
3014/*==========================================
3015 * ƒAƒCƒeƒ€‚ðE‚€
3016 *------------------------------------------*/
3017int pc_takeitem(struct map_session_data *sd,struct flooritem_data *fitem)
3018{
3019        int flag=0;
3020        unsigned int tick = gettick();
3021        struct map_session_data *first_sd = NULL,*second_sd = NULL,*third_sd = NULL;
3022        struct party_data *p=NULL;
3023
3024        nullpo_retr(0, sd);
3025        nullpo_retr(0, fitem);
3026
3027        if(!check_distance_bl(&fitem->bl, &sd->bl, 2) && sd->ud.skillid!=BS_GREED)
3028                return 0;       // ‹——£‚ª‰“‚¢
3029
3030        if (sd->status.party_id)
3031                p = party_search(sd->status.party_id);
3032       
3033        if(fitem->first_get_charid > 0 && fitem->first_get_charid != sd->status.char_id)
3034        {
3035                first_sd = map_charid2sd(fitem->first_get_charid);
3036                if(DIFF_TICK(tick,fitem->first_get_tick) < 0) {
3037                        if (!(p && p->party.item&1 &&
3038                                first_sd && first_sd->status.party_id == sd->status.party_id
3039                        ))
3040                                return 0;
3041                }
3042                else
3043                if(fitem->second_get_charid > 0 && fitem->second_get_charid != sd->status.char_id)
3044                {
3045                        second_sd = map_charid2sd(fitem->second_get_charid);
3046                        if(DIFF_TICK(tick, fitem->second_get_tick) < 0) {
3047                                if(!(p && p->party.item&1 &&
3048                                        ((first_sd && first_sd->status.party_id == sd->status.party_id) ||
3049                                        (second_sd && second_sd->status.party_id == sd->status.party_id))
3050                                ))
3051                                        return 0;
3052                        }
3053                        else
3054                        if(fitem->third_get_charid > 0 && fitem->third_get_charid != sd->status.char_id)
3055                        {
3056                                third_sd = map_charid2sd(fitem->third_get_charid);
3057                                if(DIFF_TICK(tick,fitem->third_get_tick) < 0) {
3058                                        if(!(p && p->party.item&1 &&
3059                                                ((first_sd && first_sd->status.party_id == sd->status.party_id) ||
3060                                                (second_sd && second_sd->status.party_id == sd->status.party_id) ||
3061                                                (third_sd && third_sd->status.party_id == sd->status.party_id))
3062                                        ))
3063                                                return 0;
3064                                }
3065                        }
3066                }
3067        }
3068
3069        //This function takes care of giving the item to whoever should have it, considering party-share options.
3070        if ((flag = party_share_loot(p,sd,&fitem->item_data, fitem->first_get_charid))) {
3071                clif_additem(sd,0,0,flag);
3072                return 1;
3073        }
3074
3075        //Display pickup animation.
3076        pc_stop_attack(sd);
3077        clif_takeitem(&sd->bl,&fitem->bl);
3078        map_clearflooritem(fitem->bl.id);
3079        return 1;
3080}
3081
3082int pc_isUseitem(struct map_session_data *sd,int n)
3083{
3084        struct item_data *item;
3085        int nameid;
3086
3087        nullpo_retr(0, sd);
3088
3089        item = sd->inventory_data[n];
3090        nameid = sd->status.inventory[n].nameid;
3091
3092        if(item == NULL)
3093                return 0;
3094        //Not consumable item
3095        if(item->type != IT_HEALING && item->type != IT_USABLE)
3096                return 0;
3097        if(!item->script) //if it has no script, you can't really consume it!
3098                return 0;
3099        //Anodyne (can't use Anodyne's Endure at GVG)
3100        if(nameid == 605 && map_flag_gvg(sd->bl.m))
3101                return 0;
3102        //Fly Wing/Giant Fly Wing (can't use at GVG and when noteleport flag is on)
3103        if((nameid == 601 || nameid == 12212) && (map[sd->bl.m].flag.noteleport || map_flag_gvg(sd->bl.m))) {
3104                clif_skill_teleportmessage(sd,0);
3105                return 0;
3106        }
3107        //Fly Wing/Butterfly Wing/Giant Fly Wing (can't use when you in duel) [LuzZza]
3108        if((nameid == 601 || nameid == 602 || nameid == 12212) && (!battle_config.duel_allow_teleport && sd->duel_group)) {
3109                clif_displaymessage(sd->fd, "Duel: Can't use this item in duel.");
3110                return 0;
3111        }
3112        //Butterfly Wing (can't use noreturn flag is on)
3113        if(nameid == 602 && map[sd->bl.m].flag.noreturn)
3114                return 0;
3115        //Dead Branch & Red Pouch & Bloody Branch & Poring Box (can't use at GVG and when nobranch flag is on)
3116        if((nameid == 604 || nameid == 12024 || nameid == 12103 || nameid == 12109) && (map[sd->bl.m].flag.nobranch || map_flag_gvg(sd->bl.m)))
3117                return 0;
3118
3119        //Anodyne/Aleovera not usable while sitting.
3120        if ((nameid == 605 || nameid == 606) && pc_issit(sd))
3121                return 0;
3122         
3123        //added item_noequip.txt items check by Maya&[Lupus]
3124        if (
3125                (map[sd->bl.m].flag.pvp && item->flag.no_equip&1) || // PVP
3126                (map_flag_gvg(sd->bl.m) && item->flag.no_equip&2) || // GVG
3127                (map[sd->bl.m].flag.restricted && item->flag.no_equip&map[sd->bl.m].zone) // Zone restriction
3128        )
3129                return 0;
3130
3131        //Gender check
3132        if(item->sex != 2 && sd->status.sex != item->sex)
3133                return 0;
3134        //Required level check
3135        if(item->elv && sd->status.base_level < (unsigned int)item->elv)
3136                return 0;
3137
3138        //Not equipable by class. [Skotlex]
3139        if (!(
3140                (1<<(sd->class_&MAPID_BASEMASK)) &
3141                (item->class_base[sd->class_&JOBL_2_1?1:(sd->class_&JOBL_2_2?2:0)])
3142        ))
3143                return 0;
3144       
3145        //Not usable by upper class. [Skotlex]
3146        if(!(
3147                (1<<(sd->class_&JOBL_UPPER?1:(sd->class_&JOBL_BABY?2:0))) &
3148                item->class_upper
3149        ))
3150                return 0;
3151
3152        //Dead Branch & Bloody Branch & Porings Box
3153        if((log_config.branch > 0) && (nameid == 604 || nameid == 12103 || nameid == 12109))
3154                log_branch(sd);
3155
3156        return 1;
3157}
3158
3159/*==========================================
3160 * ƒAƒCƒeƒ€‚ðŽg‚€
3161 *------------------------------------------*/
3162int pc_useitem(struct map_session_data *sd,int n)
3163{
3164        unsigned int tick = gettick();
3165        int amount;
3166        struct script_code *script;
3167
3168        nullpo_retr(0, sd);
3169
3170        if(sd->status.inventory[n].nameid <= 0 ||
3171                sd->status.inventory[n].amount <= 0)
3172                return 0;
3173
3174        if(!pc_isUseitem(sd,n))
3175                return 0;
3176
3177         //Prevent mass item usage. [Skotlex]
3178        if(DIFF_TICK(sd->canuseitem_tick, tick) > 0)
3179                return 0;
3180
3181        if (sd->sc.count && (
3182                sd->sc.data[SC_BERSERK] ||
3183                sd->sc.data[SC_MARIONETTE] ||
3184                (sd->sc.data[SC_GRAVITATION] && sd->sc.data[SC_GRAVITATION]->val3 == BCT_SELF) ||
3185                sd->sc.data[SC_TRICKDEAD] ||
3186                sd->sc.data[SC_BLADESTOP] ||
3187                sd->sc.data[SC_HIDING] ||
3188                (sd->sc.data[SC_NOCHAT] && sd->sc.data[SC_NOCHAT]->val1&MANNER_NOITEM)
3189        ))
3190                return 0;
3191
3192        //Since most delay-consume items involve using a "skill-type" target cursor,
3193        //perform a skill-use check before going through. [Skotlex]
3194        //resurrection was picked as testing skill, as a non-offensive, generic skill, it will do.
3195        if (sd->inventory_data[n]->flag.delay_consume && (
3196                sd->ud.skilltimer != -1 ||
3197                DIFF_TICK(tick, sd->ud.canact_tick) < 0 ||
3198                !status_check_skilluse(&sd->bl, &sd->bl, ALL_RESURRECTION, 0)))
3199                return 0;
3200
3201        sd->itemid = sd->status.inventory[n].nameid;
3202        sd->itemindex = n;
3203        if(sd->catch_target_class != -1) //Abort pet catching.
3204                sd->catch_target_class = -1;
3205
3206        amount = sd->status.inventory[n].amount;
3207        script = sd->inventory_data[n]->script;
3208        //Check if the item is to be consumed immediately [Skotlex]
3209        if (sd->inventory_data[n]->flag.delay_consume)
3210                clif_useitemack(sd,n,amount,1);
3211        else {
3212                clif_useitemack(sd,n,amount-1,1);
3213                //Logs (C)onsumable items [Lupus]
3214                if(log_config.enable_logs&0x100)
3215                        log_pick_pc(sd, "C", sd->status.inventory[n].nameid, -1, &sd->status.inventory[n]);
3216                //Logs
3217                pc_delitem(sd,n,1,1);
3218        }
3219        if(sd->status.inventory[n].card[0]==CARD0_CREATE &&
3220                pc_famerank(MakeDWord(sd->status.inventory[n].card[2],sd->status.inventory[n].card[3]), MAPID_ALCHEMIST))
3221        {
3222            potion_flag = 2; // Famous player's potions have 50% more efficiency
3223                 if (sd->sc.data[SC_SPIRIT] && sd->sc.data[SC_SPIRIT]->val2 == SL_ROGUE)
3224                         potion_flag = 3; //Even more effective potions.
3225        }
3226
3227        sd->canuseitem_tick= tick + battle_config.item_use_interval; //Update item use time.
3228        run_script(script,0,sd->bl.id,fake_nd->bl.id);
3229        potion_flag = 0;
3230        return 1;
3231}
3232
3233/*==========================================
3234 * ƒJ?ƒgƒAƒCƒeƒ€’ljÁBŒÂ?‚Ì‚Ýitem\‘¢?‚Ì?Žš‚𖳎‹
3235 *------------------------------------------*/
3236int pc_cart_additem(struct map_session_data *sd,struct item *item_data,int amount)
3237{
3238        struct item_data *data;
3239        int i,w;
3240
3241        nullpo_retr(1, sd);
3242        nullpo_retr(1, item_data);
3243
3244        if(item_data->nameid <= 0 || amount <= 0)
3245                return 1;
3246        data = itemdb_search(item_data->nameid);
3247
3248        if(!itemdb_cancartstore(item_data, pc_isGM(sd)))
3249        {       //Check item trade restrictions [Skotlex]
3250                clif_displaymessage (sd->fd, msg_txt(264));
3251                return 1;
3252        }
3253
3254        if((w=data->weight*amount) + sd->cart_weight > battle_config.max_cart_weight)
3255                return 1;
3256
3257        i=MAX_CART;
3258        if(itemdb_isstackable2(data))
3259        {
3260                ARR_FIND( 0, MAX_CART, i,
3261                        sd->status.cart[i].nameid == item_data->nameid &&
3262                        sd->status.cart[i].card[0] == item_data->card[0] && sd->status.cart[i].card[1] == item_data->card[1] &&
3263                        sd->status.cart[i].card[2] == item_data->card[2] && sd->status.cart[i].card[3] == item_data->card[3] );
3264        };
3265
3266        if( i < MAX_CART )
3267        {// item already in cart, stack it
3268                if(sd->status.cart[i].amount+amount > MAX_AMOUNT)
3269                        return 1; // no room
3270
3271                sd->status.cart[i].amount+=amount;
3272                clif_cart_additem(sd,i,amount,0);
3273        }
3274        else
3275        {// item not stackable or not present, add it
3276                ARR_FIND( 0, MAX_CART, i, sd->status.cart[i].nameid == 0 );
3277                if( i == MAX_CART )
3278                        return 1; // no room
3279
3280                memcpy(&sd->status.cart[i],item_data,sizeof(sd->status.cart[0]));
3281                sd->status.cart[i].amount=amount;
3282                sd->cart_num++;
3283                clif_cart_additem(sd,i,amount,0);
3284        }
3285
3286        sd->cart_weight += w;
3287        clif_updatestatus(sd,SP_CARTINFO);
3288
3289        return 0;
3290}
3291
3292/*==========================================
3293 * ƒJ?ƒgƒAƒCƒeƒ€‚ðŒž‚ç‚·
3294 *------------------------------------------*/
3295int pc_cart_delitem(struct map_session_data *sd,int n,int amount,int type)
3296{
3297        nullpo_retr(1, sd);
3298
3299        if(sd->status.cart[n].nameid==0 ||
3300           sd->status.cart[n].amount<amount)
3301                return 1;
3302
3303        sd->status.cart[n].amount -= amount;
3304        sd->cart_weight -= itemdb_weight(sd->status.cart[n].nameid)*amount ;
3305        if(sd->status.cart[n].amount <= 0){
3306                memset(&sd->status.cart[n],0,sizeof(sd->status.cart[0]));
3307                sd->cart_num--;
3308        }
3309        if(!type) {
3310                clif_cart_delitem(sd,n,amount);
3311                clif_updatestatus(sd,SP_CARTINFO);
3312        }
3313
3314        return 0;
3315}
3316
3317/*==========================================
3318 * ƒJ?ƒg‚ÖƒAƒCƒeƒ€ˆÚ“®
3319 *------------------------------------------*/
3320int pc_putitemtocart(struct map_session_data *sd,int idx,int amount)
3321{
3322        struct item *item_data;
3323
3324        nullpo_retr(0, sd);
3325
3326        if (idx < 0 || idx >= MAX_INVENTORY) //Invalid index check [Skotlex]
3327                return 1;
3328       
3329        item_data = &sd->status.inventory[idx];
3330
3331        if (item_data->nameid==0 || amount < 1 || item_data->amount<amount || sd->vender_id)
3332                return 1;
3333
3334        if (pc_cart_additem(sd,item_data,amount) == 0)
3335                return pc_delitem(sd,idx,amount,0);
3336
3337        return 1;
3338}
3339
3340/*==========================================
3341 * ƒJ?ƒg?‚̃AƒCƒeƒ€?Šm”F(ŒÂ?‚̍·•ª‚ð•Ô‚·)
3342 *------------------------------------------*/
3343int pc_cartitem_amount(struct map_session_data* sd, int idx, int amount)
3344{
3345        struct item* item_data;
3346
3347        nullpo_retr(-1, sd);
3348
3349        item_data = &sd->status.cart[idx];
3350        if( item_data->nameid == 0 || item_data->amount == 0 )
3351                return -1;
3352
3353        return item_data->amount - amount;
3354}
3355
3356/*==========================================
3357 * ƒJ?ƒg‚©‚çƒAƒCƒeƒ€ˆÚ“®
3358 *------------------------------------------*/
3359int pc_getitemfromcart(struct map_session_data *sd,int idx,int amount)
3360{
3361        struct item *item_data;
3362        int flag;
3363
3364        nullpo_retr(0, sd);
3365
3366        if (idx < 0 || idx >= MAX_CART) //Invalid index check [Skotlex]
3367                return 1;
3368       
3369        item_data=&sd->status.cart[idx];
3370
3371        if(item_data->nameid==0 || amount < 1 || item_data->amount<amount || sd->vender_id )
3372                return 1;
3373        if((flag = pc_additem(sd,item_data,amount)) == 0)
3374                return pc_cart_delitem(sd,idx,amount,0);
3375
3376        clif_additem(sd,0,0,flag);
3377        return 1;
3378}
3379
3380/*==========================================
3381 * ƒXƒeƒBƒ‹•iŒöŠJ
3382 *------------------------------------------*/
3383int pc_show_steal(struct block_list *bl,va_list ap)
3384{
3385        struct map_session_data *sd;
3386        int itemid;
3387
3388        struct item_data *item=NULL;
3389        char output[100];
3390
3391        sd=va_arg(ap,struct map_session_data *);
3392        itemid=va_arg(ap,int);
3393
3394        if((item=itemdb_exists(itemid))==NULL)
3395                sprintf(output,"%s stole an Unknown Item (id: %i).",sd->status.name, itemid);
3396        else
3397                sprintf(output,"%s stole %s.",sd->status.name,item->jname);
3398        clif_displaymessage( ((struct map_session_data *)bl)->fd, output);
3399
3400        return 0;
3401}
3402/*==========================================
3403 *
3404 *------------------------------------------*/
3405int pc_steal_item(struct map_session_data *sd,struct block_list *bl, int lv)
3406{
3407        int i,itemid,flag;
3408        double rate;
3409        struct status_data *sd_status, *md_status;
3410        struct mob_data *md;
3411        struct item tmp_item;
3412
3413        if(!sd || !bl || bl->type!=BL_MOB)
3414                return 0;
3415
3416        md = (TBL_MOB *)bl;
3417
3418        if(md->state.steal_flag == UCHAR_MAX || md->sc.opt1) //already stolen from / status change check
3419                return 0;
3420       
3421        sd_status= status_get_status_data(&sd->bl);
3422        md_status= status_get_status_data(bl);
3423
3424        if(md->master_id || md_status->mode&MD_BOSS ||
3425                (md->class_>=1324 && md->class_<1364) || // prevent stealing from treasure boxes [Valaris]
3426                map[bl->m].flag.nomobloot || // check noloot map flag [Lorky]
3427                (battle_config.skill_steal_max_tries && //Reached limit of steal attempts. [Lupus]
3428                        md->state.steal_flag++ >= battle_config.skill_steal_max_tries)
3429        ) { //Can't steal from
3430                md->state.steal_flag = UCHAR_MAX;
3431                return 0;
3432        }
3433
3434        // base skill success chance (percentual)
3435        rate = (sd_status->dex - md_status->dex)/2 + lv*6 + 4;
3436        rate += sd->add_steal_rate;
3437               
3438        if( rate < 1 )
3439                return 0;
3440
3441        // Try dropping one item, in the order from first to last possible slot.
3442        // Droprate is affected by the skill success rate.
3443        for( i = 0; i < MAX_STEAL_DROP; i++ )
3444                if( md->db->dropitem[i].nameid > 0 && itemdb_exists(md->db->dropitem[i].nameid) && rand() % 10000 < md->db->dropitem[i].p * rate/100. )
3445                        break;
3446        if( i == MAX_STEAL_DROP )
3447                return 0;
3448
3449        itemid = md->db->dropitem[i].nameid;
3450        memset(&tmp_item,0,sizeof(tmp_item));
3451        tmp_item.nameid = itemid;
3452        tmp_item.amount = 1;
3453        tmp_item.identify = itemdb_isidentified(itemid);
3454        flag = pc_additem(sd,&tmp_item,1);
3455
3456        //TODO: Should we disable stealing when the item you stole couldn't be added to your inventory? Perhaps players will figure out a way to exploit this behaviour otherwise?
3457        md->state.steal_flag = UCHAR_MAX; //you can't steal from this mob any more
3458
3459        if(flag) { //Failed to steal due to overweight
3460                clif_additem(sd,0,0,flag);
3461                return 0;
3462        }
3463       
3464        if(battle_config.show_steal_in_same_party)
3465                party_foreachsamemap(pc_show_steal,sd,AREA_SIZE,sd,tmp_item.nameid);
3466
3467        //Logs items, Stolen from mobs [Lupus]
3468        if(log_config.enable_logs&0x80) {
3469                log_pick_mob(md, "M", itemid, -1, NULL);
3470                log_pick_pc(sd, "P", itemid, 1, NULL);
3471        }
3472               
3473        //A Rare Steal Global Announce by Lupus
3474        if(md->db->dropitem[i].p<=battle_config.rare_drop_announce) {
3475                struct item_data *i_data;
3476                char message[128];
3477                i_data = itemdb_search(itemid);
3478                sprintf (message, msg_txt(542), (sd->status.name != NULL)?sd->status.name :"GM", md->db->jname, i_data->jname, (float)md->db->dropitem[i].p/100);
3479                //MSG: "'%s' stole %s's %s (chance: %0.02f%%)"
3480                intif_GMmessage(message,strlen(message)+1,0);
3481        }
3482        return 1;
3483}
3484
3485/*==========================================
3486 *
3487 *------------------------------------------*/
3488int pc_steal_coin(struct map_session_data *sd,struct block_list *target)
3489{
3490        int rate,skill;
3491        struct mob_data *md;
3492        if(!sd || !target || target->type != BL_MOB)
3493                return 0;
3494
3495        md = (TBL_MOB*)target;
3496        if(md->state.steal_coin_flag || md->sc.data[SC_STONE] || md->sc.data[SC_FREEZE])
3497                return 0;
3498
3499        if (md->class_>=1324 && md->class_<1364)
3500                return 0;
3501
3502        skill = pc_checkskill(sd,RG_STEALCOIN)*10;
3503        rate = skill + (sd->status.base_level - md->level)*3 + sd->battle_status.dex*2 + sd->battle_status.luk*2;
3504        if(rand()%1000 < rate) {
3505                pc_getzeny(sd,md->level*10 + rand()%100);
3506                md->state.steal_coin_flag = 1;
3507                return 1;
3508        }
3509        return 0;
3510}
3511
3512/*==========================================
3513 * Set's a player position.
3514 * Return values:
3515 * 0 - Success.
3516 * 1 - Invalid map index.
3517 * 2 - Map not in this map-server, and failed to locate alternate map-server.
3518 *------------------------------------------*/
3519int pc_setpos(struct map_session_data* sd, unsigned short mapindex, int x, int y, uint8 clrtype)
3520{
3521        int m;
3522
3523        nullpo_retr(0, sd);
3524
3525        if (!mapindex || !mapindex_id2name(mapindex)) {
3526                ShowDebug("pc_setpos: Passed mapindex(%d) is invalid!\n", mapindex);
3527                return 1;
3528        }
3529
3530        sd->state.changemap = (sd->mapindex != mapindex);
3531        if( sd->state.changemap )
3532        {       //Misc map-changing settings
3533                if (sd->sc.count)
3534                { //Cancel some map related stuff.
3535                        if (sd->sc.data[SC_JAILED])
3536                                return 1; //You may not get out!
3537                        if (sd->sc.data[SC_WARM])
3538                                status_change_end(&sd->bl,SC_WARM,-1);
3539                        if (sd->sc.data[SC_SUN_COMFORT])
3540                                status_change_end(&sd->bl,SC_SUN_COMFORT,-1);
3541                        if (sd->sc.data[SC_MOON_COMFORT])
3542                                status_change_end(&sd->bl,SC_MOON_COMFORT,-1);
3543                        if (sd->sc.data[SC_STAR_COMFORT])
3544                                status_change_end(&sd->bl,SC_STAR_COMFORT,-1);
3545                        if (sd->sc.data[SC_KNOWLEDGE]) {
3546                                struct status_change_entry *sce = sd->sc.data[SC_KNOWLEDGE];
3547                                if (sce->timer != -1)
3548                                        delete_timer(sce->timer, status_change_timer);
3549                                sce->timer = add_timer(gettick() + skill_get_time(SG_KNOWLEDGE, sce->val1), status_change_timer, sd->bl.id, SC_KNOWLEDGE);
3550                        }
3551                }
3552                if (battle_config.clear_unit_onwarp&BL_PC)
3553                        skill_clear_unitgroup(&sd->bl);
3554                party_send_dot_remove(sd); //minimap dot fix [Kevin]
3555                guild_send_dot_remove(sd);
3556                if (sd->regen.state.gc)
3557                        sd->regen.state.gc = 0;
3558        }
3559
3560        m=map_mapindex2mapid(mapindex);
3561        if(m<0) {
3562                uint32 ip;
3563                uint16 port;
3564                //if can't find any map-servers, just abort setting position.
3565                if(!sd->mapindex || map_mapname2ipport(mapindex,&ip,&port))
3566                        return 2;
3567
3568                //remove from map, THEN change x/y coordinates
3569                unit_remove_map_pc(sd,clrtype);
3570                sd->mapindex = mapindex;
3571                sd->bl.x=x;
3572                sd->bl.y=y;
3573                pc_clean_skilltree(sd);
3574                chrif_save(sd,2);
3575                chrif_changemapserver(sd, ip, (short)port);
3576
3577                //Free session data from this map server [Kevin]
3578                unit_free_pc(sd);
3579
3580                return 0;
3581        }
3582
3583        if( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
3584        {
3585                ShowError("pc_setpos: attempt to place player %s (%d:%d) on invalid coordinates (%s-%d,%d)\n", sd->status.name, sd->status.account_id, sd->status.char_id, mapindex_id2name(mapindex),x,y);
3586                x = y = 0; // make it random
3587        }
3588
3589        if( x == 0 && y == 0 )
3590        {// pick a random walkable cell
3591                do {
3592                        x=rand()%(map[m].xs-2)+1;
3593                        y=rand()%(map[m].ys-2)+1;
3594                } while(map_getcell(m,x,y,CELL_CHKNOPASS));
3595        }
3596
3597        if(sd->bl.prev != NULL){
3598                unit_remove_map_pc(sd,clrtype);
3599                clif_changemap(sd,map[m].index,x,y); // [MouseJstr]
3600        } else if(sd->state.active)
3601                //Tag player for rewarping after map-loading is done. [Skotlex]
3602                sd->state.rewarp = 1;
3603       
3604        sd->mapindex =  mapindex;
3605        sd->bl.m = m;
3606        sd->bl.x = sd->ud.to_x = x;
3607        sd->bl.y = sd->ud.to_y = y;
3608
3609        if (sd->status.guild_id > 0 && map[m].flag.gvg_castle)
3610        {       // Increased guild castle regen [Valaris]
3611                struct guild_castle *gc = guild_mapindex2gc(sd->mapindex);
3612                if(gc && gc->guild_id == sd->status.guild_id)
3613                        sd->regen.state.gc = 1;
3614        }
3615
3616        if(sd->status.pet_id > 0 && sd->pd && sd->pd->pet.intimate > 0) {
3617                sd->pd->bl.m = m;
3618                sd->pd->bl.x = sd->pd->ud.to_x = x;
3619                sd->pd->bl.y = sd->pd->ud.to_y = y;
3620                sd->pd->ud.dir = sd->ud.dir;
3621        }
3622
3623        if(merc_is_hom_active(sd->hd)) {        //orn
3624                sd->hd->bl.m = m;
3625                sd->hd->bl.x = sd->hd->ud.to_x = x;
3626                sd->hd->bl.y = sd->hd->ud.to_y = y;
3627                sd->hd->ud.dir = sd->ud.dir;
3628        }
3629
3630        return 0;
3631}
3632
3633/*==========================================
3634 * PC‚̃‰ƒ“ƒ_ƒ€ƒ?ƒv
3635 *------------------------------------------*/
3636int pc_randomwarp(struct map_session_data *sd, int type)
3637{
3638        int x,y,i=0;
3639        int m;
3640
3641        nullpo_retr(0, sd);
3642
3643        m=sd->bl.m;
3644
3645        if (map[sd->bl.m].flag.noteleport)      // ƒeƒŒƒ|?ƒg‹ÖŽ~
3646                return 0;
3647
3648        do{
3649                x=rand()%(map[m].xs-2)+1;
3650                y=rand()%(map[m].ys-2)+1;
3651        }while(map_getcell(m,x,y,CELL_CHKNOPASS) && (i++)<1000 );
3652
3653        if (i < 1000)
3654                return pc_setpos(sd,map[sd->bl.m].index,x,y,type);
3655
3656        return 0;
3657}
3658
3659/*==========================================
3660 * Records a memo point at sd's current position
3661 * pos - entry to replace, (-1: shift oldest entry out)
3662 *------------------------------------------*/
3663int pc_memo(struct map_session_data* sd, int pos)
3664{
3665        int skill;
3666
3667        nullpo_retr(0, sd);
3668
3669        // check mapflags
3670        if( sd->bl.m >= 0 && (map[sd->bl.m].flag.nomemo || map[sd->bl.m].flag.nowarpto) && battle_config.any_warp_GM_min_level > pc_isGM(sd) ) {
3671                clif_skill_teleportmessage(sd, 1); // "Saved point cannot be memorized."
3672                return 0;
3673        }
3674
3675        // check inputs
3676        if( pos < -1 || pos >= MAX_MEMOPOINTS )
3677                return 0; // invalid input
3678
3679        // check required skill level
3680        skill = pc_checkskill(sd, AL_WARP);
3681        if( skill < 1 ) {
3682                clif_skill_memomessage(sd,2); // "You haven't learned Warp."
3683                return 0;
3684        }
3685        if( skill < 2 || skill - 2 < pos ) {
3686                clif_skill_memomessage(sd,1); // "Skill Level is not high enough."
3687                return 0;
3688        }
3689
3690        if( pos == -1 )
3691        {
3692                int i;
3693                // prevent memo-ing the same map multiple times
3694                ARR_FIND( 0, MAX_MEMOPOINTS, i, sd->status.memo_point[i].map == map_id2index(sd->bl.m) );
3695                memmove(&sd->status.memo_point[1], &sd->status.memo_point[0], (min(i,MAX_MEMOPOINTS-1))*sizeof(struct point));
3696                pos = 0;
3697        }
3698
3699        sd->status.memo_point[pos].map = map_id2index(sd->bl.m);
3700        sd->status.memo_point[pos].x = sd->bl.x;
3701        sd->status.memo_point[pos].y = sd->bl.y;
3702
3703        clif_skill_memomessage(sd, 0);
3704
3705        return 1;
3706}
3707
3708//
3709// •Ší??
3710//
3711/*==========================================
3712 * ƒXƒLƒ‹‚Ì?õ Š—L‚µ‚Ä‚¢‚œê‡Lv‚ª•Ô‚é
3713 *------------------------------------------*/
3714int pc_checkskill(struct map_session_data *sd,int skill_id)
3715{
3716        if(sd == NULL) return 0;
3717        if( skill_id>=GD_SKILLBASE){
3718                struct guild *g;
3719                if( sd->status.guild_id>0 && (g=guild_search(sd->status.guild_id))!=NULL)
3720                        return guild_checkskill(g,skill_id);
3721                return 0;
3722        }
3723
3724        if(sd->status.skill[skill_id].id == skill_id)
3725                return (sd->status.skill[skill_id].lv);
3726
3727        return 0;
3728}
3729
3730/*==========================================
3731 * •Ší?X‚É‚æ‚éƒXƒLƒ‹‚Ì??ƒ`ƒFƒbƒN
3732 * ˆø?F
3733 *   struct map_session_data *sd        ƒZƒbƒVƒ‡ƒ“ƒf?ƒ^
3734 *   int nameid                                         ?”õ•iID
3735 * •Ô‚è’lF
3736 *   0          ?X‚È‚µ
3737 *   -1         ƒXƒLƒ‹‚ð‰ðœ
3738 *------------------------------------------*/
3739int pc_checkallowskill(struct map_session_data *sd)
3740{
3741        const enum sc_type scw_list[] = {
3742                SC_TWOHANDQUICKEN,
3743                SC_ONEHAND,
3744                SC_AURABLADE,
3745                SC_PARRYING,
3746                SC_SPEARQUICKEN,
3747                SC_ADRENALINE,
3748                SC_ADRENALINE2,
3749                SC_GATLINGFEVER
3750        };
3751        const enum sc_type scs_list[] = {
3752                SC_AUTOGUARD,
3753                SC_DEFENDER,
3754                SC_REFLECTSHIELD
3755        };
3756        int i;
3757        nullpo_retr(0, sd);
3758
3759        if(!sd->sc.count)
3760                return 0;
3761       
3762        for (i = 0; i < ARRAYLENGTH(scw_list); i++)
3763        {       // Skills requiring specific weapon types
3764                if(sd->sc.data[scw_list[i]] &&
3765                        !pc_check_weapontype(sd,skill_get_weapontype(status_sc2skill(scw_list[i]))))
3766                        status_change_end(&sd->bl,scw_list[i],-1);
3767        }
3768       
3769        if(sd->sc.data[SC_SPURT] && sd->status.weapon)
3770                // Spurt requires bare hands (feet, in fact xD)
3771                status_change_end(&sd->bl,SC_SPURT,-1);
3772       
3773        if(sd->status.shield <= 0) { // Skills requiring a shield
3774                for (i = 0; i < ARRAYLENGTH(scs_list); i++)
3775                        if(sd->sc.data[scs_list[i]])
3776                                status_change_end(&sd->bl,scs_list[i],-1);
3777        }
3778        return 0;
3779}
3780
3781/*==========================================
3782 * ? ”õ•i‚̃`ƒFƒbƒN
3783 *------------------------------------------*/
3784int pc_checkequip(struct map_session_data *sd,int pos)
3785{
3786        int i;
3787
3788        nullpo_retr(-1, sd);
3789
3790        for(i=0;i<EQI_MAX;i++){
3791                if(pos & equip_pos[i])
3792                        return sd->equip_index[i];
3793        }
3794
3795        return -1;
3796}
3797
3798/*==========================================
3799 * Convert's from the client's lame Job ID system
3800 * to the map server's 'makes sense' system. [Skotlex]
3801 *------------------------------------------*/
3802int pc_jobid2mapid(unsigned short b_class)
3803{
3804        int class_ = 0;
3805        if (b_class >= JOB_BABY && b_class <= JOB_SUPER_BABY)
3806        {
3807                if (b_class == JOB_SUPER_BABY)
3808                        b_class = JOB_SUPER_NOVICE;
3809                else
3810                        b_class -= JOB_BABY;
3811                class_|= JOBL_BABY;
3812        }
3813        else if (b_class >= JOB_NOVICE_HIGH && b_class <= JOB_PALADIN2)
3814        {
3815                b_class -= JOB_NOVICE_HIGH;
3816                class_|= JOBL_UPPER;
3817        }
3818        if (b_class >= JOB_KNIGHT && b_class <= JOB_KNIGHT2)
3819                class_|= JOBL_2_1;
3820        else if (b_class >= JOB_CRUSADER && b_class <= JOB_CRUSADER2)
3821                class_|= JOBL_2_2;
3822        switch (b_class)
3823        {
3824                case JOB_NOVICE:
3825                case JOB_SWORDMAN:
3826                case JOB_MAGE:
3827                case JOB_ARCHER:
3828                case JOB_ACOLYTE:
3829                case JOB_MERCHANT:
3830                case JOB_THIEF:
3831                        class_ |= b_class;
3832                        break;
3833                case JOB_KNIGHT:
3834                case JOB_KNIGHT2:
3835                case JOB_CRUSADER:
3836                case JOB_CRUSADER2:
3837                        class_ |= MAPID_SWORDMAN;
3838                        break;
3839                case JOB_PRIEST:
3840                case JOB_MONK:
3841                        class_ |= MAPID_ACOLYTE;
3842                        break;
3843                case JOB_WIZARD:
3844                case JOB_SAGE:
3845                        class_ |= MAPID_MAGE;
3846                        break;
3847                case JOB_BLACKSMITH:
3848                case JOB_ALCHEMIST:
3849                        class_ |= MAPID_MERCHANT;
3850                        break;
3851                case JOB_HUNTER:
3852                case JOB_BARD:
3853                case JOB_DANCER:
3854                        class_ |= MAPID_ARCHER;
3855                        break;
3856                case JOB_ASSASSIN:
3857                case JOB_ROGUE:
3858                        class_ |= MAPID_THIEF;
3859                        break;
3860                       
3861                case JOB_STAR_GLADIATOR:
3862                case JOB_STAR_GLADIATOR2:
3863                        class_ |= JOBL_2_1;
3864                        class_ |= MAPID_TAEKWON;
3865                        break; 
3866                case JOB_SOUL_LINKER:
3867                        class_ |= JOBL_2_2;
3868                case JOB_TAEKWON:
3869                        class_ |= MAPID_TAEKWON;
3870                        break;
3871                case JOB_WEDDING:
3872                        class_ = MAPID_WEDDING;
3873                        break;
3874                case JOB_SUPER_NOVICE: //Super Novices are considered 2-1 novices. [Skotlex]
3875                        class_ |= JOBL_2_1;
3876                        break;
3877                case JOB_GUNSLINGER:
3878                        class_ |= MAPID_GUNSLINGER;
3879                        break;
3880                case JOB_NINJA:
3881                        class_ |= MAPID_NINJA;
3882                        break;
3883                case JOB_XMAS:
3884                        class_ = MAPID_XMAS;
3885                        break;
3886                case JOB_SUMMER:
3887                        class_ = MAPID_SUMMER;
3888                        break;
3889//This is where your errors begin.
3890                case JOB_NECROMANCER: // Necromancer [Brain]
3891                        class_ |= JOBL_2_1;
3892                        class_ |= MAPID_ADEPT;
3893                        break; 
3894                case JOB_WARLOCK: // Warlock [Brain]
3895                        class_ |= JOBL_2_2;
3896                case JOB_ADEPT: // Adept [Brain]
3897                        class_ |= MAPID_ADEPT;
3898                        break;
3899                default:
3900                        return -1;
3901        }
3902        return class_;
3903}
3904
3905//Reverts the map-style class id to the client-style one.
3906int pc_mapid2jobid(unsigned short class_, int sex)
3907{
3908        switch(class_) {
3909                case MAPID_NOVICE:          return JOB_NOVICE;
3910                case MAPID_SWORDMAN:        return JOB_SWORDMAN;
3911                case MAPID_MAGE:            return JOB_MAGE;
3912                case MAPID_ARCHER:          return JOB_ARCHER;
3913                case MAPID_ACOLYTE:         return JOB_ACOLYTE;
3914                case MAPID_MERCHANT:        return JOB_MERCHANT;
3915                case MAPID_THIEF:           return JOB_THIEF;
3916                case MAPID_TAEKWON:         return JOB_TAEKWON;
3917                case MAPID_WEDDING:         return JOB_WEDDING;
3918                case MAPID_GUNSLINGER:      return JOB_GUNSLINGER;
3919                case MAPID_NINJA:           return JOB_NINJA;
3920                case MAPID_XMAS:            return JOB_XMAS;
3921                case MAPID_SUMMER:          return JOB_SUMMER;
3922                // double check this too.
3923                case MAPID_ADEPT:                       return JOB_ADEPT; // Adept [Brain]
3924        //2_1 classes
3925                case MAPID_SUPER_NOVICE:    return JOB_SUPER_NOVICE;
3926                case MAPID_KNIGHT:          return JOB_KNIGHT;
3927                case MAPID_WIZARD:          return JOB_WIZARD;
3928                case MAPID_HUNTER:          return JOB_HUNTER;
3929                case MAPID_PRIEST:          return JOB_PRIEST;
3930                case MAPID_BLACKSMITH:      return JOB_BLACKSMITH;
3931                case MAPID_ASSASSIN:        return JOB_ASSASSIN;
3932                case MAPID_STAR_GLADIATOR:  return JOB_STAR_GLADIATOR;
3933                //and this
3934                case MAPID_NECROMANCER:         return JOB_NECROMANCER; // Necromancer [Brain]
3935        //2_2 classes
3936                case MAPID_CRUSADER:        return JOB_CRUSADER;
3937                case MAPID_SAGE:            return JOB_SAGE;
3938                case MAPID_BARDDANCER:      return sex?JOB_BARD:JOB_DANCER;
3939                case MAPID_MONK:            return JOB_MONK;
3940                case MAPID_ALCHEMIST:       return JOB_ALCHEMIST;
3941                case MAPID_ROGUE:           return JOB_ROGUE;
3942                case MAPID_SOUL_LINKER:     return JOB_SOUL_LINKER;
3943                //this too
3944                case MAPID_WARLOCK:                     return JOB_WARLOCK; // Warlock [Brain]
3945        //1-1: advanced
3946                case MAPID_NOVICE_HIGH:     return JOB_NOVICE_HIGH;
3947                case MAPID_SWORDMAN_HIGH:   return JOB_SWORDMAN_HIGH;
3948                case MAPID_MAGE_HIGH:       return JOB_MAGE_HIGH;
3949                case MAPID_ARCHER_HIGH:     return JOB_ARCHER_HIGH;
3950                case MAPID_ACOLYTE_HIGH:    return JOB_ACOLYTE_HIGH;
3951                case MAPID_MERCHANT_HIGH:   return JOB_MERCHANT_HIGH;
3952                case MAPID_THIEF_HIGH:      return JOB_THIEF_HIGH;
3953        //2_1 advanced
3954                case MAPID_LORD_KNIGHT:     return JOB_LORD_KNIGHT;
3955                case MAPID_HIGH_WIZARD:     return JOB_HIGH_WIZARD;
3956                case MAPID_SNIPER:          return JOB_SNIPER;
3957                case MAPID_HIGH_PRIEST:     return JOB_HIGH_PRIEST;
3958                case MAPID_WHITESMITH:      return JOB_WHITESMITH;
3959                case MAPID_ASSASSIN_CROSS:  return JOB_ASSASSIN_CROSS;
3960        //2_2 advanced
3961                case MAPID_PALADIN:         return JOB_PALADIN;
3962                case MAPID_PROFESSOR:       return JOB_PROFESSOR;
3963                case MAPID_CLOWNGYPSY:      return sex?JOB_CLOWN:JOB_GYPSY;
3964                case MAPID_CHAMPION:        return JOB_CHAMPION;
3965                case MAPID_CREATOR:         return JOB_CREATOR;
3966                case MAPID_STALKER:         return JOB_STALKER;
3967        //1-1 baby
3968                case MAPID_BABY:            return JOB_BABY;
3969                case MAPID_BABY_SWORDMAN:   return JOB_BABY_SWORDMAN;
3970                case MAPID_BABY_MAGE:       return JOB_BABY_MAGE;
3971                case MAPID_BABY_ARCHER:     return JOB_BABY_ARCHER;
3972                case MAPID_BABY_ACOLYTE:    return JOB_BABY_ACOLYTE;
3973                case MAPID_BABY_MERCHANT:   return JOB_BABY_MERCHANT;
3974                case MAPID_BABY_THIEF:      return JOB_BABY_THIEF;
3975        //2_1 baby
3976                case MAPID_SUPER_BABY:      return JOB_SUPER_BABY;
3977                case MAPID_BABY_KNIGHT:     return JOB_BABY_KNIGHT;
3978                case MAPID_BABY_WIZARD:     return JOB_BABY_WIZARD;
3979                case MAPID_BABY_HUNTER:     return JOB_BABY_HUNTER;
3980                case MAPID_BABY_PRIEST:     return JOB_BABY_PRIEST;
3981                case MAPID_BABY_BLACKSMITH: return JOB_BABY_BLACKSMITH;
3982                case MAPID_BABY_ASSASSIN:   return JOB_BABY_ASSASSIN;
3983        //2_2 baby
3984                case MAPID_BABY_CRUSADER:   return JOB_BABY_CRUSADER;
3985                case MAPID_BABY_SAGE:       return JOB_BABY_SAGE;
3986                case MAPID_BABY_BARDDANCER: return sex?JOB_BABY_BARD:JOB_BABY_DANCER;
3987                case MAPID_BABY_MONK:       return JOB_BABY_MONK;
3988                case MAPID_BABY_ALCHEMIST:  return JOB_BABY_ALCHEMIST;
3989                case MAPID_BABY_ROGUE:      return JOB_BABY_ROGUE;
3990                default:
3991                        return -1;
3992        }
3993}
3994
3995/*====================================================
3996 * This function return the name of the job (by [Yor])
3997 *----------------------------------------------------*/
3998char* job_name(int class_)
3999{
4000        switch (class_) {
4001        case JOB_NOVICE:
4002        case JOB_SWORDMAN:
4003        case JOB_MAGE:
4004        case JOB_ARCHER:
4005        case JOB_ACOLYTE:
4006        case JOB_MERCHANT:
4007        case JOB_THIEF:
4008                return msg_txt(550 - JOB_NOVICE+class_);
4009               
4010        case JOB_KNIGHT:
4011        case JOB_PRIEST:
4012        case JOB_WIZARD:
4013        case JOB_BLACKSMITH:
4014        case JOB_HUNTER:
4015        case JOB_ASSASSIN:
4016                return msg_txt(557 - JOB_KNIGHT+class_);
4017               
4018        case JOB_KNIGHT2:
4019                return msg_txt(557);
4020               
4021        case JOB_CRUSADER:
4022        case JOB_MONK:
4023        case JOB_SAGE:
4024        case JOB_ROGUE:
4025        case JOB_ALCHEMIST:
4026        case JOB_BARD:
4027        case JOB_DANCER:
4028                return msg_txt(563 - JOB_CRUSADER+class_);
4029                       
4030        case JOB_CRUSADER2:
4031                return msg_txt(563);
4032               
4033        case JOB_WEDDING:
4034        case JOB_SUPER_NOVICE:
4035
4036        case JOB_XMAS:
4037                return msg_txt(570 - JOB_WEDDING+class_);
4038
4039        case JOB_SUMMER:
4040                return msg_txt(621);
4041
4042        case JOB_NOVICE_HIGH:
4043        case JOB_SWORDMAN_HIGH:
4044        case JOB_MAGE_HIGH:
4045        case JOB_ARCHER_HIGH:
4046        case JOB_ACOLYTE_HIGH:
4047        case JOB_MERCHANT_HIGH:
4048        case JOB_THIEF_HIGH:
4049                return msg_txt(575 - JOB_NOVICE_HIGH+class_);
4050
4051        case JOB_LORD_KNIGHT:
4052        case JOB_HIGH_PRIEST:
4053        case JOB_HIGH_WIZARD:
4054        case JOB_WHITESMITH:
4055        case JOB_SNIPER:
4056        case JOB_ASSASSIN_CROSS:
4057                return msg_txt(582 - JOB_LORD_KNIGHT+class_);
4058               
4059        case JOB_LORD_KNIGHT2:
4060                return msg_txt(582);
4061               
4062        case JOB_PALADIN:
4063        case JOB_CHAMPION:
4064        case JOB_PROFESSOR:
4065        case JOB_STALKER:
4066        case JOB_CREATOR:
4067        case JOB_CLOWN:
4068        case JOB_GYPSY:
4069                return msg_txt(588 - JOB_PALADIN + class_);
4070               
4071        case JOB_PALADIN2:
4072                return msg_txt(588);
4073
4074        case JOB_BABY:
4075        case JOB_BABY_SWORDMAN:
4076        case JOB_BABY_MAGE:
4077        case JOB_BABY_ARCHER:
4078        case JOB_BABY_ACOLYTE:
4079        case JOB_BABY_MERCHANT:
4080        case JOB_BABY_THIEF:
4081                return msg_txt(595 - JOB_BABY + class_);
4082               
4083        case JOB_BABY_KNIGHT:
4084        case JOB_BABY_PRIEST:
4085        case JOB_BABY_WIZARD:
4086        case JOB_BABY_BLACKSMITH:
4087        case JOB_BABY_HUNTER:
4088        case JOB_BABY_ASSASSIN:
4089                return msg_txt(602 - JOB_BABY_KNIGHT + class_);
4090               
4091        case JOB_BABY_KNIGHT2:
4092                return msg_txt(602);
4093               
4094        case JOB_BABY_CRUSADER:
4095        case JOB_BABY_MONK:
4096        case JOB_BABY_SAGE:
4097        case JOB_BABY_ROGUE:
4098        case JOB_BABY_ALCHEMIST:
4099        case JOB_BABY_BARD:
4100        case JOB_BABY_DANCER:
4101                return msg_txt(608 - JOB_BABY_CRUSADER +class_);
4102               
4103        case JOB_BABY_CRUSADER2:
4104                return msg_txt(608);
4105               
4106        case JOB_SUPER_BABY:
4107                return msg_txt(615);
4108               
4109        case JOB_TAEKWON:
4110                return msg_txt(616);
4111        case JOB_STAR_GLADIATOR:
4112        case JOB_STAR_GLADIATOR2:
4113                return msg_txt(617);
4114        case JOB_SOUL_LINKER:
4115                return msg_txt(618);
4116               
4117        case JOB_GUNSLINGER:
4118                return msg_txt(619);
4119        case JOB_NINJA:
4120                return msg_txt(620);
4121//message display for job change?
4122        case JOB_ADEPT: // Adept [Brain]
4123                return msg_txt(1000);//have to add these to the msg_txt in the conf?
4124        case JOB_NECROMANCER: // Necromancer [Brain]
4125                return msg_txt(1001);
4126        case JOB_WARLOCK: // Warlock [Flavio]
4127                return msg_txt(1002);
4128
4129       
4130        default:
4131                return msg_txt(650);
4132        }
4133}
4134
4135int pc_follow_timer(int tid, unsigned int tick, int id, intptr data)
4136{
4137        struct map_session_data *sd;
4138        struct block_list *tbl;
4139
4140        sd = map_id2sd(id);
4141        nullpo_retr(0, sd);
4142
4143        if (sd->followtimer != tid){
4144                ShowError("pc_follow_timer %d != %d\n",sd->followtimer,tid);
4145                sd->followtimer = -1;
4146                return 0;
4147        }
4148
4149        sd->followtimer = -1;
4150        if (pc_isdead(sd))
4151                return 0;
4152
4153        if ((tbl = map_id2bl(sd->followtarget)) == NULL)
4154                return 0;
4155
4156        if(status_isdead(tbl))
4157                return 0;
4158
4159        // either player or target is currently detached from map blocks (could be teleporting),
4160        // but still connected to this map, so we'll just increment the timer and check back later
4161        if (sd->bl.prev != NULL && tbl->prev != NULL &&
4162                sd->ud.skilltimer == -1 && sd->ud.attacktimer == -1 && sd->ud.walktimer == -1)
4163        {
4164                if((sd->bl.m == tbl->m) && unit_can_reach_bl(&sd->bl,tbl, AREA_SIZE, 0, NULL, NULL)) {
4165                        if (!check_distance_bl(&sd->bl, tbl, 5))
4166                                unit_walktobl(&sd->bl, tbl, 5, 0);
4167                } else
4168                        pc_setpos(sd, map_id2index(tbl->m), tbl->x, tbl->y, 3);
4169        }
4170        sd->followtimer = add_timer(
4171                tick + 1000,    // increase time a bit to loosen up map's load
4172                pc_follow_timer, sd->bl.id, 0);
4173        return 0;
4174}
4175
4176int pc_stop_following (struct map_session_data *sd)
4177{
4178        nullpo_retr(0, sd);
4179
4180        if (sd->followtimer != -1) {
4181                delete_timer(sd->followtimer,pc_follow_timer);
4182                sd->followtimer = -1;
4183        }
4184        sd->followtarget = -1;
4185
4186        return 0;
4187}
4188
4189int pc_follow(struct map_session_data *sd,int target_id)
4190{
4191        struct block_list *bl = map_id2bl(target_id);
4192        if (bl == NULL /*|| bl->type != BL_PC*/)
4193                return 1;
4194        if (sd->followtimer != -1)
4195                pc_stop_following(sd);
4196
4197        sd->followtarget = target_id;
4198        pc_follow_timer(-1,gettick(),sd->bl.id,0);
4199
4200        return 0;
4201}
4202
4203int pc_checkbaselevelup(struct map_session_data *sd)
4204{
4205        unsigned int next = pc_nextbaseexp(sd);
4206
4207        if (!next || sd->status.base_exp < next)
4208                return 0;
4209        do {
4210                sd->status.base_exp -= next;
4211                //Kyoki pointed out that the max overcarry exp is the exp needed for the previous level -1. [Skotlex]
4212                if(!battle_config.multi_level_up && sd->status.base_exp > next-1)
4213                        sd->status.base_exp = next-1;
4214
4215                sd->status.base_level ++;
4216
4217                if (battle_config.use_statpoint_table)
4218                        next = statp[sd->status.base_level] - statp[sd->status.base_level-1];
4219                else //Estimated way.
4220                        next = (sd->status.base_level+14) / 5 ;
4221                if (sd->status.status_point > USHRT_MAX - next)
4222                        sd->status.status_point = USHRT_MAX;
4223                else   
4224                        sd->status.status_point += next;
4225
4226        } while ((next=pc_nextbaseexp(sd)) > 0 && sd->status.base_exp >= next);
4227
4228        if (battle_config.pet_lv_rate && sd->pd)        //<Skotlex> update pet's level
4229                status_calc_pet(sd->pd,0);
4230       
4231        clif_updatestatus(sd,SP_STATUSPOINT);
4232        clif_updatestatus(sd,SP_BASELEVEL);
4233        clif_updatestatus(sd,SP_NEXTBASEEXP);
4234        status_calc_pc(sd,0);
4235        status_percent_heal(&sd->bl,100,100);
4236
4237        if((sd->class_&MAPID_UPPERMASK) == MAPID_SUPER_NOVICE)
4238        {
4239                sc_start(&sd->bl,status_skill2sc(PR_KYRIE),100,1,skill_get_time(PR_KYRIE,1));
4240                sc_start(&sd->bl,status_skill2sc(PR_IMPOSITIO),100,1,skill_get_time(PR_IMPOSITIO,1));
4241                sc_start(&sd->bl,status_skill2sc(PR_MAGNIFICAT),100,1,skill_get_time(PR_MAGNIFICAT,1));
4242                sc_start(&sd->bl,status_skill2sc(PR_GLORIA),100,1,skill_get_time(PR_GLORIA,1));
4243                sc_start(&sd->bl,status_skill2sc(PR_SUFFRAGIUM),100,1,skill_get_time(PR_SUFFRAGIUM,1));
4244                if (sd->state.snovice_dead_flag)
4245                        sd->state.snovice_dead_flag = 0; //Reenable steelbody resurrection on dead.
4246        } else
4247        if((sd->class_&MAPID_UPPERMASK) == MAPID_TAEKWON || (sd->class_&MAPID_UPPERMASK) == MAPID_STAR_GLADIATOR)
4248        {
4249                sc_start(&sd->bl,status_skill2sc(AL_INCAGI),100,10,600000);
4250                sc_start(&sd->bl,status_skill2sc(AL_BLESSING),100,10,600000);
4251        }
4252        clif_misceffect(&sd->bl,0);
4253        npc_script_event(sd, NPCE_BASELVUP); //LORDALFA - LVLUPEVENT
4254
4255        if(sd->status.party_id)
4256                party_send_levelup(sd);
4257        return 1;
4258}
4259
4260int pc_checkjoblevelup(struct map_session_data *sd)
4261{
4262        unsigned int next = pc_nextjobexp(sd);
4263
4264        nullpo_retr(0, sd);
4265        if(!next || sd->status.job_exp < next)
4266                return 0;
4267
4268        do {
4269                sd->status.job_exp -= next;
4270                //Kyoki pointed out that the max overcarry exp is the exp needed for the previous level -1. [Skotlex]
4271                if(!battle_config.multi_level_up && sd->status.job_exp > next-1)
4272                        sd->status.job_exp = next-1;
4273
4274                sd->status.job_level ++;
4275                sd->status.skill_point ++;
4276
4277        } while ((next=pc_nextjobexp(sd)) > 0 && sd->status.job_exp >= next);
4278
4279        clif_updatestatus(sd,SP_JOBLEVEL);
4280        clif_updatestatus(sd,SP_NEXTJOBEXP);
4281        clif_updatestatus(sd,SP_SKILLPOINT);
4282        status_calc_pc(sd,0);
4283        clif_misceffect(&sd->bl,1);
4284        if (pc_checkskill(sd, SG_DEVIL) && !pc_nextjobexp(sd))
4285                clif_status_change(&sd->bl,SI_DEVIL, 1); //Permanent blind effect from SG_DEVIL.
4286
4287        npc_script_event(sd, NPCE_JOBLVUP);
4288        return 1;
4289}
4290
4291/*==========================================
4292 * Alters experienced based on self bonuses that do not get even shared to the party.
4293 *------------------------------------------*/
4294static void pc_calcexp(struct map_session_data *sd, unsigned int *base_exp, unsigned int *job_exp, struct block_list *src)
4295{
4296        int bonus = 0;
4297        struct status_data *status = status_get_status_data(src);
4298
4299        if (sd->expaddrace[status->race])
4300                bonus += sd->expaddrace[status->race]; 
4301        bonus += sd->expaddrace[status->mode&MD_BOSS?RC_BOSS:RC_NONBOSS];
4302       
4303        if (battle_config.pk_mode && 
4304                (int)(status_get_lv(src) - sd->status.base_level) >= 20)
4305                bonus += 15; // pk_mode additional exp if monster >20 levels [Valaris] 
4306
4307        if (sd->sc.data[SC_EXPBOOST])
4308                bonus += sd->sc.data[SC_EXPBOOST]->val1;
4309
4310        if (!bonus)
4311                return;
4312       
4313        *base_exp += (unsigned int) cap_value((double)*base_exp * bonus/100., 1, UINT_MAX);
4314        *job_exp += (unsigned int) cap_value((double)*job_exp * bonus/100., 1, UINT_MAX);
4315
4316        return;
4317}
4318/*==========================================
4319 * ??’lŽæ“Ÿ
4320 *------------------------------------------*/
4321int pc_gainexp(struct map_session_data *sd, struct block_list *src, unsigned int base_exp,unsigned int job_exp)
4322{
4323        char output[256];
4324        float nextbp=0, nextjp=0;
4325        unsigned int nextb=0, nextj=0;
4326        nullpo_retr(0, sd);
4327
4328        if(sd->bl.prev == NULL || pc_isdead(sd))
4329                return 0;
4330
4331        if(!battle_config.pvp_exp && map[sd->bl.m].flag.pvp)  // [MouseJstr]
4332                return 0; // no exp on pvp maps
4333
4334        if(sd->status.guild_id>0)
4335                base_exp-=guild_payexp(sd,base_exp);
4336
4337        if(src) pc_calcexp(sd, &base_exp, &job_exp, src);
4338
4339        nextb = pc_nextbaseexp(sd);
4340        nextj = pc_nextjobexp(sd);
4341               
4342        if(sd->state.showexp || battle_config.max_exp_gain_rate){
4343                if (nextb > 0)
4344                        nextbp = (float) base_exp / (float) nextb;
4345                if (nextj > 0)
4346                        nextjp = (float) job_exp / (float) nextj;
4347
4348                if(battle_config.max_exp_gain_rate) {
4349                        if (nextbp > battle_config.max_exp_gain_rate/1000.) {
4350                                //Note that this value should never be greater than the original
4351                                //base_exp, therefore no overflow checks are needed. [Skotlex]
4352                                base_exp = (unsigned int)(battle_config.max_exp_gain_rate/1000.*nextb);
4353                                if (sd->state.showexp)
4354                                        nextbp = (float) base_exp / (float) nextb;
4355                        }
4356                        if (nextjp > battle_config.max_exp_gain_rate/1000.) {
4357                                job_exp = (unsigned int)(battle_config.max_exp_gain_rate/1000.*nextj);
4358                                if (sd->state.showexp)
4359                                        nextjp = (float) job_exp / (float) nextj;
4360                        }
4361                }
4362        }
4363       
4364        //Cap exp to the level up requirement of the previous level when you are at max level, otherwise cap at UINT_MAX (this is required for some S. Novice bonuses). [Skotlex]
4365        if (base_exp) {
4366                nextb = nextb?UINT_MAX:pc_thisbaseexp(sd);
4367                if(sd->status.base_exp > nextb - base_exp)
4368                        sd->status.base_exp = nextb;
4369                else
4370                        sd->status.base_exp += base_exp;
4371                pc_checkbaselevelup(sd);
4372                clif_updatestatus(sd,SP_BASEEXP);
4373        }
4374
4375        if (job_exp) {
4376                nextj = nextj?UINT_MAX:pc_thisjobexp(sd);
4377                if(sd->status.job_exp > nextj - job_exp)
4378                        sd->status.job_exp = nextj;
4379                else
4380                        sd->status.job_exp += job_exp;
4381                pc_checkjoblevelup(sd);
4382                clif_updatestatus(sd,SP_JOBEXP);
4383        }
4384
4385        if(sd->state.showexp){
4386                sprintf(output,
4387                        "Experience Gained Base:%u (%.2f%%) Job:%u (%.2f%%)",base_exp,nextbp*(float)100,job_exp,nextjp*(float)100);
4388                clif_disp_onlyself(sd,output,strlen(output));
4389        }
4390
4391        return 1;
4392}
4393
4394/*==========================================
4395 * Returns max level for this character.
4396 *------------------------------------------*/
4397unsigned int pc_maxbaselv(struct map_session_data *sd)
4398{
4399        return max_level[pc_class2idx(sd->status.class_)][0];
4400};
4401
4402unsigned int pc_maxjoblv(struct map_session_data *sd)
4403{
4404        return max_level[pc_class2idx(sd->status.class_)][1];
4405};
4406
4407/*==========================================
4408 * base level‘€•K—v??’lŒvŽZ
4409 *------------------------------------------*/
4410unsigned int pc_nextbaseexp(struct map_session_data *sd)
4411{
4412        nullpo_retr(0, sd);
4413
4414        if(sd->status.base_level>=pc_maxbaselv(sd) || sd->status.base_level<=0)
4415                return 0;
4416
4417        return exp_table[pc_class2idx(sd->status.class_)][0][sd->status.base_level-1];
4418}
4419
4420unsigned int pc_thisbaseexp(struct map_session_data *sd)
4421{
4422        if(sd->status.base_level>pc_maxbaselv(sd) || sd->status.base_level<=1)
4423                return 0;
4424
4425        return exp_table[pc_class2idx(sd->status.class_)][0][sd->status.base_level-2];
4426}
4427
4428
4429/*==========================================
4430 * job level‘€•K—v??’lŒvŽZ
4431 *------------------------------------------*/
4432unsigned int pc_nextjobexp(struct map_session_data *sd)
4433{
4434        nullpo_retr(0, sd);
4435
4436        if(sd->status.job_level>=pc_maxjoblv(sd) || sd->status.job_level<=0)
4437                return 0;
4438        return exp_table[pc_class2idx(sd->status.class_)][1][sd->status.job_level-1];
4439}
4440
4441unsigned int pc_thisjobexp(struct map_session_data *sd)
4442{
4443        if(sd->status.job_level>pc_maxjoblv(sd) || sd->status.job_level<=1)
4444                return 0;
4445        return exp_table[pc_class2idx(sd->status.class_)][1][sd->status.job_level-2];
4446}
4447
4448static int pc_getstat(struct map_session_data* sd, int type)
4449{
4450        nullpo_retr(-1, sd);
4451        switch( type ) {
4452        case SP_STR: return sd->status.str;
4453        case SP_AGI: return sd->status.agi;
4454        case SP_VIT: return sd->status.vit;
4455        case SP_INT: return sd->status.int_;
4456        case SP_DEX: return sd->status.dex;
4457        case SP_LUK: return sd->status.luk;
4458        default:
4459                return -1;
4460        }
4461}
4462
4463/*==========================================
4464 * •K—vƒXƒe?ƒ^ƒXƒ|ƒCƒ“ƒgŒvŽZ
4465 *------------------------------------------*/
4466int pc_need_status_point(struct map_session_data *sd,int type)
4467{
4468        nullpo_retr(-1, sd);
4469        if( type < SP_STR || type > SP_LUK )
4470                return -1;
4471        return ( 1 + (pc_getstat(sd,type) + 9) / 10 );
4472}
4473
4474/*==========================================
4475 * ”\—Í’l¬’·
4476 *------------------------------------------*/
4477int pc_statusup(struct map_session_data *sd,int type)
4478{
4479        int max, need,val = 0;
4480
4481        nullpo_retr(0, sd);
4482
4483        // check conditions
4484        need = pc_need_status_point(sd,type);
4485        if( type < SP_STR || type > SP_LUK || need < 0 || need > sd->status.status_point )
4486        {
4487                clif_statusupack(sd,type,0,0);
4488                return 1;
4489        }
4490
4491        // check limits
4492        max = pc_maxparameter(sd);
4493        if( pc_getstat(sd,type) >= max )
4494        {
4495                clif_statusupack(sd,type,0,0);
4496                return 1;
4497        }
4498
4499        switch(type){
4500        case SP_STR: val= ++sd->status.str; break;
4501        case SP_AGI: val= ++sd->status.agi; break;
4502        case SP_VIT: val= ++sd->status.vit; break;
4503        case SP_INT: val= ++sd->status.int_; break;
4504        case SP_DEX: val= ++sd->status.dex; break;
4505        case SP_LUK: val= ++sd->status.luk; break;
4506        }
4507
4508        sd->status.status_point-=need;
4509        status_calc_pc(sd,0);
4510
4511        if( need != pc_need_status_point(sd,type) )
4512                clif_updatestatus(sd,type-SP_STR+SP_USTR);
4513        clif_updatestatus(sd,SP_STATUSPOINT);
4514        clif_statusupack(sd,type,1,val);
4515        clif_updatestatus(sd,type); // send after the 'ack' to override the value
4516
4517        return 0;
4518}
4519
4520/*==========================================
4521 * ”\—Í’l¬’·
4522 *------------------------------------------*/
4523int pc_statusup2(struct map_session_data *sd,int type,int val)
4524{
4525        int max;
4526        nullpo_retr(0, sd);
4527
4528        max = pc_maxparameter(sd);
4529       
4530        switch(type){
4531        case SP_STR: sd->status.str = cap_value(sd->status.str + val, 1, max); break;
4532        case SP_AGI: sd->status.agi = cap_value(sd->status.agi + val, 1, max); break;
4533        case SP_VIT: sd->status.vit = cap_value(sd->status.vit + val, 1, max); break;
4534        case SP_INT: sd->status.int_= cap_value(sd->status.int_+ val, 1, max); break;
4535        case SP_DEX: sd->status.dex = cap_value(sd->status.dex + val, 1, max); break;
4536        case SP_LUK: sd->status.luk = cap_value(sd->status.luk + val, 1, max); break;
4537        default:
4538                clif_statusupack(sd,type,0,0);
4539                return 1;
4540        }
4541
4542        status_calc_pc(sd,0);
4543        clif_statusupack(sd,type,1,val);
4544
4545        return 0;
4546}
4547
4548/*==========================================
4549 * ƒXƒLƒ‹ƒ|ƒCƒ“ƒgŠ„‚èU‚è
4550 *------------------------------------------*/
4551int pc_skillup(struct map_session_data *sd,int skill_num)
4552{
4553        nullpo_retr(0, sd);
4554
4555        if(skill_num >= GD_SKILLBASE && skill_num < GD_SKILLBASE+MAX_GUILDSKILL){
4556                guild_skillup(sd, skill_num);
4557                return 0;
4558        }
4559
4560        if(skill_num >= HM_SKILLBASE && skill_num < HM_SKILLBASE+MAX_HOMUNSKILL && sd->hd){
4561                merc_hom_skillup(sd->hd, skill_num);
4562                return 0;
4563        }
4564
4565        if (skill_num < 0 || skill_num >= MAX_SKILL)
4566                return 0;
4567
4568        if(sd->status.skill_point>0 &&
4569                sd->status.skill[skill_num].id &&
4570                sd->status.skill[skill_num].flag==0 && //Don't allow raising while you have granted skills. [Skotlex]
4571                sd->status.skill[skill_num].lv < skill_tree_get_max(skill_num, sd->status.class_) )
4572        {
4573                sd->status.skill[skill_num].lv++;
4574                sd->status.skill_point--;
4575                if (!skill_get_inf(skill_num)) //Only recalculate for passive skills.
4576                        status_calc_pc(sd,0);
4577                else
4578                        pc_check_skilltree(sd, skill_num);
4579                clif_skillup(sd,skill_num);
4580                clif_updatestatus(sd,SP_SKILLPOINT);
4581                clif_skillinfoblock(sd);
4582        }
4583
4584        return 0;
4585}
4586
4587/*==========================================
4588 * /allskill
4589 *------------------------------------------*/
4590int pc_allskillup(struct map_session_data *sd)
4591{
4592        int i,id;
4593
4594        nullpo_retr(0, sd);
4595
4596        for(i=0;i<MAX_SKILL;i++){
4597                if (sd->status.skill[i].flag && sd->status.skill[i].flag != 13){
4598                        sd->status.skill[i].lv=(sd->status.skill[i].flag==1)?0:sd->status.skill[i].flag-2;
4599                        sd->status.skill[i].flag=0;
4600                        if (!sd->status.skill[i].lv)
4601                                sd->status.skill[i].id=0;
4602                }
4603        }
4604
4605        //pc_calc_skilltree takes care of setting the ID to valid skills. [Skotlex]
4606        if (battle_config.gm_allskill > 0 && pc_isGM(sd) >= battle_config.gm_allskill)
4607        {       //Get ALL skills except npc/guild ones. [Skotlex]
4608                //and except SG_DEVIL [Komurka] and MO_TRIPLEATTACK and RG_SNATCHER [ultramage]
4609                for(i=0;i<MAX_SKILL;i++){
4610                        if(!(skill_get_inf2(i)&(INF2_NPC_SKILL|INF2_GUILD_SKILL)) && i!=SG_DEVIL && i!=MO_TRIPLEATTACK && i!=RG_SNATCHER)
4611                                sd->status.skill[i].lv=skill_get_max(i); //Nonexistant skills should return a max of 0 anyway.
4612                }
4613        }
4614        else
4615        {
4616                int inf2;
4617                for(i=0;i < MAX_SKILL_TREE && (id=skill_tree[pc_class2idx(sd->status.class_)][i].id)>0;i++){
4618                        inf2 = skill_get_inf2(id);
4619                        if (
4620                                (inf2&INF2_QUEST_SKILL && !battle_config.quest_skill_learn) ||
4621                                (inf2&(INF2_WEDDING_SKILL|INF2_SPIRIT_SKILL)) ||
4622                                id==SG_DEVIL
4623                        )
4624                                continue; //Cannot be learned normally.
4625                        sd->status.skill[id].lv = skill_tree_get_max(id, sd->status.class_);    // celest
4626                }
4627        }
4628        status_calc_pc(sd,0);
4629        //Required because if you could level up all skills previously,
4630        //the update will not be sent as only the lv variable changes.
4631        clif_skillinfoblock(sd);
4632        return 0;
4633}
4634
4635/*==========================================
4636 * /resetlvl
4637 *------------------------------------------*/
4638int pc_resetlvl(struct map_session_data* sd,int type)
4639{
4640        int  i;
4641
4642        nullpo_retr(0, sd);
4643
4644        if (type != 3) //Also reset skills
4645                pc_resetskill(sd, 0);
4646
4647        if(type == 1){
4648        sd->status.skill_point=0;
4649        sd->status.base_level=1;
4650        sd->status.job_level=1;
4651        sd->status.base_exp=sd->status.base_exp=0;
4652        sd->status.job_exp=sd->status.job_exp=0;
4653        if(sd->sc.option !=0)
4654                sd->sc.option = 0;
4655
4656        sd->status.str=1;
4657        sd->status.agi=1;
4658        sd->status.vit=1;
4659        sd->status.int_=1;
4660        sd->status.dex=1;
4661        sd->status.luk=1;
4662        if(sd->status.class_ == JOB_NOVICE_HIGH)
4663                sd->status.status_point=100;    // not 88 [celest]
4664                // give platinum skills upon changing
4665                pc_skill(sd,142,1,0);
4666                pc_skill(sd,143,1,0);
4667        }
4668
4669        if(type == 2){
4670                sd->status.skill_point=0;
4671                sd->status.base_level=1;
4672                sd->status.job_level=1;
4673                sd->status.base_exp=0;
4674                sd->status.job_exp=0;
4675        }
4676        if(type == 3){
4677                sd->status.base_level=1;
4678                sd->status.base_exp=0;
4679        }
4680        if(type == 4){
4681                sd->status.job_level=1;
4682                sd->status.job_exp=0;
4683        }
4684
4685        clif_updatestatus(sd,SP_STATUSPOINT);
4686        clif_updatestatus(sd,SP_STR);
4687        clif_updatestatus(sd,SP_AGI);
4688        clif_updatestatus(sd,SP_VIT);
4689        clif_updatestatus(sd,SP_INT);
4690        clif_updatestatus(sd,SP_DEX);
4691        clif_updatestatus(sd,SP_LUK);
4692        clif_updatestatus(sd,SP_BASELEVEL);
4693        clif_updatestatus(sd,SP_JOBLEVEL);
4694        clif_updatestatus(sd,SP_STATUSPOINT);
4695        clif_updatestatus(sd,SP_NEXTBASEEXP);
4696        clif_updatestatus(sd,SP_NEXTJOBEXP);
4697        clif_updatestatus(sd,SP_SKILLPOINT);
4698
4699        clif_updatestatus(sd,SP_USTR);  // Updates needed stat points - Valaris
4700        clif_updatestatus(sd,SP_UAGI);
4701        clif_updatestatus(sd,SP_UVIT);
4702        clif_updatestatus(sd,SP_UINT);
4703        clif_updatestatus(sd,SP_UDEX);
4704        clif_updatestatus(sd,SP_ULUK);  // End Addition
4705
4706        for(i=0;i<EQI_MAX;i++) { // unequip items that can't be equipped by base 1 [Valaris]
4707                if(sd->equip_index[i] >= 0)
4708                        if(!pc_isequip(sd,sd->equip_index[i]))
4709                                pc_unequipitem(sd,sd->equip_index[i],2);
4710        }
4711
4712        if ((type == 1 || type == 2 || type == 3) && sd->status.party_id)
4713                party_send_levelup(sd);
4714
4715        status_calc_pc(sd,0);
4716        clif_skillinfoblock(sd);
4717
4718        return 0;
4719}
4720/*==========================================
4721 * /resetstate
4722 *------------------------------------------*/
4723int pc_resetstate(struct map_session_data* sd)
4724{
4725        nullpo_retr(0, sd);
4726       
4727        if (battle_config.use_statpoint_table)
4728        {       // New statpoint table used here - Dexity
4729                int stat;
4730                if (sd->status.base_level > MAX_LEVEL)
4731                {       //statp[] goes out of bounds, can't reset!
4732                        ShowError("pc_resetstate: Can't reset stats of %d:%d, the base level (%d) is greater than the max level supported (%d)\n",
4733                                sd->status.account_id, sd->status.char_id, sd->status.base_level, MAX_LEVEL);
4734                        return 0;
4735                }
4736                stat = statp[sd->status.base_level];
4737                if (sd->class_&JOBL_UPPER)
4738                        stat+=52;       // extra 52+48=100 stat points
4739               
4740                if (stat > USHRT_MAX)
4741                        sd->status.status_point = USHRT_MAX;
4742                else
4743                        sd->status.status_point = stat;
4744        } else { //Use new stat-calculating equation [Skotlex]
4745#define sumsp(a) (((a-1)/10 +2)*(5*((a-1)/10 +1) + (a-1)%10) -10)
4746                int add=0;
4747                add += sumsp(sd->status.str);
4748                add += sumsp(sd->status.agi);
4749                add += sumsp(sd->status.vit);
4750                add += sumsp(sd->status.int_);
4751                add += sumsp(sd->status.dex);
4752                add += sumsp(sd->status.luk);
4753                if (add > USHRT_MAX - sd->status.status_point)
4754                        sd->status.status_point = USHRT_MAX;
4755                else
4756                        sd->status.status_point+=add;
4757        }
4758
4759        sd->status.str=1;
4760        sd->status.agi=1;
4761        sd->status.vit=1;
4762        sd->status.int_=1;
4763        sd->status.dex=1;
4764        sd->status.luk=1;
4765
4766        clif_updatestatus(sd,SP_STR);
4767        clif_updatestatus(sd,SP_AGI);
4768        clif_updatestatus(sd,SP_VIT);
4769        clif_updatestatus(sd,SP_INT);
4770        clif_updatestatus(sd,SP_DEX);
4771        clif_updatestatus(sd,SP_LUK);
4772
4773        clif_updatestatus(sd,SP_USTR);  // Updates needed stat points - Valaris
4774        clif_updatestatus(sd,SP_UAGI);
4775        clif_updatestatus(sd,SP_UVIT);
4776        clif_updatestatus(sd,SP_UINT);
4777        clif_updatestatus(sd,SP_UDEX);
4778        clif_updatestatus(sd,SP_ULUK);  // End Addition
4779       
4780        clif_updatestatus(sd,SP_STATUSPOINT);
4781        status_calc_pc(sd,0);
4782
4783        return 1;
4784}
4785
4786/*==========================================
4787 * /resetskill
4788 * if flag&1, perform block resync and status_calc call.
4789 * if flag&2, just count total amount of skill points used by player, do not really reset.
4790 *------------------------------------------*/
4791int pc_resetskill(struct map_session_data* sd, int flag)
4792{
4793        int i, lv, inf2, skill_point=0;
4794        nullpo_retr(0, sd);
4795
4796        if(!(flag&2))
4797        {       //Remove stuff lost when resetting skills.
4798                if (pc_checkskill(sd, SG_DEVIL) &&  !pc_nextjobexp(sd))
4799                        clif_status_load(&sd->bl, SI_DEVIL, 0); //Remove perma blindness due to skill-reset. [Skotlex]
4800                i = sd->sc.option;
4801                if (i&OPTION_RIDING && pc_checkskill(sd, KN_RIDING))
4802                i&=~OPTION_RIDING;
4803                if(i&OPTION_CART && pc_checkskill(sd, MC_PUSHCART))
4804                        i&=~OPTION_CART;
4805                if(i&OPTION_FALCON && pc_checkskill(sd, HT_FALCON))
4806                        i&=~OPTION_FALCON;
4807
4808                if(i != sd->sc.option)
4809                        pc_setoption(sd, i);
4810
4811                if(merc_is_hom_active(sd->hd) && pc_checkskill(sd, AM_CALLHOMUN))
4812                        merc_hom_vaporize(sd, 0);
4813        }
4814       
4815        for (i = 1; i < MAX_SKILL; i++) {
4816                lv= sd->status.skill[i].lv;
4817                if (lv < 1) continue;
4818
4819                inf2 = skill_get_inf2(i);
4820
4821                if(inf2&(INF2_WEDDING_SKILL|INF2_SPIRIT_SKILL)) //Avoid reseting wedding/linker skills.
4822                        continue;
4823
4824                if (inf2&INF2_QUEST_SKILL && !battle_config.quest_skill_learn)
4825                {       //Only handle quest skills in a special way when you can't learn them manually
4826                        if (battle_config.quest_skill_reset && !(flag&2))
4827                        {       //Wipe them
4828                                sd->status.skill[i].lv = 0;
4829                                sd->status.skill[i].flag = 0;
4830                        }
4831                        continue;
4832                }
4833                if (!sd->status.skill[i].flag)
4834                        skill_point += lv;
4835                else if (sd->status.skill[i].flag > 2 && sd->status.skill[i].flag != 13)
4836                        skill_point += (sd->status.skill[i].flag - 2);
4837
4838                if (!(flag&2)) {
4839                        sd->status.skill[i].lv = 0;
4840                        sd->status.skill[i].flag = 0;
4841                }
4842        }
4843       
4844        if (flag&2 || !skill_point) return skill_point;
4845
4846        if (sd->status.skill_point > USHRT_MAX - skill_point)
4847                sd->status.skill_point = USHRT_MAX;
4848        else
4849                sd->status.skill_point += skill_point;
4850
4851        if (flag&1) {
4852                clif_updatestatus(sd,SP_SKILLPOINT);
4853                clif_skillinfoblock(sd);
4854                status_calc_pc(sd,0);
4855        }
4856        return skill_point;
4857}
4858
4859/*==========================================
4860 * /resetfeel [Komurka]
4861 *------------------------------------------*/
4862int pc_resetfeel(struct map_session_data* sd)
4863{
4864        int i;
4865        nullpo_retr(0, sd);
4866
4867        for (i=0; i<3; i++)
4868        {
4869                sd->feel_map[i].m = -1;
4870                sd->feel_map[i].index = 0;
4871                pc_setglobalreg(sd,sg_info[i].feel_var,0);
4872        }
4873
4874        return 0;
4875}
4876
4877int pc_resethate(struct map_session_data* sd)
4878{
4879        int i;
4880        nullpo_retr(0, sd);
4881
4882        for (i=0; i<3; i++)
4883        {
4884                sd->hate_mob[i] = -1;
4885                pc_setglobalreg(sd,sg_info[i].hate_var,0);
4886        }
4887        return 0;
4888}
4889
4890int pc_skillatk_bonus(struct map_session_data *sd, int skill_num)
4891{
4892        int i;
4893        for (i = 0; i < ARRAYLENGTH(sd->skillatk) && sd->skillatk[i].id; i++)
4894        {
4895                if (sd->skillatk[i].id == skill_num)
4896                        return sd->skillatk[i].val;
4897        }
4898        return 0;
4899}
4900
4901int pc_skillheal_bonus(struct map_session_data *sd, int skill_num)
4902{
4903        int i;
4904        for (i = 0; i < ARRAYLENGTH(sd->skillheal) && sd->skillheal[i].id; i++)
4905        {
4906                if (sd->skillheal[i].id == skill_num)
4907                        return sd->skillheal[i].val;
4908        }
4909        return 0;
4910}
4911
4912void pc_respawn(struct map_session_data* sd, uint8 clrtype)
4913{
4914        if( !pc_isdead(sd) )
4915                return; // not applicable
4916
4917        pc_setstand(sd);
4918        pc_setrestartvalue(sd,3);
4919        if(pc_setpos(sd, sd->status.save_point.map, sd->status.save_point.x, sd->status.save_point.y, clrtype))
4920                clif_resurrection(&sd->bl, 1); //If warping fails, send a normal stand up packet.
4921}
4922
4923static int pc_respawn_timer(int tid, unsigned int tick, int id, intptr data)
4924{
4925        struct map_session_data *sd = map_id2sd(id);
4926        if( sd != NULL )
4927                pc_respawn(sd,0);
4928
4929        return 0;
4930}
4931
4932/*==========================================
4933 * Invoked when a player has received damage
4934 *------------------------------------------*/
4935void pc_damage(struct map_session_data *sd,struct block_list *src,unsigned int hp, unsigned int sp)
4936{
4937        if (sp) clif_updatestatus(sd,SP_SP);
4938        if (!hp) return;
4939
4940        if(pc_issit(sd)) {
4941                pc_setstand(sd);
4942                skill_sit(sd,0);
4943        }
4944
4945        clif_updatestatus(sd,SP_HP);
4946
4947        if(!src || src == &sd->bl)
4948                return;
4949       
4950        if(sd->status.pet_id > 0 && sd->pd && battle_config.pet_damage_support)
4951                pet_target_check(sd,src,1);
4952
4953        sd->canlog_tick = gettick();
4954        return;
4955}
4956
4957int pc_dead(struct map_session_data *sd,struct block_list *src)
4958{
4959        int i=0,j=0,k=0;
4960        unsigned int tick = gettick();
4961               
4962        if(sd->vender_id)
4963                vending_closevending(sd);
4964
4965        for(k = 0; k < 5; k++)
4966        if (sd->devotion[k]){
4967                struct map_session_data *devsd = map_id2sd(sd->devotion[k]);
4968                if (devsd) status_change_end(&devsd->bl,SC_DEVOTION,-1);
4969                sd->devotion[k] = 0;
4970        }
4971
4972        if(sd->status.pet_id > 0 && sd->pd)
4973        {
4974                struct s_pet *pet = &sd->pd->pet;
4975                if(!map[sd->bl.m].flag.noexppenalty){
4976                        pet->intimate -= sd->pd->petDB->die;
4977                        if(pet->intimate < 0)
4978                                pet->intimate = 0;
4979                        clif_send_petdata(sd,sd->pd,1,pet->intimate);
4980                }
4981                if(sd->pd->target_id) // Unlock all targets...
4982                        pet_unlocktarget(sd->pd);
4983        }
4984
4985        if(sd->status.hom_id > 0 && battle_config.homunculus_auto_vapor)        //orn
4986                merc_hom_vaporize(sd, 0);
4987
4988        // Leave duel if you die [LuzZza]
4989        if(battle_config.duel_autoleave_when_die) {
4990                if(sd->duel_group > 0)
4991                        duel_leave(sd->duel_group, sd);
4992                if(sd->duel_invite > 0)
4993                        duel_reject(sd->duel_invite, sd);
4994        }
4995
4996        pc_setdead(sd);
4997        //Reset menu skills/item skills
4998        if (sd->skillitem)
4999                sd->skillitem = sd->skillitemlv = 0;
5000        if (sd->menuskill_id)
5001                sd->menuskill_id = sd->menuskill_val = 0;
5002        //Reset ticks.
5003        sd->hp_loss.tick = sd->sp_loss.tick = sd->hp_regen.tick = sd->sp_regen.tick = 0;
5004
5005        pc_setglobalreg(sd,"PC_DIE_COUNTER",sd->die_counter+1);
5006        pc_setglobalreg(sd,"killerrid",src?src->id:0);
5007        npc_script_event(sd,NPCE_DIE);
5008
5009        if ( sd && sd->spiritball && (sd->class_&MAPID_BASEMASK)==MAPID_GUNSLINGER ) // maybe also monks' spiritballs ?
5010                pc_delspiritball(sd,sd->spiritball,0);
5011
5012        if (src)
5013        switch (src->type) {
5014        case BL_MOB:
5015        {
5016                struct mob_data *md=(struct mob_data *)src;
5017                if(md->target_id==sd->bl.id)
5018                        mob_unlocktarget(md,tick);
5019                if(battle_config.mobs_level_up && md->status.hp &&
5020                        (unsigned int)md->level < pc_maxbaselv(sd) &&
5021                        !md->guardian_data && !md->special_state.ai// Guardians/summons should not level. [Skotlex]
5022                ) {     // monster level up [Valaris]
5023                        clif_misceffect(&md->bl,0);
5024                        md->level++;
5025                        status_calc_mob(md, 0);
5026                        status_percent_heal(src,10,0);
5027                }
5028                if(md->nd)
5029                        mob_script_callback(md, &sd->bl, CALLBACK_KILL);
5030        }
5031        break;
5032        case BL_PET: //Pass on to master...
5033                src = &((TBL_PET*)src)->msd->bl;
5034        break;
5035        case BL_HOM:
5036                src = &((TBL_HOM*)src)->master->bl;
5037        break;
5038        }
5039
5040        if (src && src->type == BL_PC)
5041        {
5042                struct map_session_data *ssd = (struct map_session_data *)src;
5043                pc_setglobalreg(ssd, "killedrid", sd->bl.id);
5044                npc_script_event(ssd, NPCE_KILLPC);
5045
5046                if (battle_config.pk_mode&2) {
5047                        ssd->status.manner -= 5;
5048                        if(ssd->status.manner < 0)
5049                                sc_start(src,SC_NOCHAT,100,0,0);
5050#if 0
5051                        // PK/Karma system code (not enabled yet) [celest]
5052                        // originally from Kade Online, so i don't know if any of these is correct ^^;
5053                        // note: karma is measured REVERSE, so more karma = more 'evil' / less honourable,
5054                        // karma going down = more 'good' / more honourable.
5055                        // The Karma System way...
5056               
5057                        if (sd->status.karma > ssd->status.karma) {     // If player killed was more evil
5058                                sd->status.karma--;
5059                                ssd->status.karma--;
5060                        }
5061                        else if (sd->status.karma < ssd->status.karma)  // If player killed was more good
5062                                ssd->status.karma++;
5063       
5064
5065                        // or the PK System way...
5066       
5067                        if (sd->status.karma > 0)       // player killed is dishonourable?
5068                                ssd->status.karma--; // honour points earned
5069                        sd->status.karma++;     // honour points lost
5070               
5071                        // To-do: Receive exp on certain occasions
5072#endif
5073                }
5074        }
5075
5076        if(battle_config.bone_drop==2
5077                || (battle_config.bone_drop==1 && map[sd->bl.m].flag.pvp))
5078        {
5079                struct item item_tmp;
5080                memset(&item_tmp,0,sizeof(item_tmp));
5081                item_tmp.nameid=7420; //PVP Skull item ID
5082                item_tmp.identify=1;
5083                item_tmp.card[0]=CARD0_CREATE;
5084                item_tmp.card[1]=0;
5085                item_tmp.card[2]=GetWord(sd->status.char_id,0); // CharId
5086                item_tmp.card[3]=GetWord(sd->status.char_id,1);
5087                map_addflooritem(&item_tmp,1,sd->bl.m,sd->bl.x,sd->bl.y,0,0,0,0);
5088        }
5089
5090        // activate Steel body if a super novice dies at 99+% exp [celest]
5091        if ((sd->class_&MAPID_UPPERMASK) == MAPID_SUPER_NOVICE && !sd->state.snovice_dead_flag)
5092        {
5093                unsigned int next = pc_nextbaseexp(sd);
5094                if( next == 0 ) next = pc_thisbaseexp(sd);
5095                if( get_percentage(sd->status.base_exp,next) >= 99 && !map_flag_gvg(sd->bl.m) )
5096                {
5097                        sd->state.snovice_dead_flag = 1;
5098                        pc_setstand(sd);
5099                        status_percent_heal(&sd->bl, 100, 100);
5100                        clif_resurrection(&sd->bl, 1);
5101                        if(battle_config.pc_invincible_time)
5102                                pc_setinvincibletimer(sd, battle_config.pc_invincible_time);
5103                        sc_start(&sd->bl,status_skill2sc(MO_STEELBODY),100,1,skill_get_time(MO_STEELBODY,1));
5104                        if(map_flag_gvg(sd->bl.m))
5105                                pc_respawn_timer(-1, gettick(), sd->bl.id, 0);
5106                        return 0;
5107                }
5108        }
5109
5110        // changed penalty options, added death by player if pk_mode [Valaris]
5111        if(battle_config.death_penalty_type
5112                && (sd->class_&MAPID_UPPERMASK) != MAPID_NOVICE // only novices will receive no penalty
5113                && !map[sd->bl.m].flag.noexppenalty && !map_flag_gvg(sd->bl.m)
5114                && !sd->sc.data[SC_BABY] && !sd->sc.data[SC_LIFEINSURANCE])
5115        {
5116                unsigned int base_penalty =0;
5117                if (battle_config.death_penalty_base > 0) {
5118                        switch (battle_config.death_penalty_type) {
5119                                case 1:
5120                                        base_penalty = (unsigned int) ((double)pc_nextbaseexp(sd) * (double)battle_config.death_penalty_base/10000);
5121                                break;
5122                                case 2:
5123                                        base_penalty = (unsigned int) ((double)sd->status.base_exp * (double)battle_config.death_penalty_base/10000);
5124                                break;
5125                        }
5126                        if(base_penalty) {
5127                                if (battle_config.pk_mode && src && src->type==BL_PC)
5128                                        base_penalty*=2;
5129                                if(sd->status.base_exp < base_penalty)
5130                                        sd->status.base_exp = 0;
5131                                else
5132                                        sd->status.base_exp -= base_penalty;
5133                                clif_updatestatus(sd,SP_BASEEXP);
5134                        }
5135                }
5136                if(battle_config.death_penalty_job > 0)
5137                {
5138                        base_penalty = 0;
5139                        switch (battle_config.death_penalty_type) {
5140                                case 1:
5141                                        base_penalty = (unsigned int) ((double)pc_nextjobexp(sd) * (double)battle_config.death_penalty_job/10000);
5142                                break;
5143                                case 2:
5144                                        base_penalty = (unsigned int) ((double)sd->status.job_exp * (double)battle_config.death_penalty_job/10000);
5145                                break;
5146                        }
5147                        if(base_penalty) {
5148                                if (battle_config.pk_mode && src && src->type==BL_PC)
5149                                        base_penalty*=2;
5150                                if(sd->status.job_exp < base_penalty)
5151                                        sd->status.job_exp = 0;
5152                                else
5153                                        sd->status.job_exp -= base_penalty;
5154                                clif_updatestatus(sd,SP_JOBEXP);
5155                        }
5156                }
5157                if(battle_config.zeny_penalty > 0 && !map[sd->bl.m].flag.nozenypenalty)
5158                {
5159                        base_penalty = (unsigned int)((double)sd->status.zeny * (double)battle_config.zeny_penalty / 10000.);
5160                        if(base_penalty)
5161                                pc_payzeny(sd, base_penalty);
5162                }
5163        }
5164
5165        if(map[sd->bl.m].flag.pvp_nightmaredrop)
5166        { // Moved this outside so it works when PVP isn't enabled and during pk mode [Ancyker]
5167                for(j=0;j<MAX_DROP_PER_MAP;j++){
5168                        int id = map[sd->bl.m].drop_list[j].drop_id;
5169                        int type = map[sd->bl.m].drop_list[j].drop_type;
5170                        int per = map[sd->bl.m].drop_list[j].drop_per;
5171                        if(id == 0)
5172                                continue;
5173                        if(id == -1){
5174                                int eq_num=0,eq_n[MAX_INVENTORY];
5175                                memset(eq_n,0,sizeof(eq_n));
5176                                for(i=0;i<MAX_INVENTORY;i++){
5177                                        int k;
5178                                        if( (type == 1 && !sd->status.inventory[i].equip)
5179                                                || (type == 2 && sd->status.inventory[i].equip)
5180                                                ||  type == 3)
5181                                        {
5182                                                ARR_FIND( 0, MAX_INVENTORY, k, eq_n[k] <= 0 );
5183                                                if( k < MAX_INVENTORY )
5184                                                        eq_n[k] = i;
5185
5186                                                eq_num++;
5187                                        }
5188                                }
5189                                if(eq_num > 0){
5190                                        int n = eq_n[rand()%eq_num];
5191                                        if(rand()%10000 < per){
5192                                                if(sd->status.inventory[n].equip)
5193                                                        pc_unequipitem(sd,n,3);
5194                                                pc_dropitem(sd,n,1);
5195                                        }
5196                                }
5197                        }
5198                        else if(id > 0){
5199                                for(i=0;i<MAX_INVENTORY;i++){
5200                                        if(sd->status.inventory[i].nameid == id
5201                                                && rand()%10000 < per
5202                                                && ((type == 1 && !sd->status.inventory[i].equip)
5203                                                        || (type == 2 && sd->status.inventory[i].equip)
5204                                                        || type == 3) ){
5205                                                if(sd->status.inventory[i].equip)
5206                                                        pc_unequipitem(sd,i,3);
5207                                                pc_dropitem(sd,i,1);
5208                                                break;
5209                                        }
5210                                }
5211                        }
5212                }
5213        }
5214        // pvp
5215        // disable certain pvp functions on pk_mode [Valaris]
5216        if (map[sd->bl.m].flag.gvg_dungeon ||
5217                (map[sd->bl.m].flag.pvp && !battle_config.pk_mode && !map[sd->bl.m].flag.pvp_nocalcrank))
5218        {       //Pvp points always take effect on gvg_dungeon maps.
5219                sd->pvp_point -= 5;
5220                sd->pvp_lost++;
5221                if (src && src->type == BL_PC) {
5222                        struct map_session_data *ssd = (struct map_session_data *)src;
5223                        ssd->pvp_point++;
5224                        ssd->pvp_won++;
5225                }
5226                if( sd->pvp_point < 0 ){
5227                        sd->pvp_point=0;
5228                        add_timer(tick+1000, pc_respawn_timer,sd->bl.id,0);
5229                        return 1|8;
5230                }
5231        }
5232        //GvG
5233        if(map_flag_gvg(sd->bl.m)){
5234                add_timer(tick+1000, pc_respawn_timer,sd->bl.id,0);
5235                return 1|8;
5236        }
5237
5238        //Reset "can log out" tick.
5239        if (battle_config.prevent_logout)
5240                sd->canlog_tick = gettick() - battle_config.prevent_logout;
5241        return 1;
5242}
5243
5244void pc_revive(struct map_session_data *sd,unsigned int hp, unsigned int sp)
5245{
5246        if(hp) clif_updatestatus(sd,SP_HP);
5247        if(sp) clif_updatestatus(sd,SP_SP);
5248
5249        pc_setstand(sd);
5250        if(battle_config.pc_invincible_time > 0)
5251                pc_setinvincibletimer(sd, battle_config.pc_invincible_time);
5252}
5253// script? ˜A
5254//
5255/*==========================================
5256 * script—pPCƒXƒe?ƒ^ƒX?‚ݏo‚µ
5257 *------------------------------------------*/
5258int pc_readparam(struct map_session_data* sd,int type)
5259{
5260        int val = 0;
5261
5262        nullpo_retr(0, sd);
5263
5264        switch(type) {
5265        case SP_SKILLPOINT:  val = sd->status.skill_point; break;
5266        case SP_STATUSPOINT: val = sd->status.status_point; break;
5267        case SP_ZENY:        val = sd->status.zeny; break;
5268        case SP_BASELEVEL:   val = sd->status.base_level; break;
5269        case SP_JOBLEVEL:    val = sd->status.job_level; break;
5270        case SP_CLASS:       val = sd->status.class_; break;
5271        case SP_BASEJOB:     val = pc_mapid2jobid(sd->class_&MAPID_UPPERMASK, sd->status.sex); break; //Base job, extracting upper type.
5272        case SP_UPPER:       val = sd->class_&JOBL_UPPER?1:(sd->class_&JOBL_BABY?2:0); break;
5273        case SP_BASECLASS:   val = pc_mapid2jobid(sd->class_&MAPID_BASEMASK, sd->status.sex); break; //Extract base class tree. [Skotlex]
5274        case SP_SEX:         val = sd->status.sex; break;
5275        case SP_WEIGHT:      val = sd->weight; break;
5276        case SP_MAXWEIGHT:   val = sd->max_weight; break;
5277        case SP_BASEEXP:     val = sd->status.base_exp; break;
5278        case SP_JOBEXP:      val = sd->status.job_exp; break;
5279        case SP_NEXTBASEEXP: val = pc_nextbaseexp(sd); break;
5280        case SP_NEXTJOBEXP:  val = pc_nextjobexp(sd); break;
5281        case SP_HP:          val = sd->battle_status.hp; break;
5282        case SP_MAXHP:       val = sd->battle_status.max_hp; break;
5283        case SP_SP:          val = sd->battle_status.sp; break;
5284        case SP_MAXSP:       val = sd->battle_status.max_sp; break;
5285        case SP_STR:         val = sd->status.str; break;
5286        case SP_AGI:         val = sd->status.agi; break;
5287        case SP_VIT:         val = sd->status.vit; break;
5288        case SP_INT:         val = sd->status.int_; break;
5289        case SP_DEX:         val = sd->status.dex; break;
5290        case SP_LUK:         val = sd->status.luk; break;
5291        case SP_KARMA:       val = sd->status.karma; break;
5292        case SP_MANNER:      val = sd->status.manner; break;
5293        case SP_FAME:        val = sd->status.fame; break;
5294        }
5295
5296        return val;
5297}
5298
5299/*==========================================
5300 * script—pPCƒXƒe?ƒ^ƒXÝ’è
5301 *------------------------------------------*/
5302int pc_setparam(struct map_session_data *sd,int type,int val)
5303{
5304        int i = 0;
5305
5306        nullpo_retr(0, sd);
5307
5308        switch(type){
5309        case SP_BASELEVEL:
5310                if ((unsigned int)val > pc_maxbaselv(sd)) //Capping to max
5311                        val = pc_maxbaselv(sd);
5312                if ((unsigned int)val > sd->status.base_level) {
5313                        int stat=0;
5314                        for (i = 1; i <= (int)((unsigned int)val - sd->status.base_level); i++)
5315                                stat += (sd->status.base_level + i + 14) / 5 ;
5316                        if (sd->status.status_point > USHRT_MAX - stat)
5317                               
5318                                sd->status.status_point = USHRT_MAX;
5319                        else
5320                                sd->status.status_point += stat;
5321                }
5322                sd->status.base_level = (unsigned int)val;
5323                sd->status.base_exp = 0;
5324                clif_updatestatus(sd, SP_BASELEVEL);
5325                clif_updatestatus(sd, SP_NEXTBASEEXP);
5326                clif_updatestatus(sd, SP_STATUSPOINT);
5327                clif_updatestatus(sd, SP_BASEEXP);
5328                status_calc_pc(sd, 0);
5329                break;
5330        case SP_JOBLEVEL:
5331                if ((unsigned int)val >= sd->status.job_level) {
5332                        if ((unsigned int)val > pc_maxjoblv(sd)) val = pc_maxjoblv(sd);
5333                        if (sd->status.skill_point > USHRT_MAX - val + sd->status.job_level)
5334                                sd->status.skill_point = USHRT_MAX;
5335                        else
5336                                sd->status.skill_point += val-sd->status.job_level;
5337                        clif_updatestatus(sd, SP_SKILLPOINT);
5338                }
5339                sd->status.job_level = (unsigned int)val;
5340                sd->status.job_exp = 0;
5341                clif_updatestatus(sd, SP_JOBLEVEL);
5342                clif_updatestatus(sd, SP_NEXTJOBEXP);
5343                clif_updatestatus(sd, SP_JOBEXP);
5344                status_calc_pc(sd, 0);
5345                clif_updatestatus(sd,type);
5346                break;
5347        case SP_SKILLPOINT:
5348                sd->status.skill_point = val;
5349                break;
5350        case SP_STATUSPOINT:
5351                sd->status.status_point = val;
5352                break;
5353        case SP_ZENY:
5354                sd->status.zeny = cap_value(val, 0, MAX_ZENY);
5355                break;
5356        case SP_BASEEXP:
5357                if(pc_nextbaseexp(sd) > 0) {
5358                        sd->status.base_exp = val;
5359                        pc_checkbaselevelup(sd);
5360                }
5361                break;
5362        case SP_JOBEXP:
5363                if(pc_nextjobexp(sd) > 0) {
5364                        sd->status.job_exp = val;
5365                        pc_checkjoblevelup(sd);
5366                }
5367                break;
5368        case SP_SEX:
5369                sd->status.sex = val;
5370                break;
5371        case SP_WEIGHT:
5372                sd->weight = val;
5373                break;
5374        case SP_MAXWEIGHT:
5375                sd->max_weight = val;
5376                break;
5377        case SP_HP:
5378                sd->battle_status.hp = val;
5379                break;
5380        case SP_MAXHP:
5381                sd->battle_status.max_hp = val;
5382                break;
5383        case SP_SP:
5384                sd->battle_status.sp = val;
5385                break;
5386        case SP_MAXSP:
5387                sd->battle_status.max_sp = val;
5388                break;
5389        case SP_STR:
5390                sd->status.str = val;
5391                break;
5392        case SP_AGI:
5393                sd->status.agi = val;
5394                break;
5395        case SP_VIT:
5396                sd->status.vit = val;
5397                break;
5398        case SP_INT:
5399                sd->status.int_ = val;
5400                break;
5401        case SP_DEX:
5402                sd->status.dex = val;
5403                break;
5404        case SP_LUK:
5405                sd->status.luk = val;
5406                break;
5407        case SP_KARMA:
5408                sd->status.karma = val;
5409                break;
5410        case SP_MANNER:
5411                sd->status.manner = val;
5412                break;
5413        case SP_FAME:
5414                sd->status.fame = val;
5415                break;
5416        }
5417        clif_updatestatus(sd,type);
5418
5419        return 1;
5420}
5421
5422/*==========================================
5423 * HP/SP Healing. If flag is passed, the heal type is through clif_heal, otherwise update status.
5424 *------------------------------------------*/
5425void pc_heal(struct map_session_data *sd,unsigned int hp,unsigned int sp, int type)
5426{
5427        if (type) {
5428                if (hp)
5429                        clif_heal(sd->fd,SP_HP,hp);
5430                if (sp)
5431                        clif_heal(sd->fd,SP_SP,sp);
5432        } else {
5433                if(hp)
5434                        clif_updatestatus(sd,SP_HP);
5435                if(sp)
5436                        clif_updatestatus(sd,SP_SP);
5437        }
5438        return;
5439}
5440
5441/*==========================================
5442 * HP/SP‰ñ•œ
5443 *------------------------------------------*/
5444int pc_itemheal(struct map_session_data *sd,int itemid, int hp,int sp)
5445{
5446        int i, bonus;
5447
5448        if(hp) {
5449                bonus = 100 + (sd->battle_status.vit<<1)
5450                        + pc_checkskill(sd,SM_RECOVERY)*10
5451                        + pc_checkskill(sd,AM_LEARNINGPOTION)*5;
5452                // A potion produced by an Alchemist in the Fame Top 10 gets +50% effect [DracoRPG]
5453                if (potion_flag > 1)
5454                        bonus += bonus*(potion_flag-1)*50/100;
5455                //Item Group bonuses
5456                bonus += bonus*itemdb_group_bonus(sd, itemid)/100;
5457                //Individual item bonuses.
5458                for(i = 0; i < ARRAYLENGTH(sd->itemhealrate) && sd->itemhealrate[i].nameid; i++)
5459                {
5460                        if (sd->itemhealrate[i].nameid == itemid) {
5461                                bonus += bonus*sd->itemhealrate[i].rate/100;
5462                                break;
5463                        }
5464                }
5465                if(bonus!=100)
5466                        hp = hp * bonus / 100;
5467
5468                // Recovery Potion
5469                if( sd->sc.data[SC_INCHEALRATE] )
5470                        hp += (int)(hp * sd->sc.data[SC_INCHEALRATE]->val1/100.);
5471        }
5472        if(sp) {
5473                bonus = 100 + (sd->battle_status.int_<<1)
5474                        + pc_checkskill(sd,MG_SRECOVERY)*10
5475                        + pc_checkskill(sd,AM_LEARNINGPOTION)*5;
5476                if (potion_flag > 1)
5477                        bonus += bonus*(potion_flag-1)*50/100;
5478                if(bonus != 100)
5479                        sp = sp * bonus / 100;
5480        }
5481
5482        if (sd->sc.data[SC_CRITICALWOUND])
5483        {
5484                hp -= hp * sd->sc.data[SC_CRITICALWOUND]->val2 / 100;
5485                sp -= sp * sd->sc.data[SC_CRITICALWOUND]->val2 / 100;
5486        }
5487
5488        return status_heal(&sd->bl, hp, sp, 1);
5489}
5490
5491/*==========================================
5492 * HP/SP‰ñ•œ
5493 *------------------------------------------*/
5494int pc_percentheal(struct map_session_data *sd,int hp,int sp)
5495{
5496        nullpo_retr(0, sd);
5497
5498        if(hp > 100) hp = 100;
5499        else
5500        if(hp <-100) hp =-100;
5501
5502        if(sp > 100) sp = 100;
5503        else
5504        if(sp <-100) sp =-100;
5505
5506        if(hp >= 0 && sp >= 0) //Heal
5507                return status_percent_heal(&sd->bl, hp, sp);
5508
5509        if(hp <= 0 && sp <= 0) //Damage (negative rates indicate % of max rather than current), and only kill target IF the specified amount is 100%
5510                return status_percent_damage(NULL, &sd->bl, hp, sp, hp==-100);
5511
5512        //Crossed signs
5513        if(hp) {
5514                if(hp > 0)
5515                        status_percent_heal(&sd->bl, hp, 0);
5516                else
5517                        status_percent_damage(NULL, &sd->bl, hp, 0, hp==-100);
5518        }
5519       
5520        if(sp) {
5521                if(sp > 0)
5522                        status_percent_heal(&sd->bl, 0, sp);
5523                else
5524                        status_percent_damage(NULL, &sd->bl, 0, sp, false);
5525        }
5526        return 0;
5527}
5528
5529/*==========================================
5530 * E?X
5531 * ˆø?  job E‹Æ 0`23
5532 *              upper ’ʏí 0, ?¶ 1, —{Žq 2, ‚»‚Ì‚Ü‚Ü -1
5533 * Rewrote to make it tidider [Celest]
5534 *------------------------------------------*/
5535int pc_jobchange(struct map_session_data *sd,int job, int upper)
5536{
5537        int i, fame_flag=0;
5538        int b_class;
5539
5540        nullpo_retr(0, sd);
5541
5542        if (job < 0)
5543                return 1;
5544
5545        //Normalize job.
5546        b_class = pc_jobid2mapid(job);
5547        if (b_class == -1)
5548                return 1;
5549        switch (upper) {
5550                case 1:
5551                        b_class|= JOBL_UPPER; 
5552                        break;
5553                case 2:
5554                        b_class|= JOBL_BABY;
5555                        break;
5556        }
5557        //This will automatically adjust bard/dancer classes to the correct gender
5558        //That is, if you try to jobchange into dancer, it will turn you to bard.       
5559        job = pc_mapid2jobid(b_class, sd->status.sex);
5560        if (job == -1)
5561                return 1;
5562       
5563        if ((unsigned short)b_class == sd->class_)
5564                return 1; //Nothing to change.
5565        // check if we are changing from 1st to 2nd job
5566        if (b_class&JOBL_2) {
5567                if (!(sd->class_&JOBL_2))
5568                        sd->change_level = sd->status.job_level;
5569                else if (!sd->change_level)
5570                        sd->change_level = 40; //Assume 40?
5571                pc_setglobalreg (sd, "jobchange_level", sd->change_level);
5572        }
5573
5574        if(sd->cloneskill_id) {
5575                sd->cloneskill_id = 0;
5576                pc_setglobalreg(sd, "CLONE_SKILL", 0);
5577                pc_setglobalreg(sd, "CLONE_SKILL_LV", 0);
5578        }
5579        if ((b_class&&MAPID_UPPERMASK) != (sd->class_&MAPID_UPPERMASK))
5580        { //Things to remove when changing class tree.
5581                const int class_ = pc_class2idx(sd->status.class_);
5582                short id;
5583                for(i = 0; i < MAX_SKILL_TREE && (id = skill_tree[class_][i].id) > 0; i++) {
5584                        //Remove status specific to your current tree skills.
5585                        enum sc_type sc = status_skill2sc(id);
5586                        if (sc > SC_COMMON_MAX && sd->sc.data[sc])
5587                                status_change_end(&sd->bl, sc, -1);
5588                }
5589        }
5590       
5591        sd->status.class_ = job;
5592        fame_flag = pc_famerank(sd->status.char_id,sd->class_&MAPID_UPPERMASK);
5593        sd->class_ = (unsigned short)b_class;
5594        sd->status.job_level=1;
5595        sd->status.job_exp=0;
5596        clif_updatestatus(sd,SP_JOBLEVEL);
5597        clif_updatestatus(sd,SP_JOBEXP);
5598        clif_updatestatus(sd,SP_NEXTJOBEXP);
5599
5600        for(i=0;i<EQI_MAX;i++) {
5601                if(sd->equip_index[i] >= 0)
5602                        if(!pc_isequip(sd,sd->equip_index[i]))
5603                                pc_unequipitem(sd,sd->equip_index[i],2);        // ?”õŠO‚µ
5604        }
5605
5606        //Change look, if disguised, you need to undisguise
5607        //to correctly calculate new job sprite without
5608        if (sd->disguise)
5609                pc_disguise(sd, 0);
5610
5611        status_set_viewdata(&sd->bl, job);
5612        clif_changelook(&sd->bl,LOOK_BASE,sd->vd.class_); // move sprite update to prevent client crashes with incompatible equipment [Valaris]
5613        if(sd->vd.cloth_color)
5614                clif_changelook(&sd->bl,LOOK_CLOTHES_COLOR,sd->vd.cloth_color);
5615
5616        //Update skill tree.
5617        pc_calc_skilltree(sd);
5618        clif_skillinfoblock(sd);
5619
5620        //Remove peco/cart/falcon
5621        i = sd->sc.option;
5622        if(i&OPTION_RIDING && !pc_checkskill(sd, KN_RIDING))
5623                i&=~OPTION_RIDING;
5624        if(i&OPTION_CART && !pc_checkskill(sd, MC_PUSHCART))
5625                i&=~OPTION_CART;
5626        if(i&OPTION_FALCON && !pc_checkskill(sd, HT_FALCON))
5627                i&=~OPTION_FALCON;
5628
5629        if(i != sd->sc.option)
5630                pc_setoption(sd, i);
5631
5632        if(merc_is_hom_active(sd->hd) && !pc_checkskill(sd, AM_CALLHOMUN))
5633                merc_hom_vaporize(sd, 0);
5634       
5635        if(sd->status.manner < 0)
5636                clif_changestatus(&sd->bl,SP_MANNER,sd->status.manner);
5637
5638        status_calc_pc(sd,0);
5639        pc_checkallowskill(sd);
5640        pc_equiplookall(sd);
5641
5642        //if you were previously famous, not anymore.
5643        if (fame_flag) {
5644                chrif_save(sd,0);
5645                chrif_buildfamelist();
5646        } else if (sd->status.fame > 0) {
5647                //It may be that now they are famous?
5648                switch (sd->class_&MAPID_UPPERMASK) {
5649                        case MAPID_BLACKSMITH:
5650                        case MAPID_ALCHEMIST:
5651                        case MAPID_TAEKWON:
5652                                chrif_save(sd,0);
5653                                chrif_buildfamelist();
5654                        break;
5655                }
5656        }
5657
5658        return 0;
5659}
5660
5661/*==========================================
5662 * Œ©‚œ–Ú?X
5663 *------------------------------------------*/
5664int pc_equiplookall(struct map_session_data *sd)
5665{
5666        nullpo_retr(0, sd);
5667
5668#if PACKETVER < 4
5669        clif_changelook(&sd->bl,LOOK_WEAPON,sd->status.weapon);
5670        clif_changelook(&sd->bl,LOOK_SHIELD,sd->status.shield);
5671#else
5672        clif_changelook(&sd->bl,LOOK_WEAPON,0);
5673        clif_changelook(&sd->bl,LOOK_SHOES,0);
5674#endif
5675        clif_changelook(&sd->bl,LOOK_HEAD_BOTTOM,sd->status.head_bottom);
5676        clif_changelook(&sd->bl,LOOK_HEAD_TOP,sd->status.head_top);
5677        clif_changelook(&sd->bl,LOOK_HEAD_MID,sd->status.head_mid);
5678
5679        return 0;
5680}
5681
5682/*==========================================
5683 * Œ©‚œ–Ú?X
5684 *------------------------------------------*/
5685int pc_changelook(struct map_session_data *sd,int type,int val)
5686{
5687        nullpo_retr(0, sd);
5688
5689        switch(type){
5690        case LOOK_HAIR: //Use the battle_config limits! [Skotlex]
5691                if (val < battle_config.min_hair_style)
5692                        val = battle_config.min_hair_style;
5693                else if (val > battle_config.max_hair_style)
5694                        val = battle_config.max_hair_style;
5695                if (sd->status.hair != val)
5696                {
5697                        sd->status.hair=val;
5698                        if (sd->status.guild_id) //Update Guild Window. [Skotlex]
5699                                intif_guild_change_memberinfo(sd->status.guild_id,sd->status.account_id,sd->status.char_id,
5700                                GMI_HAIR,&sd->status.hair,sizeof(sd->status.hair));
5701                }
5702                break;
5703        case LOOK_WEAPON:
5704                sd->status.weapon=val;
5705                break;
5706        case LOOK_HEAD_BOTTOM:
5707                sd->status.head_bottom=val;
5708                break;
5709        case LOOK_HEAD_TOP:
5710                sd->status.head_top=val;
5711                break;
5712        case LOOK_HEAD_MID:
5713                sd->status.head_mid=val;
5714                break;
5715        case LOOK_HAIR_COLOR:   //Use the battle_config limits! [Skotlex]
5716                if (val < battle_config.min_hair_color)
5717                        val = battle_config.min_hair_color;
5718                else if (val > battle_config.max_hair_color)
5719                        val = battle_config.max_hair_color;
5720                if (sd->status.hair_color != val)
5721                {
5722                        sd->status.hair_color=val;
5723                        if (sd->status.guild_id) //Update Guild Window. [Skotlex]
5724                                intif_guild_change_memberinfo(sd->status.guild_id,sd->status.account_id,sd->status.char_id,
5725                                GMI_HAIR_COLOR,&sd->status.hair_color,sizeof(sd->status.hair_color));
5726                }
5727                break;
5728        case LOOK_CLOTHES_COLOR:        //Use the battle_config limits! [Skotlex]
5729                if (val < battle_config.min_cloth_color)
5730                        val = battle_config.min_cloth_color;
5731                else if (val > battle_config.max_cloth_color)
5732                        val = battle_config.max_cloth_color;
5733                sd->status.clothes_color=val;
5734                break;
5735        case LOOK_SHIELD:
5736                sd->status.shield=val;
5737                break;
5738        case LOOK_SHOES:
5739                break;
5740        }
5741        clif_changelook(&sd->bl,type,val);
5742        return 0;
5743}
5744
5745/*==========================================
5746 * •t?•i(‘é,ƒyƒR,ƒJ?ƒg)Ý’è
5747 *------------------------------------------*/
5748int pc_setoption(struct map_session_data *sd,int type)
5749{
5750        int p_type, new_look=0;
5751        nullpo_retr(0, sd);
5752        p_type = sd->sc.option;
5753
5754        //Option has to be changed client-side before the class sprite or it won't always work (eg: Wedding sprite) [Skotlex]
5755        sd->sc.option=type;
5756        clif_changeoption(&sd->bl);
5757
5758        if (type&OPTION_RIDING && !(p_type&OPTION_RIDING) && (sd->class_&MAPID_BASEMASK) == MAPID_SWORDMAN)
5759        {       //We are going to mount. [Skotlex]
5760                new_look = -1;
5761                clif_status_load(&sd->bl,SI_RIDING,1);
5762                status_calc_pc(sd,0); //Mounting/Umounting affects walk and attack speeds.
5763        }
5764        else if (!(type&OPTION_RIDING) && p_type&OPTION_RIDING && (sd->class_&MAPID_BASEMASK) == MAPID_SWORDMAN)
5765        {       //We are going to dismount.
5766                new_look = -1;
5767                clif_status_load(&sd->bl,SI_RIDING,0);
5768                status_calc_pc(sd,0); //Mounting/Umounting affects walk and attack speeds.
5769        }
5770        if(type&OPTION_CART && !(p_type&OPTION_CART))
5771        { //Cart On
5772                clif_cartlist(sd);
5773                clif_updatestatus(sd, SP_CARTINFO);
5774                if(pc_checkskill(sd, MC_PUSHCART) < 10)
5775                        status_calc_pc(sd,0); //Apply speed penalty.
5776        } else
5777        if(!(type&OPTION_CART) && p_type&OPTION_CART)
5778        { //Cart Off
5779                clif_clearcart(sd->fd);
5780                if(pc_checkskill(sd, MC_PUSHCART) < 10)
5781                        status_calc_pc(sd,0); //Remove speed penalty.
5782        }
5783
5784        if (type&OPTION_FALCON && !(p_type&OPTION_FALCON)) //Falcon ON
5785                clif_status_load(&sd->bl,SI_FALCON,1);
5786        else if (!(type&OPTION_FALCON) && p_type&OPTION_FALCON) //Falcon OFF
5787                clif_status_load(&sd->bl,SI_FALCON,0);
5788
5789        if (type&OPTION_FLYING && !(p_type&OPTION_FLYING))
5790                new_look = JOB_STAR_GLADIATOR2;
5791        else if (!(type&OPTION_FLYING) && p_type&OPTION_FLYING)
5792                new_look = -1;
5793       
5794        if (type&OPTION_WEDDING && !(p_type&OPTION_WEDDING))
5795                new_look = JOB_WEDDING;
5796        else if (!(type&OPTION_WEDDING) && p_type&OPTION_WEDDING)
5797                new_look = -1;
5798
5799        if (type&OPTION_XMAS && !(p_type&OPTION_XMAS))
5800                new_look = JOB_XMAS;
5801        else if (!(type&OPTION_XMAS) && p_type&OPTION_XMAS)
5802                new_look = -1;
5803
5804        if (type&OPTION_SUMMER && !(p_type&OPTION_SUMMER))
5805                new_look = JOB_SUMMER;
5806        else if (!(type&OPTION_SUMMER) && p_type&OPTION_SUMMER)
5807                new_look = -1;
5808
5809        if (sd->disguise)
5810                return 0; //Disguises break sprite changes
5811
5812        if (new_look < 0) { //Restore normal look.
5813                status_set_viewdata(&sd->bl, sd->status.class_);
5814                new_look = sd->vd.class_;
5815        }
5816        if (new_look) {
5817                //Stop attacking on new view change (to prevent wedding/santa attacks.
5818                pc_stop_attack(sd);
5819                clif_changelook(&sd->bl,LOOK_BASE,new_look);
5820                if (sd->vd.cloth_color)
5821                        clif_changelook(&sd->bl,LOOK_CLOTHES_COLOR,sd->vd.cloth_color);
5822        }
5823        return 0;
5824}
5825
5826/*==========================================
5827 * ƒJ?ƒgÝ’è
5828 *------------------------------------------*/
5829int pc_setcart(struct map_session_data *sd,int type)
5830{
5831        int cart[6] = {0x0000,OPTION_CART1,OPTION_CART2,OPTION_CART3,OPTION_CART4,OPTION_CART5};
5832        int option;
5833
5834        nullpo_retr(0, sd);
5835
5836        if( type < 0 || type > 5 )
5837                return 1;// Never trust the values sent by the client! [Skotlex]
5838
5839        if( pc_checkskill(sd,MC_PUSHCART) <= 0 )
5840                return 1;// Push cart is required
5841
5842        // Update option
5843        option = sd->sc.option;
5844        option &= ~OPTION_CART;// clear cart bits
5845        option |= cart[type]; // set cart
5846        pc_setoption(sd, option);
5847
5848        return 0;
5849}
5850
5851/*==========================================
5852 * ‘éÝ’è
5853 *------------------------------------------*/
5854int pc_setfalcon(TBL_PC* sd, int flag)
5855{
5856        if( flag ){
5857                if( pc_checkskill(sd,HT_FALCON)>0 )     // ƒtƒ@ƒ‹ƒRƒ“ƒ}ƒXƒ^ƒŠ?ƒXƒLƒ‹ŠŽ
5858                        pc_setoption(sd,sd->sc.option|OPTION_FALCON);
5859        } else if( pc_isfalcon(sd) ){
5860                pc_setoption(sd,sd->sc.option&~OPTION_FALCON); // remove falcon
5861        }
5862
5863        return 0;
5864}
5865
5866/*==========================================
5867 * ƒyƒRƒyƒRÝ’è
5868 *------------------------------------------*/
5869int pc_setriding(TBL_PC* sd, int flag)
5870{
5871        if( flag ){
5872                if( pc_checkskill(sd,KN_RIDING) > 0 ) // ƒ‰ƒCƒfƒBƒ“ƒOƒXƒLƒ‹ŠŽ
5873                        pc_setoption(sd, sd->sc.option|OPTION_RIDING);
5874        } else if( pc_isriding(sd) ){
5875                pc_setoption(sd, sd->sc.option&~OPTION_RIDING);
5876        }
5877
5878        return 0;
5879}
5880
5881/*==========================================
5882 * ƒAƒCƒeƒ€ƒhƒƒbƒv‰Â•s‰Â”»’è
5883 *------------------------------------------*/
5884int pc_candrop(struct map_session_data *sd,struct item *item)
5885{
5886        int level = pc_isGM(sd);
5887        if ( !pc_can_give_items(level) ) //check if this GM level can drop items
5888                return 0;
5889        return (itemdb_isdropable(item, level));
5890}
5891
5892/*==========================================
5893 * script—p??‚Ì’l‚ð?‚Þ
5894 *------------------------------------------*/
5895int pc_readreg(struct map_session_data* sd, int reg)
5896{
5897        int i;
5898
5899        nullpo_retr(0, sd);
5900
5901        ARR_FIND( 0, sd->reg_num, i,  sd->reg[i].index == reg );
5902        return ( i < sd->reg_num ) ? sd->reg[i].data : 0;
5903}
5904/*==========================================
5905 * script—p??‚Ì’l‚ðÝ’è
5906 *------------------------------------------*/
5907int pc_setreg(struct map_session_data* sd, int reg, int val)
5908{
5909        int i;
5910
5911        nullpo_retr(0, sd);
5912
5913        ARR_FIND( 0, sd->reg_num, i, sd->reg[i].index == reg );
5914        if( i < sd->reg_num )
5915        {// overwrite existing entry
5916                sd->reg[i].data = val;
5917                return 1;
5918        }
5919
5920        ARR_FIND( 0, sd->reg_num, i, sd->reg[i].data == 0 );
5921        if( i == sd->reg_num )
5922        {// nothing free, increase size
5923                sd->reg_num++;
5924                RECREATE(sd->reg, struct script_reg, sd->reg_num);
5925        }
5926        sd->reg[i].index = reg;
5927        sd->reg[i].data = val;
5928
5929        return 1;
5930}
5931
5932/*==========================================
5933 * script—p•¶Žš—ñ??‚Ì’l‚ð?‚Þ
5934 *------------------------------------------*/
5935char* pc_readregstr(struct map_session_data* sd, int reg)
5936{
5937        int i;
5938
5939        nullpo_retr(0, sd);
5940
5941        ARR_FIND( 0, sd->regstr_num, i,  sd->regstr[i].index == reg );
5942        return ( i < sd->regstr_num ) ? sd->regstr[i].data : NULL;
5943}
5944/*==========================================
5945 * script—p•¶Žš—ñ??‚Ì’l‚ðÝ’è
5946 *------------------------------------------*/
5947int pc_setregstr(struct map_session_data* sd, int reg, const char* str)
5948{
5949        int i;
5950
5951        nullpo_retr(0, sd);
5952
5953        ARR_FIND( 0, sd->regstr_num, i, sd->regstr[i].index == reg );
5954        if( i < sd->regstr_num )
5955        {// found entry, update
5956                if( str == NULL || *str == '\0' )
5957                {// empty string
5958                        if( sd->regstr[i].data != NULL )
5959                                aFree(sd->regstr[i].data);
5960                        sd->regstr[i].data = NULL;
5961                }
5962                else if( sd->regstr[i].data )
5963                {// recreate
5964                        size_t len = strlen(str)+1;
5965                        RECREATE(sd->regstr[i].data, char, len);
5966                        memcpy(sd->regstr[i].data, str, len*sizeof(char));
5967                }
5968                else
5969                {// create
5970                        sd->regstr[i].data = aStrdup(str);
5971                }
5972                return 1;
5973        }
5974
5975        if( str == NULL || *str == '\0' )
5976                return 1;// nothing to add, empty string
5977
5978        ARR_FIND( 0, sd->regstr_num, i, sd->regstr[i].data == NULL );
5979        if( i == sd->regstr_num )
5980        {// nothing free, increase size
5981                sd->regstr_num++;
5982                RECREATE(sd->regstr, struct script_regstr, sd->regstr_num);
5983        }
5984        sd->regstr[i].index = reg;
5985        sd->regstr[i].data = aStrdup(str);
5986
5987        return 1;
5988}
5989
5990int pc_readregistry(struct map_session_data *sd,const char *reg,int type)
5991{
5992        struct global_reg *sd_reg;
5993        int i,max;
5994
5995        nullpo_retr(0, sd);
5996        switch (type) {
5997        case 3: //Char reg
5998                sd_reg = sd->save_reg.global;
5999                max = sd->save_reg.global_num;
6000        break;
6001        case 2: //Account reg
6002                sd_reg = sd->save_reg.account;
6003                max = sd->save_reg.account_num;
6004        break;
6005        case 1: //Account2 reg
6006                sd_reg = sd->save_reg.account2;
6007                max = sd->save_reg.account2_num;
6008        break;
6009        default:
6010                return 0;
6011        }
6012        if (max == -1) {
6013                ShowError("pc_readregistry: Trying to read reg value %s (type %d) before it's been loaded!\n", reg, type);
6014                //This really shouldn't happen, so it's possible the data was lost somewhere, we should request it again.
6015                intif_request_registry(sd,type==3?4:type);
6016                return 0;
6017        }
6018
6019        ARR_FIND( 0, max, i, strcmp(sd_reg[i].str,reg) == 0 );
6020        return ( i < max ) ? atoi(sd_reg[i].value) : 0;
6021}
6022
6023char* pc_readregistry_str(struct map_session_data *sd,char *reg,int type)
6024{
6025        struct global_reg *sd_reg;
6026        int i,max;
6027       
6028        nullpo_retr(0, sd);
6029        switch (type) {
6030        case 3: //Char reg
6031                sd_reg = sd->save_reg.global;
6032                max = sd->save_reg.global_num;
6033        break;
6034        case 2: //Account reg
6035                sd_reg = sd->save_reg.account;
6036                max = sd->save_reg.account_num;
6037        break;
6038        case 1: //Account2 reg
6039                sd_reg = sd->save_reg.account2;
6040                max = sd->save_reg.account2_num;
6041        break;
6042        default:
6043                return NULL;
6044        }
6045        if (max == -1) {
6046                ShowError("pc_readregistry: Trying to read reg value %s (type %d) before it's been loaded!\n", reg, type);
6047                //This really shouldn't happen, so it's possible the data was lost somewhere, we should request it again.
6048                intif_request_registry(sd,type==3?4:type);
6049                return NULL;
6050        }
6051
6052        ARR_FIND( 0, max, i, strcmp(sd_reg[i].str,reg) == 0 );
6053        return ( i < max ) ? sd_reg[i].value : NULL;
6054}
6055
6056int pc_setregistry(struct map_session_data *sd,const char *reg,int val,int type)
6057{
6058        struct global_reg *sd_reg;
6059        int i,*max, regmax;
6060
6061        nullpo_retr(0, sd);
6062
6063        switch( type )
6064        {
6065        case 3: //Char reg
6066                if( !strcmp(reg,"PC_DIE_COUNTER") && sd->die_counter != val )
6067                {
6068                        i = (!sd->die_counter && (sd->class_&MAPID_UPPERMASK) == MAPID_SUPER_NOVICE);
6069                        sd->die_counter = val;
6070                        if( i )
6071                                status_calc_pc(sd,0); // Lost the bonus.
6072                }
6073                sd_reg = sd->save_reg.global;
6074                max = &sd->save_reg.global_num;
6075                regmax = GLOBAL_REG_NUM;
6076        break;
6077        case 2: //Account reg
6078                if( !strcmp(reg,"#CASHPOINTS") && sd->cashPoints != val )
6079                {
6080                        val = cap_value(val, 0, MAX_ZENY);
6081                        sd->cashPoints = val;
6082                }
6083                else if( !strcmp(reg,"#KAFRAPOINTS") && sd->kafraPoints != val )
6084                {
6085                        val = cap_value(val, 0, MAX_ZENY);
6086                        sd->kafraPoints = val;
6087                }
6088                sd_reg = sd->save_reg.account;
6089                max = &sd->save_reg.account_num;
6090                regmax = ACCOUNT_REG_NUM;
6091        break;
6092        case 1: //Account2 reg
6093                sd_reg = sd->save_reg.account2;
6094                max = &sd->save_reg.account2_num;
6095                regmax = ACCOUNT_REG2_NUM;
6096        break;
6097        default:
6098                return 0;
6099        }
6100        if (*max == -1) {
6101                ShowError("pc_setregistry : refusing to set %s (type %d) until vars are received.\n", reg, type);
6102                return 1;
6103        }
6104       
6105        // delete reg
6106        if (val == 0) {
6107                ARR_FIND( 0, *max, i, strcmp(sd_reg[i].str, reg) == 0 );
6108                if( i < *max )
6109                {
6110                        if (i != *max - 1)
6111                                memcpy(&sd_reg[i], &sd_reg[*max - 1], sizeof(struct global_reg));
6112                        memset(&sd_reg[*max - 1], 0, sizeof(struct global_reg));
6113                        (*max)--;
6114                        sd->state.reg_dirty |= 1<<(type-1); //Mark this registry as "need to be saved"
6115                }
6116                return 1;
6117        }
6118        // change value if found
6119        ARR_FIND( 0, *max, i, strcmp(sd_reg[i].str, reg) == 0 );
6120        if( i < *max )
6121        {
6122                safesnprintf(sd_reg[i].value, sizeof(sd_reg[i].value), "%d", val);
6123                sd->state.reg_dirty |= 1<<(type-1);
6124                return 1;
6125        }
6126
6127        // add value if not found
6128        if (i < regmax) {
6129                memset(&sd_reg[i], 0, sizeof(struct global_reg));
6130                safestrncpy(sd_reg[i].str, reg, sizeof(sd_reg[i].str));
6131                safesnprintf(sd_reg[i].value, sizeof(sd_reg[i].value), "%d", val);
6132                (*max)++;
6133                sd->state.reg_dirty |= 1<<(type-1);
6134                return 1;
6135        }
6136
6137        ShowError("pc_setregistry : couldn't set %s, limit of registries reached (%d)\n", reg, regmax);
6138
6139        return 0;
6140}
6141
6142int pc_setregistry_str(struct map_session_data *sd,char *reg,const char *val,int type)
6143{
6144        struct global_reg *sd_reg;
6145        int i,*max, regmax;
6146
6147        nullpo_retr(0, sd);
6148        if (reg[strlen(reg)-1] != '$') {
6149                ShowError("pc_setregistry_str : reg %s must be string (end in '$') to use this!\n", reg);
6150                return 0;
6151        }
6152
6153        switch (type) {
6154        case 3: //Char reg
6155                sd_reg = sd->save_reg.global;
6156                max = &sd->save_reg.global_num;
6157                regmax = GLOBAL_REG_NUM;
6158        break;
6159        case 2: //Account reg
6160                sd_reg = sd->save_reg.account;
6161                max = &sd->save_reg.account_num;
6162                regmax = ACCOUNT_REG_NUM;
6163        break;
6164        case 1: //Account2 reg
6165                sd_reg = sd->save_reg.account2;
6166                max = &sd->save_reg.account2_num;
6167                regmax = ACCOUNT_REG2_NUM;
6168        break;
6169        default:
6170                return 0;
6171        }
6172        if (*max == -1) {
6173                ShowError("pc_setregistry_str : refusing to set %s (type %d) until vars are received.\n", reg, type);
6174                return 0;
6175        }
6176       
6177        // delete reg
6178        if (!val || strcmp(val,"")==0)
6179        {
6180                ARR_FIND( 0, *max, i, strcmp(sd_reg[i].str, reg) == 0 );
6181                if( i < *max )
6182                {
6183                        if (i != *max - 1)
6184                                memcpy(&sd_reg[i], &sd_reg[*max - 1], sizeof(struct global_reg));
6185                        memset(&sd_reg[*max - 1], 0, sizeof(struct global_reg));
6186                        (*max)--;
6187                        sd->state.reg_dirty |= 1<<(type-1); //Mark this registry as "need to be saved"
6188                        if (type!=3) intif_saveregistry(sd,type);
6189                }
6190                return 1;
6191        }
6192
6193        // change value if found
6194        ARR_FIND( 0, *max, i, strcmp(sd_reg[i].str, reg) == 0 );
6195        if( i < *max )
6196        {
6197                safestrncpy(sd_reg[i].value, val, sizeof(sd_reg[i].value));
6198                sd->state.reg_dirty |= 1<<(type-1); //Mark this registry as "need to be saved"
6199                if (type!=3) intif_saveregistry(sd,type);
6200                return 1;
6201        }
6202
6203        // add value if not found
6204        if (i < regmax) {
6205                memset(&sd_reg[i], 0, sizeof(struct global_reg));
6206                safestrncpy(sd_reg[i].str, reg, sizeof(sd_reg[i].str));
6207                safestrncpy(sd_reg[i].value, val, sizeof(sd_reg[i].value));
6208                (*max)++;
6209                sd->state.reg_dirty |= 1<<(type-1); //Mark this registry as "need to be saved"
6210                if (type!=3) intif_saveregistry(sd,type);
6211                return 1;
6212        }
6213
6214        ShowError("pc_setregistry : couldn't set %s, limit of registries reached (%d)\n", reg, regmax);
6215
6216        return 0;
6217}
6218
6219/*==========================================
6220 * ƒCƒxƒ“ƒgƒ^ƒCƒ}??—
6221 *------------------------------------------*/
6222static int pc_eventtimer(int tid, unsigned int tick, int id, intptr data)
6223{
6224        struct map_session_data *sd=map_id2sd(id);
6225        char *p = (char *)data;
6226        int i;
6227        if(sd==NULL)
6228                return 0;
6229
6230        ARR_FIND( 0, MAX_EVENTTIMER, i, sd->eventtimer[i] == tid );
6231        if( i < MAX_EVENTTIMER )
6232        {
6233                sd->eventtimer[i] = -1;
6234                sd->eventcount--;
6235                npc_event(sd,p,0);
6236        }
6237        else
6238                ShowError("pc_eventtimer: no such event timer\n");
6239
6240        if (p) aFree(p);
6241        return 0;
6242}
6243
6244/*==========================================
6245 * ƒCƒxƒ“ƒgƒ^ƒCƒ}?’ljÁ
6246 *------------------------------------------*/
6247int pc_addeventtimer(struct map_session_data *sd,int tick,const char *name)
6248{
6249        int i;
6250        nullpo_retr(0, sd);
6251
6252        ARR_FIND( 0, MAX_EVENTTIMER, i, sd->eventtimer[i] == -1 );
6253        if( i == MAX_EVENTTIMER )
6254                return 0;
6255
6256        sd->eventtimer[i] = add_timer(gettick()+tick, pc_eventtimer, sd->bl.id, (int)aStrdup(name));
6257        sd->eventcount++;
6258
6259        return 1;
6260}
6261
6262/*==========================================
6263 * ƒCƒxƒ“ƒgƒ^ƒCƒ}?íœ
6264 *------------------------------------------*/
6265int pc_deleventtimer(struct map_session_data *sd,const char *name)
6266{
6267        char* p = NULL;
6268        int i;
6269
6270        nullpo_retr(0, sd);
6271
6272        if (sd->eventcount <= 0)
6273                return 0;
6274
6275        // find the named event timer
6276        ARR_FIND( 0, MAX_EVENTTIMER, i,
6277                sd->eventtimer[i] != -1 &&
6278                (p = (char *)(get_timer(sd->eventtimer[i])->data)) != NULL &&
6279                strcmp(p, name) == 0
6280        );
6281        if( i == MAX_EVENTTIMER )
6282                return 0; // not found
6283
6284        delete_timer(sd->eventtimer[i],pc_eventtimer);
6285        sd->eventtimer[i]=-1;
6286        sd->eventcount--;
6287        aFree(p);
6288
6289        return 1;
6290}
6291
6292/*==========================================
6293 * ƒCƒxƒ“ƒgƒ^ƒCƒ}?ƒJƒEƒ“ƒg’l’ljÁ
6294 *------------------------------------------*/
6295int pc_addeventtimercount(struct map_session_data *sd,const char *name,int tick)
6296{
6297        int i;
6298
6299        nullpo_retr(0, sd);
6300
6301        for(i=0;i<MAX_EVENTTIMER;i++)
6302                if( sd->eventtimer[i]!=-1 && strcmp(
6303                        (char *)(get_timer(sd->eventtimer[i])->data), name)==0 ){
6304                                addtick_timer(sd->eventtimer[i],tick);
6305                                break;
6306                }
6307
6308        return 0;
6309}
6310
6311/*==========================================
6312 * ƒCƒxƒ“ƒgƒ^ƒCƒ}?‘Síœ
6313 *------------------------------------------*/
6314int pc_cleareventtimer(struct map_session_data *sd)
6315{
6316        int i;
6317
6318        nullpo_retr(0, sd);
6319
6320        if (sd->eventcount <= 0)
6321                return 0;
6322
6323        for(i=0;i<MAX_EVENTTIMER;i++)
6324                if( sd->eventtimer[i]!=-1 ){
6325                        char *p = (char *)(get_timer(sd->eventtimer[i])->data);
6326                        delete_timer(sd->eventtimer[i],pc_eventtimer);
6327                        sd->eventtimer[i]=-1;
6328                        sd->eventcount--;
6329                        if (p) aFree(p);
6330                }
6331        return 0;
6332}
6333
6334//
6335// ? ”õ•š
6336//
6337/*==========================================
6338 * ƒAƒCƒeƒ€‚ð?”õ‚·‚é
6339 *------------------------------------------*/
6340int pc_equipitem(struct map_session_data *sd,int n,int req_pos)
6341{
6342        int i,pos,flag=0;
6343        struct item_data *id;
6344
6345        nullpo_retr(0, sd);
6346
6347        if( n < 0 || n >= MAX_INVENTORY ) {
6348                clif_equipitemack(sd,0,0,0);
6349                return 0;
6350        }
6351
6352        id = sd->inventory_data[n];
6353        pos = pc_equippoint(sd,n); //With a few exceptions, item should go in all specified slots.
6354
6355        if(battle_config.battle_log)
6356                ShowInfo("equip %d(%d) %x:%x\n",sd->status.inventory[n].nameid,n,id->equip,req_pos);
6357        if(!pc_isequip(sd,n) || !(pos&req_pos) || sd->status.inventory[n].attribute==1 ) { // [Valaris]
6358                clif_equipitemack(sd,n,0,0);    // fail
6359                return 0;
6360        }
6361
6362        if(sd->sc.data[SC_BERSERK] || sd->sc.data[SC_BLADESTOP])
6363        {
6364                clif_equipitemack(sd,n,0,0);    // fail
6365                return 0;
6366        }
6367
6368        if(pos == EQP_ACC) { //Accesories should only go in one of the two,
6369                pos = req_pos&EQP_ACC;
6370                if (pos == EQP_ACC) //User specified both slots..
6371                        pos = sd->equip_index[EQI_ACC_R] >= 0 ? EQP_ACC_L : EQP_ACC_R;
6372        }
6373
6374        if(pos == EQP_ARMS && id->equip == EQP_HAND_R)
6375        {       //Dual wield capable weapon.
6376                pos = (req_pos&EQP_ARMS);
6377                if (pos == EQP_ARMS) //User specified both slots, pick one for them.
6378                        pos = sd->equip_index[EQI_HAND_R] >= 0 ? EQP_HAND_L : EQP_HAND_R;
6379        }
6380
6381        if (pos&EQP_HAND_R && battle_config.use_weapon_skill_range&BL_PC)
6382        {       //Update skill-block range database when weapon range changes. [Skotlex]
6383                i = sd->equip_index[EQI_HAND_R];
6384                if (i < 0 || !sd->inventory_data[i]) //No data, or no weapon equipped
6385                        flag = 1;
6386                else
6387                        flag = id->range != sd->inventory_data[i]->range;
6388        }
6389
6390        for(i=0;i<EQI_MAX;i++) {
6391                if(pos & equip_pos[i]) {
6392                        if(sd->equip_index[i] >= 0) //Slot taken, remove item from there.
6393                                pc_unequipitem(sd,sd->equip_index[i],2);
6394
6395                        sd->equip_index[i] = n;
6396                }
6397        }
6398
6399        if(pos==EQP_AMMO){
6400                clif_arrowequip(sd,n);
6401                clif_arrow_fail(sd,3);
6402        }
6403        else
6404                clif_equipitemack(sd,n,pos,1);
6405
6406        sd->status.inventory[n].equip=pos;
6407
6408        if(pos & EQP_HAND_R) {
6409                if(id)
6410                        sd->weapontype1 = id->look;
6411                else
6412                        sd->weapontype1 = 0;
6413                pc_calcweapontype(sd);
6414                clif_changelook(&sd->bl,LOOK_WEAPON,sd->status.weapon);
6415        }
6416        if(pos & EQP_HAND_L) {
6417                if(id) {
6418                        if(id->type == IT_WEAPON) {
6419                                sd->status.shield = 0;
6420                                if(sd->status.inventory[n].equip == EQP_HAND_L)
6421                                        sd->weapontype2 = id->look;
6422                                else
6423                                        sd->weapontype2 = 0;
6424                        }
6425                        else
6426                        if(id->type == IT_ARMOR) {
6427                                sd->status.shield = id->look;
6428                                sd->weapontype2 = 0;
6429                        }
6430                }
6431                else
6432                        sd->status.shield = sd->weapontype2 = 0;
6433                pc_calcweapontype(sd);
6434                clif_changelook(&sd->bl,LOOK_SHIELD,sd->status.shield);
6435        }
6436        //Added check to prevent sending the same look on multiple slots ->
6437        //causes client to redraw item on top of itself. (suggested by Lupus)
6438        if(pos & EQP_HEAD_LOW) {
6439                if(id && !(pos&(EQP_HEAD_TOP|EQP_HEAD_MID)))
6440                        sd->status.head_bottom = id->look;
6441                else
6442                        sd->status.head_bottom = 0;
6443                clif_changelook(&sd->bl,LOOK_HEAD_BOTTOM,sd->status.head_bottom);
6444        }
6445        if(pos & EQP_HEAD_TOP) {
6446                if(id)
6447                        sd->status.head_top = id->look;
6448                else
6449                        sd->status.head_top = 0;
6450                clif_changelook(&sd->bl,LOOK_HEAD_TOP,sd->status.head_top);
6451        }
6452        if(pos & EQP_HEAD_MID) {
6453                if(id && !(pos&EQP_HEAD_TOP))
6454                        sd->status.head_mid = id->look;
6455                else
6456                        sd->status.head_mid = 0;
6457                clif_changelook(&sd->bl,LOOK_HEAD_MID,sd->status.head_mid);
6458        }
6459        if(pos & EQP_SHOES)
6460                clif_changelook(&sd->bl,LOOK_SHOES,0);
6461
6462        pc_checkallowskill(sd); //Check if status changes should be halted.
6463
6464
6465        status_calc_pc(sd,0);
6466        if (flag) //Update skill data
6467                clif_skillinfoblock(sd);
6468
6469        //OnEquip script [Skotlex]
6470        if (id) {
6471                int i;
6472                struct item_data *data;
6473                if (id->equip_script)
6474                        run_script(id->equip_script,0,sd->bl.id,fake_nd->bl.id);
6475                if(itemdb_isspecial(sd->status.inventory[n].card[0]))
6476                        ; //No cards
6477                else
6478                for(i=0;i<id->slot; i++)
6479                {
6480                        if (!sd->status.inventory[n].card[i])
6481                                continue;
6482                        data = itemdb_exists(sd->status.inventory[n].card[i]);
6483                        if (data && data->equip_script)
6484                                run_script(data->equip_script,0,sd->bl.id,fake_nd->bl.id);
6485                }
6486        }
6487        return 0;
6488}
6489
6490/*==========================================
6491 * ? ”õ‚µ‚œ•š‚ðŠO‚·
6492 * type:
6493 * 0 - only unequip
6494 * 1 - calculate status after unequipping
6495 * 2 - force unequip
6496 *------------------------------------------*/
6497int pc_unequipitem(struct map_session_data *sd,int n,int flag)
6498{
6499        int i;
6500        nullpo_retr(0, sd);
6501
6502        if( n < 0 || n >= MAX_INVENTORY ) {
6503                clif_unequipitemack(sd,0,0,0);
6504                return 0;
6505        }
6506
6507        // if player is berserk then cannot unequip
6508        if(!(flag&2) && sd->sc.count && (sd->sc.data[SC_BLADESTOP] || sd->sc.data[SC_BERSERK])){
6509                clif_unequipitemack(sd,n,0,0);
6510                return 0;
6511        }
6512
6513        if(battle_config.battle_log)
6514                ShowInfo("unequip %d %x:%x\n",n,pc_equippoint(sd,n),sd->status.inventory[n].equip);
6515
6516        if(!sd->status.inventory[n].equip){ //Nothing to unequip
6517                clif_unequipitemack(sd,n,0,0);
6518                return 0;
6519        }
6520        for(i=0;i<EQI_MAX;i++) {
6521                if(sd->status.inventory[n].equip & equip_pos[i])
6522                        sd->equip_index[i] = -1;
6523        }
6524
6525        if(sd->status.inventory[n].equip & EQP_HAND_R) {
6526                sd->weapontype1 = 0;
6527                sd->status.weapon = sd->weapontype2;
6528                pc_calcweapontype(sd);
6529                clif_changelook(&sd->bl,LOOK_WEAPON,sd->status.weapon);
6530                if(sd->sc.data[SC_DANCING]) //When unequipping, stop dancing. [Skotlex]
6531                        skill_stop_dancing(&sd->bl);
6532        }
6533        if(sd->status.inventory[n].equip & EQP_HAND_L) {
6534                sd->status.shield = sd->weapontype2 = 0;
6535                pc_calcweapontype(sd);
6536                clif_changelook(&sd->bl,LOOK_SHIELD,sd->status.shield);
6537        }
6538        if(sd->status.inventory[n].equip & EQP_HEAD_LOW) {
6539                sd->status.head_bottom = 0;
6540                clif_changelook(&sd->bl,LOOK_HEAD_BOTTOM,sd->status.head_bottom);
6541        }
6542        if(sd->status.inventory[n].equip & EQP_HEAD_TOP) {
6543                sd->status.head_top = 0;
6544                clif_changelook(&sd->bl,LOOK_HEAD_TOP,sd->status.head_top);
6545        }
6546        if(sd->status.inventory[n].equip & EQP_HEAD_MID) {
6547                sd->status.head_mid = 0;
6548                clif_changelook(&sd->bl,LOOK_HEAD_MID,sd->status.head_mid);
6549        }
6550        if(sd->status.inventory[n].equip & EQP_SHOES)
6551                clif_changelook(&sd->bl,LOOK_SHOES,0);
6552
6553        clif_unequipitemack(sd,n,sd->status.inventory[n].equip,1);
6554
6555        if((sd->status.inventory[n].equip & EQP_ARMS) && 
6556                sd->weapontype1 == 0 && sd->weapontype2 == 0 && (!sd->sc.data[SC_SEVENWIND] || sd->sc.data[SC_ASPERSIO])) //Check for seven wind (but not level seven!)
6557                skill_enchant_elemental_end(&sd->bl,-1);
6558
6559        if(sd->status.inventory[n].equip & EQP_ARMOR) {
6560                // On Armor Change...
6561                if( sd->sc.data[SC_BENEDICTIO] )
6562                        status_change_end(&sd->bl, SC_BENEDICTIO, -1);
6563                if( sd->sc.data[SC_ARMOR_RESIST] )
6564                        status_change_end(&sd->bl, SC_ARMOR_RESIST, -1);
6565        }
6566
6567        sd->status.inventory[n].equip=0;
6568
6569        if(flag&1) {
6570                pc_checkallowskill(sd);
6571                status_calc_pc(sd,0);
6572        }
6573
6574        if(sd->sc.data[SC_SIGNUMCRUCIS] && !battle_check_undead(sd->battle_status.race,sd->battle_status.def_ele))
6575                status_change_end(&sd->bl,SC_SIGNUMCRUCIS,-1);
6576
6577        //OnUnEquip script [Skotlex]
6578        if (sd->inventory_data[n]) {
6579                struct item_data *data;
6580                if (sd->inventory_data[n]->unequip_script)
6581                        run_script(sd->inventory_data[n]->unequip_script,0,sd->bl.id,fake_nd->bl.id);
6582                if(itemdb_isspecial(sd->status.inventory[n].card[0]))
6583                        ; //No cards
6584                else
6585                for(i=0;i<sd->inventory_data[n]->slot; i++)
6586                {
6587                        if (!sd->status.inventory[n].card[i])
6588                                continue;
6589                        data = itemdb_exists(sd->status.inventory[n].card[i]);
6590                        if (data && data->unequip_script)
6591                                run_script(data->unequip_script,0,sd->bl.id,fake_nd->bl.id);
6592                }
6593        }
6594
6595        return 0;
6596}
6597
6598/*==========================================
6599 * ƒAƒCƒeƒ€‚Ìindex”Ô?‚ð‹l‚ß‚œ‚è
6600 * ? ”õ•i‚Ì?”õ‰Â”\ƒ`ƒFƒbƒN‚ðs‚È‚€
6601 *------------------------------------------*/
6602int pc_checkitem(struct map_session_data *sd)
6603{
6604        int i,j,k,id,calc_flag = 0;
6605        struct item_data *it=NULL;
6606
6607        nullpo_retr(0, sd);
6608
6609        if (sd->vender_id) //Avoid reorganizing items when we are vending, as that leads to exploits (pointed out by End of Exam)
6610                return 0;
6611       
6612        // ŠŽ•i‹ó‚«‹l‚ß
6613        for(i=j=0;i<MAX_INVENTORY;i++){
6614                if( (id=sd->status.inventory[i].nameid)==0)
6615                        continue;
6616                if( battle_config.item_check && !itemdb_available(id) ){
6617                        ShowWarning("illegal item id %d in %d[%s] inventory.\n",id,sd->bl.id,sd->status.name);
6618                        pc_delitem(sd,i,sd->status.inventory[i].amount,3);
6619                        continue;
6620                }
6621                if(i>j){
6622                        memcpy(&sd->status.inventory[j],&sd->status.inventory[i],sizeof(struct item));
6623                        sd->inventory_data[j] = sd->inventory_data[i];
6624                }
6625                j++;
6626        }
6627        if(j < MAX_INVENTORY)
6628                memset(&sd->status.inventory[j],0,sizeof(struct item)*(MAX_INVENTORY-j));
6629        for(k=j;k<MAX_INVENTORY;k++)
6630                sd->inventory_data[k] = NULL;
6631
6632        // ƒJ?ƒg?‹ó‚«‹l‚ß
6633        for(i=j=0;i<MAX_CART;i++){
6634                if( (id=sd->status.cart[i].nameid)==0 )
6635                        continue;
6636                if( battle_config.item_check &&  !itemdb_available(id) ){
6637                        ShowWarning("illegal item id %d in %d[%s] cart.\n",id,sd->bl.id,sd->status.name);
6638                        pc_cart_delitem(sd,i,sd->status.cart[i].amount,1);
6639                        continue;
6640                }
6641                if(i>j){
6642                        memcpy(&sd->status.cart[j],&sd->status.cart[i],sizeof(struct item));
6643                }
6644                j++;
6645        }
6646        if(j < MAX_CART)
6647                memset(&sd->status.cart[j],0,sizeof(struct item)*(MAX_CART-j));
6648
6649        // ? ”õˆÊ’uƒ`ƒFƒbƒN
6650
6651        for(i=0;i<MAX_INVENTORY;i++){
6652
6653                it=sd->inventory_data[i];
6654
6655                if(sd->status.inventory[i].nameid==0)
6656                        continue;
6657
6658                if(!sd->status.inventory[i].equip)
6659                        continue;
6660
6661                if(sd->status.inventory[i].equip&~pc_equippoint(sd,i)) {
6662                        sd->status.inventory[i].equip=0;
6663                        calc_flag = 1;
6664                        continue;
6665                }
6666                if(it) {
6667                        //check for forbiden items.
6668                        int flag =
6669                                        (map[sd->bl.m].flag.restricted?map[sd->bl.m].zone:0)
6670                                        | (map[sd->bl.m].flag.pvp?1:0)
6671                                        | (map_flag_gvg(sd->bl.m)?2:0);
6672                        if (flag && (it->flag.no_equip&flag || !pc_isAllowedCardOn(sd,it->slot,i,flag)))
6673                        {
6674                                sd->status.inventory[i].equip=0;
6675                                calc_flag = 1;
6676                        }
6677                }
6678        }
6679
6680        pc_setequipindex(sd);
6681        if(calc_flag && sd->state.active)
6682        {
6683                status_calc_pc(sd,0);
6684                pc_equiplookall(sd);
6685        }
6686        return 0;
6687}
6688
6689/*==========================================
6690 * PVP‡ˆÊŒvŽZ—p(foreachinarea)
6691 *------------------------------------------*/
6692int pc_calc_pvprank_sub(struct block_list *bl,va_list ap)
6693{
6694        struct map_session_data *sd1,*sd2=NULL;
6695
6696        sd1=(struct map_session_data *)bl;
6697        sd2=va_arg(ap,struct map_session_data *);
6698
6699        if( sd1->pvp_point > sd2->pvp_point )
6700                sd2->pvp_rank++;
6701        return 0;
6702}
6703/*==========================================
6704 * PVP‡ˆÊŒvŽZ
6705 *------------------------------------------*/
6706int pc_calc_pvprank(struct map_session_data *sd)
6707{
6708        int old;
6709        struct map_data *m;
6710        m=&map[sd->bl.m];
6711        old=sd->pvp_rank;
6712        sd->pvp_rank=1;
6713        map_foreachinmap(pc_calc_pvprank_sub,sd->bl.m,BL_PC,sd);
6714        if(old!=sd->pvp_rank || sd->pvp_lastusers!=m->users)
6715                clif_pvpset(sd,sd->pvp_rank,sd->pvp_lastusers=m->users,0);
6716        return sd->pvp_rank;
6717}
6718/*==========================================
6719 * PVP‡ˆÊŒvŽZ(timer)
6720 *------------------------------------------*/
6721int pc_calc_pvprank_timer(int tid, unsigned int tick, int id, intptr data)
6722{
6723        struct map_session_data *sd=NULL;
6724
6725        sd=map_id2sd(id);
6726        if(sd==NULL)
6727                return 0;
6728        sd->pvp_timer = -1;
6729        if( pc_calc_pvprank(sd) > 0 )
6730                sd->pvp_timer = add_timer(gettick()+PVP_CALCRANK_INTERVAL,pc_calc_pvprank_timer,id,data);
6731        return 0;
6732}
6733
6734/*==========================================
6735 * sd‚ÍŒ‹¥‚µ‚Ä‚¢‚é‚©(?¥‚̏ꍇ‚Í‘Š•û‚Ìchar_id‚ð•Ô‚·)
6736 *------------------------------------------*/
6737int pc_ismarried(struct map_session_data *sd)
6738{
6739        if(sd == NULL)
6740                return -1;
6741        if(sd->status.partner_id > 0)
6742                return sd->status.partner_id;
6743        else
6744                return 0;
6745}
6746/*==========================================
6747 * sd‚ªdstsd‚ÆŒ‹¥(dstsdšsd‚ÌŒ‹¥?—‚à“¯Žbɍs‚€)
6748 *------------------------------------------*/
6749int pc_marriage(struct map_session_data *sd,struct map_session_data *dstsd)
6750{
6751        if(sd == NULL || dstsd == NULL ||
6752                sd->status.partner_id > 0 || dstsd->status.partner_id > 0 ||
6753                sd->class_&JOBL_BABY)
6754                return -1;
6755        sd->status.partner_id = dstsd->status.char_id;
6756        dstsd->status.partner_id = sd->status.char_id;
6757        return 0;
6758}
6759
6760/*==========================================
6761 * Divorce sd from its partner
6762 *------------------------------------------*/
6763int pc_divorce(struct map_session_data *sd)
6764{
6765        struct map_session_data *p_sd;
6766        int i;
6767
6768        if( sd == NULL || !pc_ismarried(sd) )
6769                return -1;
6770
6771        if( !sd->status.partner_id )
6772                return -1; // Char is not married
6773
6774        if( (p_sd = map_charid2sd(sd->status.partner_id)) == NULL )
6775        { // Lets char server do the divorce
6776#ifndef TXT_ONLY
6777                if( chrif_divorce(sd->status.char_id, sd->status.partner_id) )
6778                        return -1; // No char server connected
6779
6780                return 0;
6781#else
6782                ShowError("pc_divorce: p_sd nullpo\n");
6783                return -1;
6784#endif
6785        }
6786
6787        // Both players online, lets do the divorce manually
6788        sd->status.partner_id = 0;
6789        p_sd->status.partner_id = 0;
6790        for( i = 0; i < MAX_INVENTORY; i++ )
6791        {
6792                if( sd->status.inventory[i].nameid == WEDDING_RING_M || sd->status.inventory[i].nameid == WEDDING_RING_F )
6793                        pc_delitem(sd, i, 1, 0);
6794                if( p_sd->status.inventory[i].nameid == WEDDING_RING_M || p_sd->status.inventory[i].nameid == WEDDING_RING_F )
6795                        pc_delitem(p_sd, i, 1, 0);
6796        }
6797
6798        clif_divorced(sd, p_sd->status.name);
6799        clif_divorced(p_sd, sd->status.name);
6800
6801        return 0;
6802}
6803
6804/*==========================================
6805 * sd‚Ì‘Š•û‚Ìmap_session_data‚ð•Ô‚·
6806 *------------------------------------------*/
6807struct map_session_data *pc_get_partner(struct map_session_data *sd)
6808{
6809        if (sd && pc_ismarried(sd))
6810                // charid2sd returns NULL if not found
6811                return map_charid2sd(sd->status.partner_id);
6812
6813        return NULL;
6814}
6815
6816struct map_session_data *pc_get_father (struct map_session_data *sd)
6817{
6818        if (sd && sd->class_&JOBL_BABY && sd->status.father > 0)
6819                // charid2sd returns NULL if not found
6820                return map_charid2sd(sd->status.father);
6821
6822        return NULL;
6823}
6824
6825struct map_session_data *pc_get_mother (struct map_session_data *sd)
6826{
6827        if (sd && sd->class_&JOBL_BABY && sd->status.mother > 0)
6828                // charid2sd returns NULL if not found
6829                return map_charid2sd(sd->status.mother);
6830
6831        return NULL;
6832}
6833
6834struct map_session_data *pc_get_child (struct map_session_data *sd)
6835{
6836        if (sd && pc_ismarried(sd) && sd->status.child > 0)
6837                // charid2sd returns NULL if not found
6838                return map_charid2sd(sd->status.child);
6839
6840        return NULL;
6841}
6842
6843void pc_bleeding (struct map_session_data *sd, unsigned int diff_tick)
6844{
6845        int hp = 0, sp = 0;
6846
6847        if (sd->hp_loss.value) {
6848                sd->hp_loss.tick += diff_tick;
6849                while (sd->hp_loss.tick >= sd->hp_loss.rate) {
6850                        hp += sd->hp_loss.value;
6851                        sd->hp_loss.tick -= sd->hp_loss.rate;
6852                }
6853                if(hp >= sd->battle_status.hp)
6854                        hp = sd->battle_status.hp-1; //Script drains cannot kill you.
6855        }
6856       
6857        if (sd->sp_loss.value) {
6858                sd->sp_loss.tick += diff_tick;
6859                while (sd->sp_loss.tick >= sd->sp_loss.rate) {
6860                        sp += sd->sp_loss.value;
6861                        sd->sp_loss.tick -= sd->sp_loss.rate;
6862                }
6863        }
6864
6865        if (hp > 0 || sp > 0)
6866                status_zap(&sd->bl, hp, sp);
6867
6868        return;
6869}
6870
6871//Character regen. Flag is used to know which types of regen can take place.
6872//&1: HP regen
6873//&2: SP regen
6874void pc_regen (struct map_session_data *sd, unsigned int diff_tick)
6875{
6876        int hp = 0, sp = 0;
6877
6878        if (sd->hp_regen.value) {
6879                sd->hp_regen.tick += diff_tick;
6880                while (sd->hp_regen.tick >= sd->hp_regen.rate) {
6881                        hp += sd->hp_regen.value;
6882                        sd->hp_regen.tick -= sd->hp_regen.rate;
6883                }
6884        }
6885       
6886        if (sd->sp_regen.value) {
6887                sd->sp_regen.tick += diff_tick;
6888                while (sd->sp_regen.tick >= sd->sp_regen.rate) {
6889                        sp += sd->sp_regen.value;
6890                        sd->sp_regen.tick -= sd->sp_regen.rate;
6891                }
6892        }
6893
6894        if (hp > 0 || sp > 0)
6895                status_heal(&sd->bl, hp, sp, 0);
6896
6897        return;
6898}
6899
6900/*==========================================
6901 * ƒZ?ƒuƒ|ƒCƒ“ƒg‚̕ۑ¶
6902 *------------------------------------------*/
6903int pc_setsavepoint(struct map_session_data *sd, short mapindex,int x,int y)
6904{
6905        nullpo_retr(0, sd);
6906
6907        sd->status.save_point.map = mapindex;
6908        sd->status.save_point.x = x;
6909        sd->status.save_point.y = y;
6910
6911        return 0;
6912}
6913
6914/*==========================================
6915 * Ž©“®ƒZ?ƒu (timer??)
6916 *------------------------------------------*/
6917int pc_autosave(int tid, unsigned int tick, int id, intptr data)
6918{
6919        int interval;
6920        struct s_mapiterator* iter;
6921        struct map_session_data* sd;
6922        static int last_save_id = 0, save_flag = 0;
6923
6924        if(save_flag == 2) //Someone was saved on last call, normal cycle
6925                save_flag = 0;
6926        else
6927                save_flag = 1; //Noone was saved, so save first found char.
6928
6929        iter = mapit_getallusers();
6930        for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
6931        {
6932                if(sd->bl.id == last_save_id && save_flag != 1) {
6933                        save_flag = 1;
6934                        continue;
6935                }
6936
6937                if(save_flag != 1) //Not our turn to save yet.
6938                        continue;
6939
6940                //Save char.
6941                last_save_id = sd->bl.id;
6942                save_flag = 2;
6943
6944                chrif_save(sd,0);
6945        }
6946        mapit_free(iter);
6947
6948        interval = autosave_interval/(map_usercount()+1);
6949        if(interval < minsave_interval)
6950                interval = minsave_interval;
6951        add_timer(gettick()+interval,pc_autosave,0,0);
6952
6953        return 0;
6954}
6955
6956int pc_read_gm_account(int fd)
6957{
6958        //FIXME: this implementation is a total failure (direct reading from RFIFO) [ultramage]
6959        int i = 0;
6960        if (gm_account != NULL)
6961                aFree(gm_account);
6962        GM_num = 0;
6963        gm_account = (struct gm_account *) aMallocA(((RFIFOW(fd,2) - 4) / 5)*sizeof(struct gm_account));
6964        for (i = 4; i < RFIFOW(fd,2); i += 5) {
6965                gm_account[GM_num].account_id = RFIFOL(fd,i);
6966                gm_account[GM_num].level = (int)RFIFOB(fd,i+4);
6967                GM_num++;
6968        }
6969        return GM_num;
6970}
6971static int pc_daynight_timer_sub(struct map_session_data *sd,va_list ap)
6972{
6973        if (sd->state.night != night_flag && map[sd->bl.m].flag.nightenabled)
6974        {       //Night/day state does not match.
6975                clif_status_load(&sd->bl, SI_NIGHT, night_flag); //New night effect by dynamix [Skotlex]
6976                sd->state.night = night_flag;
6977                return 1;
6978        }
6979        return 0;
6980}
6981/*================================================
6982 * timer to do the day [Yor]
6983 * data: 0 = called by timer, 1 = gmcommand/script
6984 *------------------------------------------------*/
6985int map_day_timer(int tid, unsigned int tick, int id, intptr data)
6986{
6987        char tmp_soutput[1024];
6988
6989        if (data == 0 && battle_config.day_duration <= 0)       // if we want a day
6990                return 0;
6991       
6992        if (!night_flag)
6993                return 0; //Already day.
6994       
6995        night_flag = 0; // 0=day, 1=night [Yor]
6996        map_foreachpc(pc_daynight_timer_sub);
6997        strcpy(tmp_soutput, (data == 0) ? msg_txt(502) : msg_txt(60)); // The day has arrived!
6998        intif_GMmessage(tmp_soutput, strlen(tmp_soutput) + 1, 0);
6999        return 0;
7000}
7001
7002/*================================================
7003 * timer to do the night [Yor]
7004 * data: 0 = called by timer, 1 = gmcommand/script
7005 *------------------------------------------------*/
7006int map_night_timer(int tid, unsigned int tick, int id, intptr data)
7007{
7008        char tmp_soutput[1024];
7009
7010        if (data == 0 && battle_config.night_duration <= 0)     // if we want a night
7011                return 0;
7012       
7013        if (night_flag)
7014                return 0; //Already nigth.
7015
7016        night_flag = 1; // 0=day, 1=night [Yor]
7017        map_foreachpc(pc_daynight_timer_sub);
7018        strcpy(tmp_soutput, (data == 0) ? msg_txt(503) : msg_txt(59)); // The night has fallen...
7019        intif_GMmessage(tmp_soutput, strlen(tmp_soutput) + 1, 0);
7020        return 0;
7021}
7022
7023void pc_setstand(struct map_session_data *sd){
7024        nullpo_retv(sd);
7025
7026        if(sd->sc.data[SC_TENSIONRELAX])
7027                status_change_end(&sd->bl,SC_TENSIONRELAX,-1);
7028
7029        //Reset sitting tick.
7030        sd->ssregen.tick.hp = sd->ssregen.tick.sp = 0;
7031        sd->state.dead_sit = sd->vd.dead_sit = 0;
7032}
7033
7034/*==========================================
7035 * Duel organizing functions [LuzZza]
7036 *------------------------------------------*/
7037void duel_savetime(struct map_session_data* sd)
7038{
7039        time_t timer;
7040        struct tm *t;
7041       
7042        time(&timer);
7043        t = localtime(&timer);
7044       
7045        pc_setglobalreg(sd, "PC_LAST_DUEL_TIME", t->tm_mday*24*60 + t->tm_hour*60 + t->tm_min); 
7046        return;
7047}
7048
7049int duel_checktime(struct map_session_data* sd)
7050{
7051        int diff;
7052        time_t timer;
7053        struct tm *t;
7054       
7055        time(&timer);
7056    t = localtime(&timer);
7057       
7058        diff = t->tm_mday*24*60 + t->tm_hour*60 + t->tm_min - pc_readglobalreg(sd, "PC_LAST_DUEL_TIME");
7059       
7060        return !(diff >= 0 && diff < battle_config.duel_time_interval);
7061}
7062static int duel_showinfo_sub(struct map_session_data* sd, va_list va)
7063{
7064        struct map_session_data *ssd = va_arg(va, struct map_session_data*);
7065        int *p = va_arg(va, int*);
7066        char output[256];
7067
7068        if (sd->duel_group != ssd->duel_group) return 0;
7069       
7070        sprintf(output, "      %d. %s", ++(*p), sd->status.name);
7071        clif_disp_onlyself(ssd, output, strlen(output));
7072        return 1;
7073}
7074
7075int duel_showinfo(const unsigned int did, struct map_session_data* sd)
7076{
7077        int p=0;
7078        char output[256];
7079
7080        if(duel_list[did].max_players_limit > 0)
7081                sprintf(output, msg_txt(370), //" -- Duels: %d/%d, Members: %d/%d, Max players: %d --"
7082                        did, duel_count,
7083                        duel_list[did].members_count,
7084                        duel_list[did].members_count + duel_list[did].invites_count,
7085                        duel_list[did].max_players_limit);
7086        else
7087                sprintf(output, msg_txt(371), //" -- Duels: %d/%d, Members: %d/%d --"
7088                        did, duel_count,
7089                        duel_list[did].members_count,
7090                        duel_list[did].members_count + duel_list[did].invites_count);
7091
7092        clif_disp_onlyself(sd, output, strlen(output));
7093        map_foreachpc(duel_showinfo_sub, sd, &p);
7094        return 0;
7095}
7096
7097int duel_create(struct map_session_data* sd, const unsigned int maxpl)
7098{
7099        int i=1;
7100        char output[256];
7101       
7102        while(duel_list[i].members_count > 0 && i < MAX_DUEL) i++;
7103        if(i == MAX_DUEL) return 0;
7104       
7105        duel_count++;
7106        sd->duel_group = i;
7107        duel_list[i].members_count++;
7108        duel_list[i].invites_count = 0;
7109        duel_list[i].max_players_limit = maxpl;
7110       
7111        strcpy(output, msg_txt(372)); // " -- Duel has been created (@invite/@leave) --"
7112        clif_disp_onlyself(sd, output, strlen(output));
7113       
7114        clif_set0199(sd, 1);
7115        //clif_misceffect2(&sd->bl, 159);
7116        return i;
7117}
7118
7119int duel_invite(const unsigned int did, struct map_session_data* sd, struct map_session_data* target_sd)
7120{
7121        char output[256];
7122
7123        // " -- Player %s invites %s to duel --"
7124        sprintf(output, msg_txt(373), sd->status.name, target_sd->status.name);
7125        clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
7126
7127        target_sd->duel_invite = did;
7128        duel_list[did].invites_count++;
7129       
7130        // "Blue -- Player %s invites you to PVP duel (@accept/@reject) --"
7131        sprintf(output, msg_txt(374), sd->status.name);
7132        clif_GMmessage((struct block_list *)target_sd, output, strlen(output)+1, 3);
7133        return 0;
7134}
7135
7136static int duel_leave_sub(struct map_session_data* sd, va_list va)
7137{
7138        int did = va_arg(va, int);
7139        if (sd->duel_invite == did)
7140                sd->duel_invite = 0;
7141        return 0;
7142}
7143
7144int duel_leave(const unsigned int did, struct map_session_data* sd)
7145{
7146        char output[256];
7147       
7148        // " <- Player %s has left duel --"
7149        sprintf(output, msg_txt(375), sd->status.name);
7150        clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
7151       
7152        duel_list[did].members_count--;
7153       
7154        if(duel_list[did].members_count == 0) {
7155                map_foreachpc(duel_leave_sub, did); 
7156                duel_count--;
7157        }
7158       
7159        sd->duel_group = 0;
7160        duel_savetime(sd);
7161        clif_set0199(sd, 0);
7162        return 0;
7163}
7164
7165int duel_accept(const unsigned int did, struct map_session_data* sd)
7166{
7167        char output[256];
7168       
7169        duel_list[did].members_count++;
7170        sd->duel_group = sd->duel_invite;
7171        duel_list[did].invites_count--;
7172        sd->duel_invite = 0;
7173       
7174        // " -> Player %s has accepted duel --"
7175        sprintf(output, msg_txt(376), sd->status.name);
7176        clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
7177
7178        clif_set0199(sd, 1);
7179        //clif_misceffect2(&sd->bl, 159);
7180        return 0;
7181}
7182
7183int duel_reject(const unsigned int did, struct map_session_data* sd)
7184{
7185        char output[256];
7186       
7187        // " -- Player %s has rejected duel --"
7188        sprintf(output, msg_txt(377), sd->status.name);
7189        clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
7190       
7191        duel_list[did].invites_count--;
7192        sd->duel_invite = 0;
7193        return 0;
7194}
7195
7196int pc_split_str(char *str,char **val,int num)
7197{
7198        int i;
7199
7200        for (i=0; i<num && str; i++){
7201                val[i] = str;
7202                str = strchr(str,',');
7203                if (str && i<num-1) //Do not remove a trailing comma.
7204                        *str++=0;
7205        }
7206        return i;
7207}
7208
7209int pc_split_atoi(char* str, int* val, char sep, int max)
7210{
7211        int i,j;
7212        for (i=0; i<max; i++) {
7213                if (!str) break;
7214                val[i] = atoi(str);
7215                str = strchr(str,sep);
7216                if (str)
7217                        *str++=0;
7218        }
7219        //Zero up the remaining.
7220        for(j=i; j < max; j++)
7221                val[j] = 0;
7222        return i;
7223}
7224
7225int pc_split_atoui(char* str, unsigned int* val, char sep, int max)
7226{
7227        static int warning=0;
7228        int i,j;
7229        double f;
7230        for (i=0; i<max; i++) {
7231                if (!str) break;
7232                f = atof(str);
7233                if (f < 0)
7234                        val[i] = 0;
7235                else if (f > UINT_MAX) {
7236                        val[i] = UINT_MAX;
7237                        if (!warning) {
7238                                warning = 1;
7239                                ShowWarning("pc_readdb (exp.txt): Required exp per level is capped to %u\n", UINT_MAX);
7240                        }
7241                } else
7242                        val[i] = (unsigned int)f;
7243                str = strchr(str,sep);
7244                if (str)
7245                        *str++=0;
7246        }
7247        //Zero up the remaining.
7248        for(j=i; j < max; j++)
7249                val[j] = 0;
7250        return i;
7251}
7252
7253/*==========================================
7254 * DB reading.
7255 * exp.txt        - required experience values
7256 * job_db1.txt    - weight, hp, sp, aspd
7257 * job_db2.txt    - job level stat bonuses
7258 * skill_tree.txt - skill tree for every class
7259 * attr_fix.txt   - elemental adjustment table
7260 * size_fix.txt   - size adjustment table for weapons
7261 * refine_db.txt  - refining data table
7262 *------------------------------------------*/
7263int pc_readdb(void)
7264{
7265        int i,j,k;
7266        FILE *fp;
7267        char line[24000],*p;
7268
7269        // •K—v??’l?‚Ý?‚Ý
7270        memset(exp_table,0,sizeof(exp_table));
7271        memset(max_level,0,sizeof(max_level));
7272        sprintf(line, "%s/exp.txt", db_path);
7273        fp=fopen(line, "r");
7274        if(fp==NULL){
7275                ShowError("can't read %s\n", line);
7276                return 1;
7277        }
7278        while(fgets(line, sizeof(line), fp))
7279        {
7280                int jobs[CLASS_COUNT], job_count, job, job_id;
7281                int type;
7282                unsigned int ui,maxlv;
7283                char *split[4];
7284                if(line[0]=='/' && line[1]=='/')
7285                        continue;
7286                if (pc_split_str(line,split,4) < 4)
7287                        continue;
7288               
7289                job_count = pc_split_atoi(split[1],jobs,':',CLASS_COUNT);
7290                if (job_count < 1)
7291                        continue;
7292                job_id = jobs[0];
7293                if (!pcdb_checkid(job_id)) {
7294                        ShowError("pc_readdb: Invalid job ID %d.\n", job_id);
7295                        continue;
7296                }
7297                type = atoi(split[2]);
7298                if (type < 0 || type > 1) {
7299                        ShowError("pc_readdb: Invalid type %d (must be 0 for base levels, 1 for job levels).\n", type);
7300                        continue;
7301                }
7302                maxlv = atoi(split[0]);
7303                if (maxlv > MAX_LEVEL) {
7304                        ShowWarning("pc_readdb: Specified max level %u for job %d is beyond server's limit (%u).\n ", maxlv, job_id, MAX_LEVEL);
7305                        maxlv = MAX_LEVEL;
7306                }
7307               
7308                job = jobs[0] = pc_class2idx(job_id);
7309                //We send one less and then one more because the last entry in the exp array should hold 0.
7310                max_level[job][type] = pc_split_atoui(split[3], exp_table[job][type],',',maxlv-1)+1;
7311                //Reverse check in case the array has a bunch of trailing zeros... [Skotlex]
7312                //The reasoning behind the -2 is this... if the max level is 5, then the array
7313                //should look like this:
7314           //0: x, 1: x, 2: x: 3: x 4: 0 <- last valid value is at 3.
7315                while ((ui = max_level[job][type]) >= 2 && exp_table[job][type][ui-2] <= 0)
7316                        max_level[job][type]--;
7317                if (max_level[job][type] < maxlv) {
7318                        ShowWarning("pc_readdb: Specified max %u for job %d, but that job's exp table only goes up to level %u.\n", maxlv, job_id, max_level[job][type]);
7319                        ShowInfo("Filling the missing values with the last exp entry.\n");
7320                        //Fill the requested values with the last entry.
7321                        ui = (max_level[job][type] <= 2? 0: max_level[job][type]-2);
7322                        for (; ui+2 < maxlv; ui++)
7323                                exp_table[job][type][ui] = exp_table[job][type][ui-1];
7324                        max_level[job][type] = maxlv;
7325                }
7326//              ShowDebug("%s - Class %d: %d\n", type?"Job":"Base", job_id, max_level[job][type]);
7327                for (i = 1; i < job_count; i++) {
7328                        job_id = jobs[i];
7329                        if (!pcdb_checkid(job_id)) {
7330                                ShowError("pc_readdb: Invalid job ID %d.\n", job_id);
7331                                continue;
7332                        }
7333                        job = pc_class2idx(job_id);
7334                        memcpy(exp_table[job][type], exp_table[jobs[0]][type], sizeof(exp_table[0][0]));
7335                        max_level[job][type] = maxlv;
7336//                      ShowDebug("%s - Class %d: %u\n", type?"Job":"Base", job_id, max_level[job][type]);
7337                }
7338        }
7339        fclose(fp);
7340        for (i = 0; i < JOB_MAX; i++) {
7341                if (!pcdb_checkid(i)) continue;
7342                if (i == JOB_WEDDING || i == JOB_XMAS || i == JOB_SUMMER)
7343                        continue; //Classes that do not need exp tables.
7344                j = pc_class2idx(i);
7345                if (!max_level[j][0])
7346                        ShowWarning("Class %s (%d) does not has a base exp table.\n", job_name(i), i);
7347                if (!max_level[j][1])
7348                        ShowWarning("Class %s (%d) does not has a job exp table.\n", job_name(i), i);
7349        }
7350        ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n","exp.txt");
7351
7352        // ƒXƒLƒ‹ƒcƒŠ?
7353        memset(skill_tree,0,sizeof(skill_tree));
7354        sprintf(line, "%s/skill_tree.txt", db_path);
7355        fp=fopen(line,"r");
7356        if(fp==NULL){
7357                ShowError("can't read %s\n", line);
7358                return 1;
7359        }
7360
7361        while(fgets(line, sizeof(line), fp))
7362        {
7363                char *split[50];
7364                int f=0, m=3, idx;
7365                if(line[0]=='/' && line[1]=='/')
7366                        continue;
7367                for(j=0,p=line;j<14 && p;j++){
7368                        split[j]=p;
7369                        p=strchr(p,',');
7370                        if(p) *p++=0;
7371                }
7372                if(j<13)
7373                        continue;
7374                if (j == 14) {
7375                        f=1;    // MinJobLvl has been added
7376                        m++;
7377                }
7378                // check for bounds [celest]
7379                idx = atoi(split[0]);
7380                if(!pcdb_checkid(idx))
7381                        continue;
7382                idx = pc_class2idx(idx);
7383                k = atoi(split[1]); //This is to avoid adding two lines for the same skill. [Skotlex]
7384                ARR_FIND( 0, MAX_SKILL_TREE, j, skill_tree[idx][j].id == 0 || skill_tree[idx][j].id == k );
7385                if( j == MAX_SKILL_TREE )
7386                {
7387                        ShowWarning("Unable to load skill %d into job %d's tree. Maximum number of skills per class has been reached.\n", k, atoi(split[0]));
7388                        continue;
7389                }
7390                skill_tree[idx][j].id=k;
7391                skill_tree[idx][j].max=atoi(split[2]);
7392                if (f) skill_tree[idx][j].joblv=atoi(split[3]);
7393
7394                for(k=0;k<5;k++){
7395                        skill_tree[idx][j].need[k].id=atoi(split[k*2+m]);
7396                        skill_tree[idx][j].need[k].lv=atoi(split[k*2+m+1]);
7397                }
7398        }
7399        fclose(fp);
7400        ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n","skill_tree.txt");
7401
7402        // ?«C³ƒe?ƒuƒ‹
7403        for(i=0;i<4;i++)
7404                for(j=0;j<ELE_MAX;j++)
7405                        for(k=0;k<ELE_MAX;k++)
7406                                attr_fix_table[i][j][k]=100;
7407
7408        sprintf(line, "%s/attr_fix.txt", db_path);
7409        fp=fopen(line,"r");
7410        if(fp==NULL){
7411                ShowError("can't read %s\n", line);
7412                return 1;
7413        }
7414        while(fgets(line, sizeof(line), fp))
7415        {
7416                char *split[10];
7417                int lv,n;
7418                if(line[0]=='/' && line[1]=='/')
7419                        continue;
7420                for(j=0,p=line;j<3 && p;j++){
7421                        split[j]=p;
7422                        p=strchr(p,',');
7423                        if(p) *p++=0;
7424                }
7425                lv=atoi(split[0]);
7426                n=atoi(split[1]);
7427
7428                for(i=0;i<n && i<ELE_MAX;){
7429                        if( !fgets(line, sizeof(line), fp) )
7430                                break;
7431                        if(line[0]=='/' && line[1]=='/')
7432                                continue;
7433
7434                        for(j=0,p=line;j<n && j<ELE_MAX && p;j++){
7435                                while(*p==32 && *p>0)
7436                                        p++;
7437                                attr_fix_table[lv-1][i][j]=atoi(p);
7438                                if(battle_config.attr_recover == 0 && attr_fix_table[lv-1][i][j] < 0)
7439                                        attr_fix_table[lv-1][i][j] = 0;
7440                                p=strchr(p,',');
7441                                if(p) *p++=0;
7442                        }
7443
7444                        i++;
7445                }
7446        }
7447        fclose(fp);
7448        ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n","attr_fix.txt");
7449
7450        // ƒXƒLƒ‹ƒcƒŠ?
7451        memset(statp,0,sizeof(statp));
7452        i=1;
7453        j=45;   // base points
7454        sprintf(line, "%s/statpoint.txt", db_path);
7455        fp=fopen(line,"r");
7456        if(fp == NULL){
7457                ShowStatus("Can't read '"CL_WHITE"%s"CL_RESET"'... Generating DB.\n",line);
7458                //return 1;
7459        } else {
7460                while(fgets(line, sizeof(line), fp))
7461                {
7462                        if(line[0]=='/' && line[1]=='/')
7463                                continue;
7464                        if ((j=atoi(line))<0)
7465                                j=0;
7466                        if (i > MAX_LEVEL)
7467                                break;
7468                        statp[i]=j;                     
7469                        i++;
7470                }
7471                fclose(fp);
7472                ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n","statpoint.txt");
7473        }
7474        // generate the remaining parts of the db if necessary
7475        for (; i <= MAX_LEVEL; i++) {
7476                j += (i+15)/5;
7477                statp[i] = j;           
7478        }
7479
7480        return 0;
7481}
7482
7483// Read MOTD on startup. [Valaris]
7484int pc_read_motd(void)
7485{
7486        FILE *fp;
7487        int ln=0,i=0;
7488
7489        memset(motd_text,0,sizeof(motd_text));
7490        if ((fp = fopen(motd_txt, "r")) != NULL) {
7491                while ((ln < MOTD_LINE_SIZE) && fgets(motd_text[ln], sizeof(motd_text[ln])-1, fp) != NULL) {
7492                        if(motd_text[ln][0] == '/' && motd_text[ln][1] == '/')
7493                                continue;
7494                        for(i=0; motd_text[ln][i]; i++) {
7495                                if (motd_text[ln][i] == '\r' || motd_text[ln][i]== '\n') {
7496                                        if(i)
7497                                                motd_text[ln][i]=0;
7498                                        else
7499                                                motd_text[ln][0]=' ';
7500                                        ln++;
7501                                        break;
7502                                }
7503                        }
7504                }
7505                fclose(fp);
7506        }
7507        else
7508                ShowWarning("In function pc_read_motd() -> File '"CL_WHITE"%s"CL_RESET"' not found.\n", motd_txt);
7509       
7510        return 0;
7511}
7512
7513/*==========================================
7514 * pc? ŒW‰Šú‰»
7515 *------------------------------------------*/
7516void do_final_pc(void)
7517{
7518        if (gm_account)
7519                aFree(gm_account);
7520        return;
7521}
7522
7523int do_init_pc(void)
7524{
7525        pc_readdb();
7526        pc_read_motd(); // Read MOTD [Valaris]
7527
7528        memset(&duel_list[0], 0, sizeof(duel_list));
7529
7530        add_timer_func_list(pc_invincible_timer, "pc_invincible_timer");
7531        add_timer_func_list(pc_eventtimer, "pc_eventtimer");
7532        add_timer_func_list(pc_calc_pvprank_timer, "pc_calc_pvprank_timer");
7533        add_timer_func_list(pc_autosave, "pc_autosave");
7534        add_timer_func_list(pc_spiritball_timer, "pc_spiritball_timer");
7535        add_timer_func_list(pc_follow_timer, "pc_follow_timer");
7536
7537        add_timer(gettick() + autosave_interval, pc_autosave, 0, 0);
7538
7539        if (battle_config.day_duration > 0 && battle_config.night_duration > 0) {
7540                int day_duration = battle_config.day_duration;
7541                int night_duration = battle_config.night_duration;
7542                // add night/day timer (by [yor])
7543                add_timer_func_list(map_day_timer, "map_day_timer"); // by [yor]
7544                add_timer_func_list(map_night_timer, "map_night_timer"); // by [yor]
7545
7546                if (!battle_config.night_at_start) {
7547                        night_flag = 0; // 0=day, 1=night [Yor]
7548                        day_timer_tid = add_timer_interval(gettick() + day_duration + night_duration, map_day_timer, 0, 0, day_duration + night_duration);
7549                        night_timer_tid = add_timer_interval(gettick() + day_duration, map_night_timer, 0, 0, day_duration + night_duration);
7550                } else {
7551                        night_flag = 1; // 0=day, 1=night [Yor]
7552                        day_timer_tid = add_timer_interval(gettick() + night_duration, map_day_timer, 0, 0, day_duration + night_duration);
7553                        night_timer_tid = add_timer_interval(gettick() + day_duration + night_duration, map_night_timer, 0, 0, day_duration + night_duration);
7554                }
7555        }
7556
7557        return 0;
7558}
Note: See TracBrowser for help on using the browser.