root/src/map/pc.c @ 10

Revision 10, 216.7 kB (checked in by jinshiro, 17 years ago)

Finished Draft for Adept, Necro and Warlock.

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