IoNuTzU

AntiFeed

Oct 17th, 2015
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 311.83 KB | None | 0 0
  1. /*
  2.  * This program is free software: you can redistribute it and/or modify it under
  3.  * the terms of the GNU General Public License as published by the Free Software
  4.  * Foundation, either version 3 of the License, or (at your option) any later
  5.  * version.
  6.  *
  7.  * This program is distributed in the hope that it will be useful, but WITHOUT
  8.  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9.  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10.  * details.
  11.  *
  12.  * You should have received a copy of the GNU General Public License along with
  13.  * this program. If not, see <http://www.gnu.org/licenses/>.
  14.  */
  15. package net.sf.l2j.gameserver.model.actor.instance;
  16.  
  17. import java.sql.Connection;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Calendar;
  23. import java.util.Collection;
  24. import java.util.HashMap;
  25. import java.util.LinkedHashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.concurrent.ConcurrentHashMap;
  30. import java.util.concurrent.CopyOnWriteArraySet;
  31. import java.util.concurrent.Future;
  32. import java.util.concurrent.ScheduledFuture;
  33. import java.util.concurrent.TimeUnit;
  34. import java.util.concurrent.atomic.AtomicInteger;
  35. import java.util.concurrent.locks.ReentrantLock;
  36. import java.util.logging.Level;
  37.  
  38. import net.sf.l2j.Config;
  39. import net.sf.l2j.L2DatabaseFactory;
  40. import net.sf.l2j.gameserver.GameTimeController;
  41. import net.sf.l2j.gameserver.GeoData;
  42. import net.sf.l2j.gameserver.ItemsAutoDestroy;
  43. import net.sf.l2j.gameserver.RecipeController;
  44. import net.sf.l2j.gameserver.SevenSigns;
  45. import net.sf.l2j.gameserver.SevenSignsFestival;
  46. import net.sf.l2j.gameserver.ThreadPoolManager;
  47. import net.sf.l2j.gameserver.ai.CtrlIntention;
  48. import net.sf.l2j.gameserver.ai.L2CharacterAI;
  49. import net.sf.l2j.gameserver.ai.L2PlayerAI;
  50. import net.sf.l2j.gameserver.ai.L2SummonAI;
  51. import net.sf.l2j.gameserver.communitybbs.BB.Forum;
  52. import net.sf.l2j.gameserver.communitybbs.Manager.ForumsBBSManager;
  53. import net.sf.l2j.gameserver.datatables.AccessLevels;
  54. import net.sf.l2j.gameserver.datatables.CharNameTable;
  55. import net.sf.l2j.gameserver.datatables.CharTemplateTable;
  56. import net.sf.l2j.gameserver.datatables.ClanTable;
  57. import net.sf.l2j.gameserver.datatables.FishTable;
  58. import net.sf.l2j.gameserver.datatables.GmListTable;
  59. import net.sf.l2j.gameserver.datatables.HennaTable;
  60. import net.sf.l2j.gameserver.datatables.ItemTable;
  61. import net.sf.l2j.gameserver.datatables.MapRegionTable;
  62. import net.sf.l2j.gameserver.datatables.PetDataTable;
  63. import net.sf.l2j.gameserver.datatables.SkillTable;
  64. import net.sf.l2j.gameserver.datatables.SkillTable.FrequentSkill;
  65. import net.sf.l2j.gameserver.datatables.SkillTreeTable;
  66. import net.sf.l2j.gameserver.handler.IItemHandler;
  67. import net.sf.l2j.gameserver.handler.ItemHandler;
  68. import net.sf.l2j.gameserver.instancemanager.AntiFeedManager;
  69. import net.sf.l2j.gameserver.instancemanager.CastleManager;
  70. import net.sf.l2j.gameserver.instancemanager.CoupleManager;
  71. import net.sf.l2j.gameserver.instancemanager.CursedWeaponsManager;
  72. import net.sf.l2j.gameserver.instancemanager.DimensionalRiftManager;
  73. import net.sf.l2j.gameserver.instancemanager.DuelManager;
  74. import net.sf.l2j.gameserver.instancemanager.GrandBossManager;
  75. import net.sf.l2j.gameserver.instancemanager.ItemsOnGroundManager;
  76. import net.sf.l2j.gameserver.instancemanager.QuestManager;
  77. import net.sf.l2j.gameserver.instancemanager.SiegeManager;
  78. import net.sf.l2j.gameserver.model.BlockList;
  79. import net.sf.l2j.gameserver.model.FishData;
  80. import net.sf.l2j.gameserver.model.L2AccessLevel;
  81. import net.sf.l2j.gameserver.model.L2Clan;
  82. import net.sf.l2j.gameserver.model.L2ClanMember;
  83. import net.sf.l2j.gameserver.model.L2Effect;
  84. import net.sf.l2j.gameserver.model.L2Fishing;
  85. import net.sf.l2j.gameserver.model.L2ItemInstance;
  86. import net.sf.l2j.gameserver.model.L2Macro;
  87. import net.sf.l2j.gameserver.model.L2ManufactureList;
  88. import net.sf.l2j.gameserver.model.L2Object;
  89. import net.sf.l2j.gameserver.model.L2Party;
  90. import net.sf.l2j.gameserver.model.L2PetData;
  91. import net.sf.l2j.gameserver.model.L2PetData.L2PetLevelData;
  92. import net.sf.l2j.gameserver.model.L2Radar;
  93. import net.sf.l2j.gameserver.model.L2RecipeList;
  94. import net.sf.l2j.gameserver.model.L2Request;
  95. import net.sf.l2j.gameserver.model.L2ShortCut;
  96. import net.sf.l2j.gameserver.model.L2Skill;
  97. import net.sf.l2j.gameserver.model.L2Skill.SkillTargetType;
  98. import net.sf.l2j.gameserver.model.L2SkillLearn;
  99. import net.sf.l2j.gameserver.model.L2World;
  100. import net.sf.l2j.gameserver.model.L2WorldRegion;
  101. import net.sf.l2j.gameserver.model.Location;
  102. import net.sf.l2j.gameserver.model.MacroList;
  103. import net.sf.l2j.gameserver.model.PartyMatchRoom;
  104. import net.sf.l2j.gameserver.model.PartyMatchRoomList;
  105. import net.sf.l2j.gameserver.model.PartyMatchWaitingList;
  106. import net.sf.l2j.gameserver.model.ShortCuts;
  107. import net.sf.l2j.gameserver.model.ShotType;
  108. import net.sf.l2j.gameserver.model.TradeList;
  109. import net.sf.l2j.gameserver.model.actor.L2Attackable;
  110. import net.sf.l2j.gameserver.model.actor.L2Character;
  111. import net.sf.l2j.gameserver.model.actor.L2Npc;
  112. import net.sf.l2j.gameserver.model.actor.L2Playable;
  113. import net.sf.l2j.gameserver.model.actor.L2Summon;
  114. import net.sf.l2j.gameserver.model.actor.L2Vehicle;
  115. import net.sf.l2j.gameserver.model.actor.appearance.PcAppearance;
  116. import net.sf.l2j.gameserver.model.actor.knownlist.PcKnownList;
  117. import net.sf.l2j.gameserver.model.actor.position.PcPosition;
  118. import net.sf.l2j.gameserver.model.actor.stat.PcStat;
  119. import net.sf.l2j.gameserver.model.actor.status.PcStatus;
  120. import net.sf.l2j.gameserver.model.base.ClassId;
  121. import net.sf.l2j.gameserver.model.base.ClassLevel;
  122. import net.sf.l2j.gameserver.model.base.Experience;
  123. import net.sf.l2j.gameserver.model.base.PlayerClass;
  124. import net.sf.l2j.gameserver.model.base.Race;
  125. import net.sf.l2j.gameserver.model.base.SubClass;
  126. import net.sf.l2j.gameserver.model.entity.Castle;
  127. import net.sf.l2j.gameserver.model.entity.Duel;
  128. import net.sf.l2j.gameserver.model.entity.Hero;
  129. import net.sf.l2j.gameserver.model.entity.Siege;
  130. import net.sf.l2j.gameserver.model.itemcontainer.Inventory;
  131. import net.sf.l2j.gameserver.model.itemcontainer.ItemContainer;
  132. import net.sf.l2j.gameserver.model.itemcontainer.PcFreight;
  133. import net.sf.l2j.gameserver.model.itemcontainer.PcInventory;
  134. import net.sf.l2j.gameserver.model.itemcontainer.PcWarehouse;
  135. import net.sf.l2j.gameserver.model.itemcontainer.PetInventory;
  136. import net.sf.l2j.gameserver.model.olympiad.OlympiadGameManager;
  137. import net.sf.l2j.gameserver.model.olympiad.OlympiadGameTask;
  138. import net.sf.l2j.gameserver.model.olympiad.OlympiadManager;
  139. import net.sf.l2j.gameserver.model.quest.Quest;
  140. import net.sf.l2j.gameserver.model.quest.QuestEventType;
  141. import net.sf.l2j.gameserver.model.quest.QuestState;
  142. import net.sf.l2j.gameserver.model.zone.ZoneId;
  143. import net.sf.l2j.gameserver.model.zone.type.L2BossZone;
  144. import net.sf.l2j.gameserver.network.L2GameClient;
  145. import net.sf.l2j.gameserver.network.SystemMessageId;
  146. import net.sf.l2j.gameserver.network.serverpackets.AbstractNpcInfo;
  147. import net.sf.l2j.gameserver.network.serverpackets.ActionFailed;
  148. import net.sf.l2j.gameserver.network.serverpackets.ChangeWaitType;
  149. import net.sf.l2j.gameserver.network.serverpackets.CharInfo;
  150. import net.sf.l2j.gameserver.network.serverpackets.ConfirmDlg;
  151. import net.sf.l2j.gameserver.network.serverpackets.EtcStatusUpdate;
  152. import net.sf.l2j.gameserver.network.serverpackets.ExAutoSoulShot;
  153. import net.sf.l2j.gameserver.network.serverpackets.ExDuelUpdateUserInfo;
  154. import net.sf.l2j.gameserver.network.serverpackets.ExFishingEnd;
  155. import net.sf.l2j.gameserver.network.serverpackets.ExFishingStart;
  156. import net.sf.l2j.gameserver.network.serverpackets.ExOlympiadMode;
  157. import net.sf.l2j.gameserver.network.serverpackets.ExSetCompassZoneCode;
  158. import net.sf.l2j.gameserver.network.serverpackets.ExStorageMaxCount;
  159. import net.sf.l2j.gameserver.network.serverpackets.FriendList;
  160. import net.sf.l2j.gameserver.network.serverpackets.GetOnVehicle;
  161. import net.sf.l2j.gameserver.network.serverpackets.HennaInfo;
  162. import net.sf.l2j.gameserver.network.serverpackets.InventoryUpdate;
  163. import net.sf.l2j.gameserver.network.serverpackets.ItemList;
  164. import net.sf.l2j.gameserver.network.serverpackets.L2GameServerPacket;
  165. import net.sf.l2j.gameserver.network.serverpackets.LeaveWorld;
  166. import net.sf.l2j.gameserver.network.serverpackets.MagicSkillUse;
  167. import net.sf.l2j.gameserver.network.serverpackets.MoveToPawn;
  168. import net.sf.l2j.gameserver.network.serverpackets.MyTargetSelected;
  169. import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
  170. import net.sf.l2j.gameserver.network.serverpackets.ObservationMode;
  171. import net.sf.l2j.gameserver.network.serverpackets.ObservationReturn;
  172. import net.sf.l2j.gameserver.network.serverpackets.PartySmallWindowUpdate;
  173. import net.sf.l2j.gameserver.network.serverpackets.PetInventoryUpdate;
  174. import net.sf.l2j.gameserver.network.serverpackets.PlaySound;
  175. import net.sf.l2j.gameserver.network.serverpackets.PledgeShowMemberListDelete;
  176. import net.sf.l2j.gameserver.network.serverpackets.PledgeShowMemberListUpdate;
  177. import net.sf.l2j.gameserver.network.serverpackets.PrivateStoreListBuy;
  178. import net.sf.l2j.gameserver.network.serverpackets.PrivateStoreListSell;
  179. import net.sf.l2j.gameserver.network.serverpackets.PrivateStoreManageListBuy;
  180. import net.sf.l2j.gameserver.network.serverpackets.PrivateStoreManageListSell;
  181. import net.sf.l2j.gameserver.network.serverpackets.PrivateStoreMsgBuy;
  182. import net.sf.l2j.gameserver.network.serverpackets.PrivateStoreMsgSell;
  183. import net.sf.l2j.gameserver.network.serverpackets.RecipeShopManageList;
  184. import net.sf.l2j.gameserver.network.serverpackets.RecipeShopMsg;
  185. import net.sf.l2j.gameserver.network.serverpackets.RecipeShopSellList;
  186. import net.sf.l2j.gameserver.network.serverpackets.RelationChanged;
  187. import net.sf.l2j.gameserver.network.serverpackets.Ride;
  188. import net.sf.l2j.gameserver.network.serverpackets.SendTradeDone;
  189. import net.sf.l2j.gameserver.network.serverpackets.ServerClose;
  190. import net.sf.l2j.gameserver.network.serverpackets.SetupGauge;
  191. import net.sf.l2j.gameserver.network.serverpackets.ShortBuffStatusUpdate;
  192. import net.sf.l2j.gameserver.network.serverpackets.ShortCutInit;
  193. import net.sf.l2j.gameserver.network.serverpackets.SkillCoolTime;
  194. import net.sf.l2j.gameserver.network.serverpackets.SkillList;
  195. import net.sf.l2j.gameserver.network.serverpackets.Snoop;
  196. import net.sf.l2j.gameserver.network.serverpackets.SocialAction;
  197. import net.sf.l2j.gameserver.network.serverpackets.StatusUpdate;
  198. import net.sf.l2j.gameserver.network.serverpackets.StopMove;
  199. import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
  200. import net.sf.l2j.gameserver.network.serverpackets.TargetSelected;
  201. import net.sf.l2j.gameserver.network.serverpackets.TargetUnselected;
  202. import net.sf.l2j.gameserver.network.serverpackets.TradePressOtherOk;
  203. import net.sf.l2j.gameserver.network.serverpackets.TradePressOwnOk;
  204. import net.sf.l2j.gameserver.network.serverpackets.TradeStart;
  205. import net.sf.l2j.gameserver.network.serverpackets.UserInfo;
  206. import net.sf.l2j.gameserver.skills.Env;
  207. import net.sf.l2j.gameserver.skills.Formulas;
  208. import net.sf.l2j.gameserver.skills.Stats;
  209. import net.sf.l2j.gameserver.skills.effects.EffectTemplate;
  210. import net.sf.l2j.gameserver.skills.funcs.FuncBowAtkRange;
  211. import net.sf.l2j.gameserver.skills.funcs.FuncHennaCON;
  212. import net.sf.l2j.gameserver.skills.funcs.FuncHennaDEX;
  213. import net.sf.l2j.gameserver.skills.funcs.FuncHennaINT;
  214. import net.sf.l2j.gameserver.skills.funcs.FuncHennaMEN;
  215. import net.sf.l2j.gameserver.skills.funcs.FuncHennaSTR;
  216. import net.sf.l2j.gameserver.skills.funcs.FuncHennaWIT;
  217. import net.sf.l2j.gameserver.skills.funcs.FuncMaxCpAdd;
  218. import net.sf.l2j.gameserver.skills.funcs.FuncMaxCpMul;
  219. import net.sf.l2j.gameserver.skills.funcs.FuncMaxHpAdd;
  220. import net.sf.l2j.gameserver.skills.funcs.FuncMaxMpAdd;
  221. import net.sf.l2j.gameserver.skills.l2skills.L2SkillSiegeFlag;
  222. import net.sf.l2j.gameserver.skills.l2skills.L2SkillSummon;
  223. import net.sf.l2j.gameserver.taskmanager.AttackStanceTaskManager;
  224. import net.sf.l2j.gameserver.taskmanager.PvpFlagTaskManager;
  225. import net.sf.l2j.gameserver.taskmanager.TakeBreakTaskManager;
  226. import net.sf.l2j.gameserver.taskmanager.WaterTaskManager;
  227. import net.sf.l2j.gameserver.templates.chars.L2PcTemplate;
  228. import net.sf.l2j.gameserver.templates.item.L2ActionType;
  229. import net.sf.l2j.gameserver.templates.item.L2Armor;
  230. import net.sf.l2j.gameserver.templates.item.L2ArmorType;
  231. import net.sf.l2j.gameserver.templates.item.L2EtcItemType;
  232. import net.sf.l2j.gameserver.templates.item.L2Henna;
  233. import net.sf.l2j.gameserver.templates.item.L2Item;
  234. import net.sf.l2j.gameserver.templates.item.L2Weapon;
  235. import net.sf.l2j.gameserver.templates.item.L2WeaponType;
  236. import net.sf.l2j.gameserver.templates.skills.L2EffectFlag;
  237. import net.sf.l2j.gameserver.templates.skills.L2EffectType;
  238. import net.sf.l2j.gameserver.templates.skills.L2SkillType;
  239. import net.sf.l2j.gameserver.util.Broadcast;
  240. import net.sf.l2j.gameserver.util.FloodProtectors;
  241. import net.sf.l2j.gameserver.util.Util;
  242. import net.sf.l2j.util.Point3D;
  243. import net.sf.l2j.util.Rnd;
  244.  
  245. /**
  246.  * This class represents all player characters in the world. There is always a client-thread connected to this (except if a player-store is activated upon logout).
  247.  */
  248. public final class L2PcInstance extends L2Playable
  249. {
  250.     // Character Skill SQL String Definitions:
  251.     private static final String RESTORE_SKILLS_FOR_CHAR = "SELECT skill_id,skill_level FROM character_skills WHERE char_obj_id=? AND class_index=?";
  252.     private static final String ADD_NEW_SKILL = "INSERT INTO character_skills (char_obj_id,skill_id,skill_level,class_index) VALUES (?,?,?,?)";
  253.     private static final String UPDATE_CHARACTER_SKILL_LEVEL = "UPDATE character_skills SET skill_level=? WHERE skill_id=? AND char_obj_id=? AND class_index=?";
  254.     private static final String DELETE_SKILL_FROM_CHAR = "DELETE FROM character_skills WHERE skill_id=? AND char_obj_id=? AND class_index=?";
  255.     private static final String DELETE_CHAR_SKILLS = "DELETE FROM character_skills WHERE char_obj_id=? AND class_index=?";
  256.    
  257.     // Character Skill Save SQL String Definitions:
  258.     private static final String ADD_SKILL_SAVE = "INSERT INTO character_skills_save (char_obj_id,skill_id,skill_level,effect_count,effect_cur_time,reuse_delay,systime,restore_type,class_index,buff_index) VALUES (?,?,?,?,?,?,?,?,?,?)";
  259.     private static final String RESTORE_SKILL_SAVE = "SELECT skill_id,skill_level,effect_count,effect_cur_time, reuse_delay, systime, restore_type FROM character_skills_save WHERE char_obj_id=? AND class_index=? ORDER BY buff_index ASC";
  260.     private static final String DELETE_SKILL_SAVE = "DELETE FROM character_skills_save WHERE char_obj_id=? AND class_index=?";
  261.    
  262.     // Character SQL String Definitions:
  263.     private static final String INSERT_CHARACTER = "INSERT INTO characters (account_name,obj_Id,char_name,level,maxHp,curHp,maxCp,curCp,maxMp,curMp,face,hairStyle,hairColor,sex,exp,sp,karma,pvpkills,pkkills,clanid,race,classid,deletetime,cancraft,title,accesslevel,online,isin7sdungeon,clan_privs,wantspeace,base_class,nobless,power_grade,last_recom_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  264.     private static final String UPDATE_CHARACTER = "UPDATE characters SET level=?,maxHp=?,curHp=?,maxCp=?,curCp=?,maxMp=?,curMp=?,face=?,hairStyle=?,hairColor=?,sex=?,heading=?,x=?,y=?,z=?,exp=?,expBeforeDeath=?,sp=?,karma=?,pvpkills=?,pkkills=?,rec_have=?,rec_left=?,clanid=?,race=?,classid=?,deletetime=?,title=?,accesslevel=?,online=?,isin7sdungeon=?,clan_privs=?,wantspeace=?,base_class=?,onlinetime=?,punish_level=?,punish_timer=?,nobless=?,power_grade=?,subpledge=?,last_recom_date=?,lvl_joined_academy=?,apprentice=?,sponsor=?,varka_ketra_ally=?,clan_join_expiry_time=?,clan_create_expiry_time=?,char_name=?,death_penalty_level=?,votebuff=?,vote_end_buff=? WHERE obj_id=?";
  265.     private static final String RESTORE_CHARACTER = "SELECT account_name, obj_Id, char_name, level, maxHp, curHp, maxCp, curCp, maxMp, curMp, face, hairStyle, hairColor, sex, heading, x, y, z, exp, expBeforeDeath, sp, karma, pvpkills, pkkills, clanid, race, classid, deletetime, cancraft, title, rec_have, rec_left, accesslevel, online, char_slot, lastAccess, clan_privs, wantspeace, base_class, onlinetime, isin7sdungeon, punish_level, punish_timer, nobless, power_grade, subpledge, last_recom_date, lvl_joined_academy, apprentice, sponsor, varka_ketra_ally,clan_join_expiry_time,clan_create_expiry_time,death_penalty_level,lastVoteNetwork,lastVoteTopzone,hasVotedNet,hasVotedTop,totalVotes,tries,votebuff,vote_end_buff FROM characters WHERE obj_id=?";
  266.    
  267.     // Character Subclass SQL String Definitions:
  268.     private static final String RESTORE_CHAR_SUBCLASSES = "SELECT class_id,exp,sp,level,class_index FROM character_subclasses WHERE char_obj_id=? ORDER BY class_index ASC";
  269.     private static final String ADD_CHAR_SUBCLASS = "INSERT INTO character_subclasses (char_obj_id,class_id,exp,sp,level,class_index) VALUES (?,?,?,?,?,?)";
  270.     private static final String UPDATE_CHAR_SUBCLASS = "UPDATE character_subclasses SET exp=?,sp=?,level=?,class_id=? WHERE char_obj_id=? AND class_index =?";
  271.     private static final String DELETE_CHAR_SUBCLASS = "DELETE FROM character_subclasses WHERE char_obj_id=? AND class_index=?";
  272.    
  273.     private static final String RESTORE_CHAR_HENNAS = "SELECT slot,symbol_id FROM character_hennas WHERE char_obj_id=? AND class_index=?";
  274.     private static final String ADD_CHAR_HENNA = "INSERT INTO character_hennas (char_obj_id,symbol_id,slot,class_index) VALUES (?,?,?,?)";
  275.     private static final String DELETE_CHAR_HENNA = "DELETE FROM character_hennas WHERE char_obj_id=? AND slot=? AND class_index=?";
  276.     private static final String DELETE_CHAR_HENNAS = "DELETE FROM character_hennas WHERE char_obj_id=? AND class_index=?";
  277.     private static final String DELETE_CHAR_SHORTCUTS = "DELETE FROM character_shortcuts WHERE char_obj_id=? AND class_index=?";
  278.    
  279.     private static final String RESTORE_CHAR_RECOMS = "SELECT char_id,target_id FROM character_recommends WHERE char_id=?";
  280.     private static final String ADD_CHAR_RECOM = "INSERT INTO character_recommends (char_id,target_id) VALUES (?,?)";
  281.     private static final String DELETE_CHAR_RECOMS = "DELETE FROM character_recommends WHERE char_id=?";
  282.    
  283.     private static final String UPDATE_NOBLESS = "UPDATE characters SET nobless=? WHERE obj_Id=?";
  284.    
  285.     public static final int REQUEST_TIMEOUT = 15;
  286.     public static final int STORE_PRIVATE_NONE = 0;
  287.     public static final int STORE_PRIVATE_SELL = 1;
  288.     public static final int STORE_PRIVATE_BUY = 3;
  289.     public static final int STORE_PRIVATE_MANAGE = 4;
  290.     public static final int STORE_PRIVATE_MANUFACTURE = 5;
  291.     public static final int STORE_PRIVATE_PACKAGE_SELL = 8;
  292.    
  293.     /** The table containing all minimum level needed for each Expertise (None, D, C, B, A, S) */
  294.     private static final int[] EXPERTISE_LEVELS =
  295.     {
  296.         SkillTreeTable.getInstance().getExpertiseLevel(0), // NONE
  297.         SkillTreeTable.getInstance().getExpertiseLevel(1), // D
  298.         SkillTreeTable.getInstance().getExpertiseLevel(2), // C
  299.         SkillTreeTable.getInstance().getExpertiseLevel(3), // B
  300.         SkillTreeTable.getInstance().getExpertiseLevel(4), // A
  301.         SkillTreeTable.getInstance().getExpertiseLevel(5), // S
  302.     };
  303.    
  304.     private static final int[] COMMON_CRAFT_LEVELS =
  305.     {
  306.         5,
  307.         20,
  308.         28,
  309.         36,
  310.         43,
  311.         49,
  312.         55,
  313.         62
  314.     };
  315.    
  316.     public class AIAccessor extends L2Character.AIAccessor
  317.     {
  318.         protected AIAccessor()
  319.         {
  320.            
  321.         }
  322.        
  323.         public L2PcInstance getPlayer()
  324.         {
  325.             return L2PcInstance.this;
  326.         }
  327.        
  328.         public void doPickupItem(L2Object object)
  329.         {
  330.             L2PcInstance.this.doPickupItem(object);
  331.            
  332.             // Schedule a paralyzed task to wait for the animation to finish
  333.             ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  334.             {
  335.                 @Override
  336.                 public void run()
  337.                 {
  338.                     setIsParalyzed(false);
  339.                 }
  340.             }, 500);
  341.             setIsParalyzed(true);
  342.         }
  343.        
  344.         public void doInteract(L2Character target)
  345.         {
  346.             L2PcInstance.this.doInteract(target);
  347.         }
  348.        
  349.         @Override
  350.         public void doAttack(L2Character target)
  351.         {
  352.             super.doAttack(target);
  353.            
  354.             // cancel the recent fake-death protection instantly if the player attacks or casts spells
  355.             getPlayer().setRecentFakeDeath(false);
  356.         }
  357.        
  358.         @Override
  359.         public void doCast(L2Skill skill)
  360.         {
  361.             super.doCast(skill);
  362.            
  363.             // cancel the recent fake-death protection instantly if the player attacks or casts spells
  364.             getPlayer().setRecentFakeDeath(false);
  365.         }
  366.     }
  367.    
  368.     private L2GameClient _client;
  369.    
  370.     private String _accountName;
  371.     private long _deleteTimer;
  372.    
  373.     private boolean _isOnline = false;
  374.     private long _onlineTime;
  375.     private long _onlineBeginTime;
  376.     private long _lastAccess;
  377.     private long _uptime;
  378.    
  379.     private final ReentrantLock _subclassLock = new ReentrantLock();
  380.     protected int _baseClass;
  381.     protected int _activeClass;
  382.     protected int _classIndex = 0;
  383.     private final Map<Integer, SubClass> _subClasses = new LinkedHashMap<>();
  384.    
  385.     private PcAppearance _appearance;
  386.     private int _charId = 0x00030b7a;
  387.    
  388.     private long _expBeforeDeath;
  389.     private int _karma;
  390.     private int _pvpKills;
  391.     private int _pkKills;
  392.     private byte _pvpFlag;
  393.     private byte _siegeState = 0;
  394.     private int _curWeightPenalty = 0;
  395.    
  396.     private boolean _isVoteBuff = false;
  397.     private long _votebuff_endTime = 0;
  398.    
  399.     private int _lastCompassZone; // the last compass zone update send to the client
  400.    
  401.     private boolean _isInWater;
  402.     private boolean _isIn7sDungeon = false;
  403.    
  404.     private PunishLevel _punishLevel = PunishLevel.NONE;
  405.     private long _punishTimer = 0;
  406.     private ScheduledFuture<?> _punishTask;
  407.    
  408.     public enum PunishLevel
  409.     {
  410.         NONE(0, ""),
  411.         CHAT(1, "chat banned"),
  412.         JAIL(2, "jailed"),
  413.         CHAR(3, "banned"),
  414.         ACC(4, "banned");
  415.        
  416.         private final int punValue;
  417.         private final String punString;
  418.        
  419.         PunishLevel(int value, String string)
  420.         {
  421.             punValue = value;
  422.             punString = string;
  423.         }
  424.        
  425.         public int value()
  426.         {
  427.             return punValue;
  428.         }
  429.        
  430.         public String string()
  431.         {
  432.             return punString;
  433.         }
  434.     }
  435.    
  436.     /** Olympiad */
  437.     private boolean _inOlympiadMode = false;
  438.     private boolean _OlympiadStart = false;
  439.     private int _olympiadGameId = -1;
  440.     private int _olympiadSide = -1;
  441.    
  442.     /** Duel */
  443.     private boolean _isInDuel = false;
  444.     private int _duelState = Duel.DUELSTATE_NODUEL;
  445.     private int _duelId = 0;
  446.     private SystemMessageId _noDuelReason = SystemMessageId.THERE_IS_NO_OPPONENT_TO_RECEIVE_YOUR_CHALLENGE_FOR_A_DUEL;
  447.    
  448.     /** Boat */
  449.     private L2Vehicle _vehicle = null;
  450.     private Point3D _inVehiclePosition;
  451.    
  452.     public ScheduledFuture<?> _taskforfish;
  453.    
  454.     private int _mountType;
  455.     private int _mountNpcId;
  456.     private int _mountLevel;
  457.     private int _mountObjectID = 0;
  458.    
  459.     public int _telemode = 0;
  460.     private boolean _inCrystallize;
  461.     private boolean _inCraftMode;
  462.    
  463.     private long _offlineShopStart = 0;
  464.     private boolean _inOfflineShopMode = false;
  465.    
  466.     /** The table containing all L2RecipeList of the L2PcInstance */
  467.     private final Map<Integer, L2RecipeList> _dwarvenRecipeBook = new HashMap<>();
  468.     private final Map<Integer, L2RecipeList> _commonRecipeBook = new HashMap<>();
  469.    
  470.     /** True if the L2PcInstance is sitting */
  471.     private boolean _waitTypeSitting;
  472.    
  473.     /** Location before entering Observer Mode */
  474.     private int _lastX;
  475.     private int _lastY;
  476.     private int _lastZ;
  477.     private boolean _observerMode = false;
  478.    
  479.     /** Stored from last ValidatePosition **/
  480.     private final Point3D _lastServerPosition = new Point3D(0, 0, 0);
  481.    
  482.     private int _recomHave; // how much I was recommended by others
  483.     private int _recomLeft; // how many recomendations I can give to others
  484.     private long _lastRecomUpdate;
  485.     private final List<Integer> _recomChars = new ArrayList<>();
  486.    
  487.     private final PcInventory _inventory = new PcInventory(this);
  488.     private PcWarehouse _warehouse;
  489.     private PcFreight _freight;
  490.     private final List<PcFreight> _depositedFreight = new ArrayList<>();
  491.    
  492.     /** The Private Store type of the L2PcInstance (STORE_PRIVATE_NONE=0, STORE_PRIVATE_SELL=1, sellmanage=2, STORE_PRIVATE_BUY=3, buymanage=4, STORE_PRIVATE_MANUFACTURE=5) */
  493.     private int _privateStore;
  494.    
  495.     private TradeList _activeTradeList;
  496.     private ItemContainer _activeWarehouse;
  497.     private L2ManufactureList _createList;
  498.     private TradeList _sellList;
  499.     private TradeList _buyList;
  500.    
  501.     private boolean _noble = false;
  502.     private boolean _hero = false;
  503.    
  504.     /** The L2Npc corresponding to the current folk the player is talking with. */
  505.     private L2Npc _currentFolkNpc = null;
  506.    
  507.     /** Last NPC Id talked on a quest */
  508.     private int _questNpcObject = 0;
  509.    
  510.     /** The list containing all Quests began by the L2PcInstance */
  511.     private final List<QuestState> _quests = new ArrayList<>();
  512.    
  513.     /** List of all QuestState instance that needs to be notified of this L2PcInstance's or its pet's death */
  514.     private final List<QuestState> _notifyQuestOfDeathList = new ArrayList<>();
  515.    
  516.     /** The list containing all shortCuts of this L2PcInstance */
  517.     private final ShortCuts _shortCuts = new ShortCuts(this);
  518.    
  519.     /** The list containing all macroses of this L2PcInstance */
  520.     private final MacroList _macroses = new MacroList(this);
  521.    
  522.     private final List<L2PcInstance> _snoopListener = new ArrayList<>();
  523.     private final List<L2PcInstance> _snoopedPlayer = new ArrayList<>();
  524.    
  525.     private ClassId _skillLearningClassId;
  526.    
  527.     // hennas
  528.     private final L2Henna[] _henna = new L2Henna[3];
  529.     private int _hennaSTR;
  530.     private int _hennaINT;
  531.     private int _hennaDEX;
  532.     private int _hennaMEN;
  533.     private int _hennaWIT;
  534.     private int _hennaCON;
  535.    
  536.     // Summons
  537.     private L2Summon _summon = null;
  538.     private L2TamedBeastInstance _tamedBeast = null;
  539.    
  540.     // client radar
  541.     // TODO: This needs to be better integrated and saved/loaded
  542.     private L2Radar _radar;
  543.    
  544.     // these values are only stored temporarily
  545.     private int _partyroom = 0;
  546.    
  547.     // Clan related attributes
  548.     /** The Clan Identifier of the L2PcInstance */
  549.     private int _clanId;
  550.    
  551.     /** The Clan object of the L2PcInstance */
  552.     private L2Clan _clan;
  553.    
  554.     /** Apprentice and Sponsor IDs */
  555.     private int _apprentice = 0;
  556.     private int _sponsor = 0;
  557.    
  558.     private long _clanJoinExpiryTime;
  559.     private long _clanCreateExpiryTime;
  560.    
  561.     private int _powerGrade = 0;
  562.     private int _clanPrivileges = 0;
  563.    
  564.     /** L2PcInstance's pledge class (knight, Baron, etc.) */
  565.     private int _pledgeClass = 0;
  566.     private int _pledgeType = 0;
  567.    
  568.     /** Level at which the player joined the clan as an academy member */
  569.     private int _lvlJoinedAcademy = 0;
  570.    
  571.     private boolean _wantsPeace;
  572.    
  573.     // Death Penalty Buff Level
  574.     private int _deathPenaltyBuffLevel = 0;
  575.    
  576.     // charges
  577.     private final AtomicInteger _charges = new AtomicInteger();
  578.     private ScheduledFuture<?> _chargeTask = null;
  579.    
  580.     // WorldPosition used by TARGET_SIGNET_GROUND
  581.     private Point3D _currentSkillWorldPosition;
  582.    
  583.     private L2AccessLevel _accessLevel;
  584.    
  585.     private boolean _messageRefusal = false; // message refusal mode
  586.     private boolean _tradeRefusal = false; // Trade refusal
  587.     private boolean _exchangeRefusal = false; // Exchange refusal
  588.    
  589.     private L2Party _party;
  590.    
  591.     // this is needed to find the inviting player for Party response
  592.     // there can only be one active party request at once
  593.     private L2PcInstance _activeRequester;
  594.     private long _requestExpireTime = 0;
  595.     private final L2Request _request = new L2Request(this);
  596.     private L2ItemInstance _arrowItem;
  597.    
  598.     // Used for protection after teleport
  599.     private long _protectEndTime = 0;
  600.    
  601.     // protects a char from agro mobs when getting up from fake death
  602.     private long _recentFakeDeathEndTime = 0;
  603.     private boolean _isFakeDeath;
  604.    
  605.     /** The fists L2Weapon of the L2PcInstance (used when no weapon is equipped) */
  606.     private L2Weapon _fistsWeaponItem;
  607.    
  608.     private final Map<Integer, String> _chars = new HashMap<>();
  609.    
  610.     /** The current higher Expertise of the L2PcInstance (None=0, D=1, C=2, B=3, A=4, S=5) */
  611.     private int _expertiseIndex; // index in EXPERTISE_LEVELS
  612.     private int _expertiseArmorPenalty = 0;
  613.     private boolean _expertiseWeaponPenalty = false;
  614.    
  615.     private L2ItemInstance _activeEnchantItem = null;
  616.    
  617.     protected boolean _inventoryDisable = false;
  618.    
  619.     protected Map<Integer, L2CubicInstance> _cubics = new ConcurrentHashMap<>();
  620.    
  621.     /** Active shots. A FastSet variable would actually suffice but this was changed to fix threading stability... */
  622.     protected Set<Integer> _activeSoulShots = new CopyOnWriteArraySet<>();
  623.    
  624.     private final int _loto[] = new int[5];
  625.     private final int _race[] = new int[2];
  626.    
  627.     private final BlockList _blockList = new BlockList(this);
  628.    
  629.     private int _team = 0;
  630.    
  631.     /**
  632.      * lvl of alliance with ketra orcs or varka silenos, used in quests and aggro checks [-5,-1] varka, 0 neutral, [1,5] ketra
  633.      */
  634.     private int _alliedVarkaKetra = 0;
  635.    
  636.     private Location _fishingLoc;
  637.     private L2ItemInstance _lure = null;
  638.     private L2Fishing _fishCombat;
  639.     private FishData _fish;
  640.    
  641.     /** Bypass validations */
  642.     private final List<String> _validBypass = new ArrayList<>();
  643.     private final List<String> _validBypass2 = new ArrayList<>();
  644.    
  645.     private Forum _forumMail;
  646.     private Forum _forumMemo;
  647.    
  648.     /** data for mounted pets */
  649.     private boolean _canFeed;
  650.     private L2PetData _data;
  651.     private L2PetLevelData _leveldata;
  652.     private int _controlItemId;
  653.     private int _curFeed;
  654.     protected Future<?> _mountFeedTask;
  655.     private ScheduledFuture<?> _dismountTask;
  656.    
  657.     private boolean _isInSiege;
  658.    
  659.     private SkillDat _currentSkill;
  660.     private SkillDat _currentPetSkill;
  661.     private SkillDat _queuedSkill;
  662.    
  663.     private int _cursedWeaponEquippedId = 0;
  664.    
  665.     private int _reviveRequested = 0;
  666.     private double _revivePower = 0;
  667.     private boolean _revivePet = false;
  668.    
  669.     private double _cpUpdateIncCheck = .0;
  670.     private double _cpUpdateDecCheck = .0;
  671.     private double _cpUpdateInterval = .0;
  672.     private double _mpUpdateIncCheck = .0;
  673.     private double _mpUpdateDecCheck = .0;
  674.     private double _mpUpdateInterval = .0;
  675.    
  676.     /** Char Coords from Client */
  677.     private volatile int _clientX;
  678.     private volatile int _clientY;
  679.     private volatile int _clientZ;
  680.     private volatile int _clientHeading;
  681.    
  682.     private int _mailPosition;
  683.    
  684.     // during fall, validation will be disabled for 10 s.
  685.     private static final int FALLING_VALIDATION_DELAY = 10000;
  686.     private volatile long _fallingTimestamp = 0;
  687.    
  688.     private int _herbstask = 0;
  689.    
  690.     /** ShortBuff clearing Task */
  691.     ScheduledFuture<?> _shortBuffTask = null;
  692.     private int _shortBuffTaskSkillId = 0;
  693.    
  694.     // L2JMOD Wedding
  695.     private boolean _married = false;
  696.     private int _coupleId = 0;
  697.     private boolean _marryrequest = false;
  698.     private int _requesterId = 0;
  699.    
  700.     // summon friend
  701.     private final SummonRequest _summonRequest = new SummonRequest();
  702.    
  703.     // open/close gates
  704.     private final GatesRequest _gatesRequest = new GatesRequest();
  705.    
  706.     /** Task for Herbs */
  707.     private class HerbTask implements Runnable
  708.     {
  709.         private final String _process;
  710.         private final int _itemId;
  711.         private final int _count;
  712.         private final L2Object _reference;
  713.         private final boolean _sendMessage;
  714.        
  715.         HerbTask(String process, int itemId, int count, L2Object reference, boolean sendMessage)
  716.         {
  717.             _process = process;
  718.             _itemId = itemId;
  719.             _count = count;
  720.             _reference = reference;
  721.             _sendMessage = sendMessage;
  722.         }
  723.        
  724.         @Override
  725.         public void run()
  726.         {
  727.             addItem(_process, _itemId, _count, _reference, _sendMessage);
  728.         }
  729.     }
  730.    
  731.     protected class ShortBuffTask implements Runnable
  732.     {
  733.         @Override
  734.         public void run()
  735.         {
  736.             sendPacket(new ShortBuffStatusUpdate(0, 0, 0));
  737.             setShortBuffTaskSkillId(0);
  738.         }
  739.     }
  740.    
  741.     /** Skill casting information (used to queue when several skills are cast in a short time) **/
  742.     public static class SkillDat
  743.     {
  744.         private final L2Skill _skill;
  745.         private final boolean _ctrlPressed;
  746.         private final boolean _shiftPressed;
  747.        
  748.         protected SkillDat(L2Skill skill, boolean ctrlPressed, boolean shiftPressed)
  749.         {
  750.             _skill = skill;
  751.             _ctrlPressed = ctrlPressed;
  752.             _shiftPressed = shiftPressed;
  753.         }
  754.        
  755.         public boolean isCtrlPressed()
  756.         {
  757.             return _ctrlPressed;
  758.         }
  759.        
  760.         public boolean isShiftPressed()
  761.         {
  762.             return _shiftPressed;
  763.         }
  764.        
  765.         public L2Skill getSkill()
  766.         {
  767.             return _skill;
  768.         }
  769.        
  770.         public int getSkillId()
  771.         {
  772.             return (getSkill() != null) ? getSkill().getId() : -1;
  773.         }
  774.     }
  775.    
  776.     protected static class SummonRequest
  777.     {
  778.         private L2PcInstance _target = null;
  779.         private L2Skill _skill = null;
  780.        
  781.         public void setTarget(L2PcInstance destination, L2Skill skill)
  782.         {
  783.             _target = destination;
  784.             _skill = skill;
  785.         }
  786.        
  787.         public L2PcInstance getTarget()
  788.         {
  789.             return _target;
  790.         }
  791.        
  792.         public L2Skill getSkill()
  793.         {
  794.             return _skill;
  795.         }
  796.     }
  797.    
  798.     protected static class GatesRequest
  799.     {
  800.         private L2DoorInstance _target = null;
  801.        
  802.         public void setTarget(L2DoorInstance door)
  803.         {
  804.             _target = door;
  805.         }
  806.        
  807.         public L2DoorInstance getDoor()
  808.         {
  809.             return _target;
  810.         }
  811.     }
  812.    
  813.     public void gatesRequest(L2DoorInstance door)
  814.     {
  815.         _gatesRequest.setTarget(door);
  816.     }
  817.    
  818.     public void gatesAnswer(int answer, int type)
  819.     {
  820.         if (_gatesRequest.getDoor() == null)
  821.             return;
  822.        
  823.         if (answer == 1 && getTarget() == _gatesRequest.getDoor() && type == 1)
  824.             _gatesRequest.getDoor().openMe();
  825.         else if (answer == 1 && getTarget() == _gatesRequest.getDoor() && type == 0)
  826.             _gatesRequest.getDoor().closeMe();
  827.        
  828.         _gatesRequest.setTarget(null);
  829.     }
  830.    
  831.     /**
  832.      * Create a new L2PcInstance and add it in the characters table of the database.<BR>
  833.      * <BR>
  834.      * <B><U> Actions</U> :</B><BR>
  835.      * <BR>
  836.      * <li>Create a new L2PcInstance with an account name</li> <li>Set the name, the Hair Style, the Hair Color and the Face type of the L2PcInstance</li> <li>Add the player in the characters table of the database</li><BR>
  837.      * <BR>
  838.      * @param objectId Identifier of the object to initialized
  839.      * @param template The L2PcTemplate to apply to the L2PcInstance
  840.      * @param accountName The name of the L2PcInstance
  841.      * @param name The name of the L2PcInstance
  842.      * @param hairStyle The hair style Identifier of the L2PcInstance
  843.      * @param hairColor The hair color Identifier of the L2PcInstance
  844.      * @param face The face type Identifier of the L2PcInstance
  845.      * @param sex The sex type Identifier of the L2PcInstance
  846.      * @return The L2PcInstance added to the database or null
  847.      */
  848.     public static L2PcInstance create(int objectId, L2PcTemplate template, String accountName, String name, byte hairStyle, byte hairColor, byte face, boolean sex)
  849.     {
  850.         // Create a new L2PcInstance with an account name
  851.         PcAppearance app = new PcAppearance(face, hairColor, hairStyle, sex);
  852.         L2PcInstance player = new L2PcInstance(objectId, template, accountName, app);
  853.        
  854.         // Set the name of the L2PcInstance
  855.         player.setName(name);
  856.        
  857.         // Set the base class ID to that of the actual class ID.
  858.         player.setBaseClass(player.getClassId());
  859.        
  860.         // Add the player in the characters table of the database
  861.         boolean ok = player.createDb();
  862.        
  863.         if (!ok)
  864.             return null;
  865.        
  866.         return player;
  867.     }
  868.    
  869.     public static L2PcInstance createDummyPlayer(int objectId, String name)
  870.     {
  871.         // Create a new L2PcInstance with an account name
  872.         L2PcInstance player = new L2PcInstance(objectId);
  873.         player.setName(name);
  874.        
  875.         return player;
  876.     }
  877.    
  878.     public String getAccountName()
  879.     {
  880.         if (getClient() == null)
  881.             return getAccountNamePlayer();
  882.        
  883.         return getClient().getAccountName();
  884.     }
  885.    
  886.     public String getAccountNamePlayer()
  887.     {
  888.         return _accountName;
  889.     }
  890.    
  891.     public Map<Integer, String> getAccountChars()
  892.     {
  893.         return _chars;
  894.     }
  895.    
  896.     public int getRelation(L2PcInstance target)
  897.     {
  898.         int result = 0;
  899.        
  900.         // karma and pvp may not be required
  901.         if (getPvpFlag() != 0)
  902.             result |= RelationChanged.RELATION_PVP_FLAG;
  903.         if (getKarma() > 0)
  904.             result |= RelationChanged.RELATION_HAS_KARMA;
  905.        
  906.         if (isClanLeader())
  907.             result |= RelationChanged.RELATION_LEADER;
  908.        
  909.         if (getSiegeState() != 0)
  910.         {
  911.             result |= RelationChanged.RELATION_INSIEGE;
  912.             if (getSiegeState() != target.getSiegeState())
  913.                 result |= RelationChanged.RELATION_ENEMY;
  914.             else
  915.                 result |= RelationChanged.RELATION_ALLY;
  916.             if (getSiegeState() == 1)
  917.                 result |= RelationChanged.RELATION_ATTACKER;
  918.         }
  919.        
  920.         if (getClan() != null && target.getClan() != null)
  921.         {
  922.             if (target.getPledgeType() != L2Clan.SUBUNIT_ACADEMY && getPledgeType() != L2Clan.SUBUNIT_ACADEMY && target.getClan().isAtWarWith(getClan().getClanId()))
  923.             {
  924.                 result |= RelationChanged.RELATION_1SIDED_WAR;
  925.                 if (getClan().isAtWarWith(target.getClan().getClanId()))
  926.                     result |= RelationChanged.RELATION_MUTUAL_WAR;
  927.             }
  928.         }
  929.         return result;
  930.     }
  931.    
  932.     private void initPcStatusUpdateValues()
  933.     {
  934.         _cpUpdateInterval = getMaxCp() / 352.0;
  935.         _cpUpdateIncCheck = getMaxCp();
  936.         _cpUpdateDecCheck = getMaxCp() - _cpUpdateInterval;
  937.         _mpUpdateInterval = getMaxMp() / 352.0;
  938.         _mpUpdateIncCheck = getMaxMp();
  939.         _mpUpdateDecCheck = getMaxMp() - _mpUpdateInterval;
  940.     }
  941.    
  942.     /**
  943.      * Constructor of L2PcInstance (use L2Character constructor).<BR>
  944.      * <BR>
  945.      * <B><U> Actions</U> :</B><BR>
  946.      * <BR>
  947.      * <li>Call the L2Character constructor to create an empty _skills slot and copy basic Calculator set to this L2PcInstance</li> <li>Set the name of the L2PcInstance</li><BR>
  948.      * <BR>
  949.      * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method SET the level of the L2PcInstance to 1</B></FONT><BR>
  950.      * <BR>
  951.      * @param objectId Identifier of the object to initialized
  952.      * @param template The L2PcTemplate to apply to the L2PcInstance
  953.      * @param accountName The name of the account including this L2PcInstance
  954.      * @param app The PcAppearance of the L2PcInstance
  955.      */
  956.     private L2PcInstance(int objectId, L2PcTemplate template, String accountName, PcAppearance app)
  957.     {
  958.         super(objectId, template);
  959.         super.initCharStatusUpdateValues();
  960.         initPcStatusUpdateValues();
  961.        
  962.         _accountName = accountName;
  963.         _appearance = app;
  964.        
  965.         // Create an AI
  966.         _ai = new L2PlayerAI(new AIAccessor());
  967.        
  968.         // Create a L2Radar object
  969.         _radar = new L2Radar(this);
  970.        
  971.         // Retrieve from the database all items of this L2PcInstance and add them to _inventory
  972.         getInventory().restore();
  973.         getWarehouse();
  974.         getFreight();
  975.     }
  976.    
  977.     private L2PcInstance(int objectId)
  978.     {
  979.         super(objectId, null);
  980.         super.initCharStatusUpdateValues();
  981.         initPcStatusUpdateValues();
  982.     }
  983.    
  984.     @Override
  985.     public void addFuncsToNewCharacter()
  986.     {
  987.         // Add L2Character functionalities.
  988.         super.addFuncsToNewCharacter();
  989.        
  990.         addStatFunc(FuncMaxCpAdd.getInstance());
  991.         addStatFunc(FuncMaxCpMul.getInstance());
  992.         addStatFunc(FuncMaxHpAdd.getInstance());
  993.         addStatFunc(FuncMaxMpAdd.getInstance());
  994.        
  995.         addStatFunc(FuncBowAtkRange.getInstance());
  996.        
  997.         addStatFunc(FuncHennaSTR.getInstance());
  998.         addStatFunc(FuncHennaDEX.getInstance());
  999.         addStatFunc(FuncHennaINT.getInstance());
  1000.         addStatFunc(FuncHennaMEN.getInstance());
  1001.         addStatFunc(FuncHennaCON.getInstance());
  1002.         addStatFunc(FuncHennaWIT.getInstance());
  1003.     }
  1004.    
  1005.     @Override
  1006.     public void initKnownList()
  1007.     {
  1008.         setKnownList(new PcKnownList(this));
  1009.     }
  1010.    
  1011.     @Override
  1012.     public final PcKnownList getKnownList()
  1013.     {
  1014.         return (PcKnownList) super.getKnownList();
  1015.     }
  1016.    
  1017.     @Override
  1018.     public void initCharStat()
  1019.     {
  1020.         setStat(new PcStat(this));
  1021.     }
  1022.    
  1023.     @Override
  1024.     public final PcStat getStat()
  1025.     {
  1026.         return (PcStat) super.getStat();
  1027.     }
  1028.    
  1029.     @Override
  1030.     public void initCharStatus()
  1031.     {
  1032.         setStatus(new PcStatus(this));
  1033.     }
  1034.    
  1035.     @Override
  1036.     public final PcStatus getStatus()
  1037.     {
  1038.         return (PcStatus) super.getStatus();
  1039.     }
  1040.    
  1041.     @Override
  1042.     public void initPosition()
  1043.     {
  1044.         setObjectPosition(new PcPosition(this));
  1045.     }
  1046.    
  1047.     @Override
  1048.     public PcPosition getPosition()
  1049.     {
  1050.         return (PcPosition) super.getPosition();
  1051.     }
  1052.    
  1053.     public final PcAppearance getAppearance()
  1054.     {
  1055.         return _appearance;
  1056.     }
  1057.    
  1058.     /**
  1059.      * @return the base L2PcTemplate link to the L2PcInstance.
  1060.      */
  1061.     public final L2PcTemplate getBaseTemplate()
  1062.     {
  1063.         return CharTemplateTable.getInstance().getTemplate(_baseClass);
  1064.     }
  1065.    
  1066.     /** Return the L2PcTemplate link to the L2PcInstance. */
  1067.     @Override
  1068.     public final L2PcTemplate getTemplate()
  1069.     {
  1070.         return (L2PcTemplate) super.getTemplate();
  1071.     }
  1072.    
  1073.     public void setTemplate(ClassId newclass)
  1074.     {
  1075.         super.setTemplate(CharTemplateTable.getInstance().getTemplate(newclass));
  1076.     }
  1077.    
  1078.     /**
  1079.      * Return the AI of the L2PcInstance (create it if necessary).
  1080.      */
  1081.     @Override
  1082.     public L2CharacterAI getAI()
  1083.     {
  1084.         if (_ai == null)
  1085.         {
  1086.             synchronized (this)
  1087.             {
  1088.                 if (_ai == null)
  1089.                     _ai = new L2PlayerAI(new AIAccessor());
  1090.             }
  1091.         }
  1092.        
  1093.         return _ai;
  1094.     }
  1095.    
  1096.     /** Return the Level of the L2PcInstance. */
  1097.     @Override
  1098.     public final int getLevel()
  1099.     {
  1100.         return getStat().getLevel();
  1101.     }
  1102.    
  1103.     /**
  1104.      * A newbie is a player reaching level 6. He isn't considered newbie at lvl 25.<br>
  1105.      * Since IL newbie isn't anymore the first character of an account reaching that state, but any.
  1106.      * @return True if newbie.
  1107.      */
  1108.     public boolean isNewbie()
  1109.     {
  1110.         return getClassId().level() <= 1 && getLevel() >= 6 && getLevel() <= 25;
  1111.     }
  1112.    
  1113.     public void setBaseClass(int baseClass)
  1114.     {
  1115.         _baseClass = baseClass;
  1116.     }
  1117.    
  1118.     public void setBaseClass(ClassId classId)
  1119.     {
  1120.         _baseClass = classId.ordinal();
  1121.     }
  1122.    
  1123.     public boolean isInStoreMode()
  1124.     {
  1125.         return _privateStore > STORE_PRIVATE_NONE;
  1126.     }
  1127.    
  1128.     public boolean isInCraftMode()
  1129.     {
  1130.         return _inCraftMode;
  1131.     }
  1132.    
  1133.     public void isInCraftMode(boolean b)
  1134.     {
  1135.         _inCraftMode = b;
  1136.     }
  1137.    
  1138.     /**
  1139.      * Manage Logout Task
  1140.      */
  1141.     public void logout()
  1142.     {
  1143.         logout(true);
  1144.     }
  1145.    
  1146.     /**
  1147.      * Manage Logout Task
  1148.      * @param closeClient
  1149.      */
  1150.     public void logout(boolean closeClient)
  1151.     {
  1152.         try
  1153.         {
  1154.             closeNetConnection(closeClient);
  1155.         }
  1156.         catch (Exception e)
  1157.         {
  1158.             _log.log(Level.WARNING, "Exception on logout(): " + e.getMessage(), e);
  1159.         }
  1160.     }
  1161.    
  1162.     /**
  1163.      * @return a table containing all Common L2RecipeList of the L2PcInstance.
  1164.      */
  1165.     public L2RecipeList[] getCommonRecipeBook()
  1166.     {
  1167.         return _commonRecipeBook.values().toArray(new L2RecipeList[_commonRecipeBook.values().size()]);
  1168.     }
  1169.    
  1170.     /**
  1171.      * @return a table containing all Dwarf L2RecipeList of the L2PcInstance.
  1172.      */
  1173.     public L2RecipeList[] getDwarvenRecipeBook()
  1174.     {
  1175.         return _dwarvenRecipeBook.values().toArray(new L2RecipeList[_dwarvenRecipeBook.values().size()]);
  1176.     }
  1177.    
  1178.     /**
  1179.      * Add a new L2RecipList to the table _commonrecipebook containing all L2RecipeList of the L2PcInstance.
  1180.      * @param recipe The L2RecipeList to add to the _recipebook
  1181.      */
  1182.     public void registerCommonRecipeList(L2RecipeList recipe)
  1183.     {
  1184.         _commonRecipeBook.put(recipe.getId(), recipe);
  1185.     }
  1186.    
  1187.     /**
  1188.      * Add a new L2RecipList to the table _recipebook containing all L2RecipeList of the L2PcInstance.
  1189.      * @param recipe The L2RecipeList to add to the _recipebook
  1190.      */
  1191.     public void registerDwarvenRecipeList(L2RecipeList recipe)
  1192.     {
  1193.         _dwarvenRecipeBook.put(recipe.getId(), recipe);
  1194.     }
  1195.    
  1196.     /**
  1197.      * @param recipeId The Identifier of the L2RecipeList to check in the player's recipe books
  1198.      * @return <b>TRUE</b> if player has the recipe on Common or Dwarven Recipe book else returns <b>FALSE</b>
  1199.      */
  1200.     public boolean hasRecipeList(int recipeId)
  1201.     {
  1202.         if (_dwarvenRecipeBook.containsKey(recipeId))
  1203.             return true;
  1204.        
  1205.         if (_commonRecipeBook.containsKey(recipeId))
  1206.             return true;
  1207.        
  1208.         return false;
  1209.     }
  1210.    
  1211.     /**
  1212.      * Tries to remove a L2RecipList from the table _DwarvenRecipeBook or from table _CommonRecipeBook, those table contain all L2RecipeList of the L2PcInstance.
  1213.      * @param recipeId The Identifier of the L2RecipeList to remove from the _recipebook.
  1214.      */
  1215.     public void unregisterRecipeList(int recipeId)
  1216.     {
  1217.         if (_dwarvenRecipeBook.containsKey(recipeId))
  1218.             _dwarvenRecipeBook.remove(recipeId);
  1219.         else if (_commonRecipeBook.containsKey(recipeId))
  1220.             _commonRecipeBook.remove(recipeId);
  1221.         else
  1222.             _log.warning("Attempted to remove unknown RecipeList: " + recipeId);
  1223.        
  1224.         for (L2ShortCut sc : getAllShortCuts())
  1225.         {
  1226.             if (sc != null && sc.getId() == recipeId && sc.getType() == L2ShortCut.TYPE_RECIPE)
  1227.                 deleteShortCut(sc.getSlot(), sc.getPage());
  1228.         }
  1229.     }
  1230.    
  1231.     /**
  1232.      * @return the Id for the last talked quest NPC.
  1233.      */
  1234.     public int getLastQuestNpcObject()
  1235.     {
  1236.         return _questNpcObject;
  1237.     }
  1238.    
  1239.     public void setLastQuestNpcObject(int npcId)
  1240.     {
  1241.         _questNpcObject = npcId;
  1242.     }
  1243.    
  1244.     /**
  1245.      * @param name The name of the quest.
  1246.      * @return The QuestState object corresponding to the quest name.
  1247.      */
  1248.     public QuestState getQuestState(String name)
  1249.     {
  1250.         for (QuestState qs : _quests)
  1251.         {
  1252.             if (name.equals(qs.getQuest().getName()))
  1253.                 return qs;
  1254.         }
  1255.         return null;
  1256.     }
  1257.    
  1258.     /**
  1259.      * Add a QuestState to the table _quest containing all quests began by the L2PcInstance.
  1260.      * @param qs The QuestState to add to _quest.
  1261.      */
  1262.     public void setQuestState(QuestState qs)
  1263.     {
  1264.         _quests.add(qs);
  1265.     }
  1266.    
  1267.     /**
  1268.      * Remove a QuestState from the table _quest containing all quests began by the L2PcInstance.
  1269.      * @param qs : The QuestState to be removed from _quest.
  1270.      */
  1271.     public void delQuestState(QuestState qs)
  1272.     {
  1273.         _quests.remove(qs);
  1274.     }
  1275.    
  1276.     /**
  1277.      * @param completed : If true, include completed quests to the list.
  1278.      * @return list of started and eventually completed quests of the player.
  1279.      */
  1280.     public List<Quest> getAllQuests(boolean completed)
  1281.     {
  1282.         List<Quest> quests = new ArrayList<>();
  1283.        
  1284.         for (QuestState qs : _quests)
  1285.         {
  1286.             if (qs == null || completed && qs.isCreated() || !completed && !qs.isStarted())
  1287.                 continue;
  1288.            
  1289.             Quest quest = qs.getQuest();
  1290.             if (quest == null || !quest.isRealQuest())
  1291.                 continue;
  1292.            
  1293.             quests.add(quest);
  1294.         }
  1295.        
  1296.         return quests;
  1297.     }
  1298.    
  1299.     public void processQuestEvent(String questName, String event)
  1300.     {
  1301.         Quest quest = QuestManager.getInstance().getQuest(questName);
  1302.         if (quest == null)
  1303.             return;
  1304.        
  1305.         QuestState qs = getQuestState(questName);
  1306.         if (qs == null)
  1307.             return;
  1308.        
  1309.         L2Object object = L2World.getInstance().findObject(getLastQuestNpcObject());
  1310.         if (!(object instanceof L2Npc) || !isInsideRadius(object, L2Npc.INTERACTION_DISTANCE, false, false))
  1311.             return;
  1312.        
  1313.         L2Npc npc = (L2Npc) object;
  1314.         List<Quest> quests = npc.getTemplate().getEventQuests(QuestEventType.ON_TALK);
  1315.         if (quests != null)
  1316.         {
  1317.             for (Quest onTalk : quests)
  1318.             {
  1319.                 if (onTalk == null || !onTalk.equals(quest))
  1320.                     continue;
  1321.                
  1322.                 quest.notifyEvent(event, npc, this);
  1323.                 break;
  1324.             }
  1325.         }
  1326.     }
  1327.    
  1328.     /**
  1329.      * Add QuestState instance that is to be notified of L2PcInstance's death.
  1330.      * @param qs The QuestState that subscribe to this event
  1331.      */
  1332.     public void addNotifyQuestOfDeath(QuestState qs)
  1333.     {
  1334.         if (qs == null)
  1335.             return;
  1336.        
  1337.         if (!_notifyQuestOfDeathList.contains(qs))
  1338.             _notifyQuestOfDeathList.add(qs);
  1339.     }
  1340.    
  1341.     /**
  1342.      * Remove QuestState instance that is to be notified of L2PcInstance's death.
  1343.      * @param qs The QuestState that subscribe to this event
  1344.      */
  1345.     public void removeNotifyQuestOfDeath(QuestState qs)
  1346.     {
  1347.         if (qs == null)
  1348.             return;
  1349.        
  1350.         _notifyQuestOfDeathList.remove(qs);
  1351.     }
  1352.    
  1353.     /**
  1354.      * @return A list of QuestStates which registered for notify of death of this L2PcInstance.
  1355.      */
  1356.     public final List<QuestState> getNotifyQuestOfDeath()
  1357.     {
  1358.         return _notifyQuestOfDeathList;
  1359.     }
  1360.    
  1361.     /**
  1362.      * @return A table containing all L2ShortCut of the L2PcInstance.
  1363.      */
  1364.     public L2ShortCut[] getAllShortCuts()
  1365.     {
  1366.         return _shortCuts.getAllShortCuts();
  1367.     }
  1368.    
  1369.     /**
  1370.      * @param slot The slot in wich the shortCuts is equipped
  1371.      * @param page The page of shortCuts containing the slot
  1372.      * @return The L2ShortCut of the L2PcInstance corresponding to the position (page-slot).
  1373.      */
  1374.     public L2ShortCut getShortCut(int slot, int page)
  1375.     {
  1376.         return _shortCuts.getShortCut(slot, page);
  1377.     }
  1378.    
  1379.     /**
  1380.      * Add a L2shortCut to the L2PcInstance _shortCuts
  1381.      * @param shortcut The shortcut to add.
  1382.      */
  1383.     public void registerShortCut(L2ShortCut shortcut)
  1384.     {
  1385.         _shortCuts.registerShortCut(shortcut);
  1386.     }
  1387.    
  1388.     /**
  1389.      * Delete the L2ShortCut corresponding to the position (page-slot) from the L2PcInstance _shortCuts.
  1390.      * @param slot
  1391.      * @param page
  1392.      */
  1393.     public void deleteShortCut(int slot, int page)
  1394.     {
  1395.         _shortCuts.deleteShortCut(slot, page);
  1396.     }
  1397.    
  1398.     /**
  1399.      * Add a L2Macro to the L2PcInstance _macroses.
  1400.      * @param macro The Macro object to add.
  1401.      */
  1402.     public void registerMacro(L2Macro macro)
  1403.     {
  1404.         _macroses.registerMacro(macro);
  1405.     }
  1406.    
  1407.     /**
  1408.      * Delete the L2Macro corresponding to the Identifier from the L2PcInstance _macroses.
  1409.      * @param id
  1410.      */
  1411.     public void deleteMacro(int id)
  1412.     {
  1413.         _macroses.deleteMacro(id);
  1414.     }
  1415.    
  1416.     /**
  1417.      * @return all L2Macro of the L2PcInstance.
  1418.      */
  1419.     public MacroList getMacroses()
  1420.     {
  1421.         return _macroses;
  1422.     }
  1423.    
  1424.     /**
  1425.      * Set the siege state of the L2PcInstance.
  1426.      * @param siegeState 1 = attacker, 2 = defender, 0 = not involved
  1427.      */
  1428.     public void setSiegeState(byte siegeState)
  1429.     {
  1430.         _siegeState = siegeState;
  1431.     }
  1432.    
  1433.     /**
  1434.      * @return the siege state of the L2PcInstance.
  1435.      */
  1436.     public byte getSiegeState()
  1437.     {
  1438.         return _siegeState;
  1439.     }
  1440.    
  1441.     /**
  1442.      * Set the PvP Flag of the L2PcInstance.
  1443.      * @param pvpFlag 0 or 1.
  1444.      */
  1445.     public void setPvpFlag(int pvpFlag)
  1446.     {
  1447.         _pvpFlag = (byte) pvpFlag;
  1448.     }
  1449.    
  1450.     @Override
  1451.     public byte getPvpFlag()
  1452.     {
  1453.         return _pvpFlag;
  1454.     }
  1455.    
  1456.     public void updatePvPFlag(int value)
  1457.     {
  1458.         if (getPvpFlag() == value)
  1459.             return;
  1460.        
  1461.         setPvpFlag(value);
  1462.         sendPacket(new UserInfo(this));
  1463.        
  1464.         if (getPet() != null)
  1465.             sendPacket(new RelationChanged(getPet(), getRelation(this), false));
  1466.        
  1467.         broadcastRelationsChanges();
  1468.     }
  1469.    
  1470.     @Override
  1471.     public void revalidateZone(boolean force)
  1472.     {
  1473.         // Cannot validate if not in a world region (happens during teleport)
  1474.         if (getWorldRegion() == null)
  1475.             return;
  1476.        
  1477.         // This function is called very often from movement code
  1478.         if (force)
  1479.             _zoneValidateCounter = 4;
  1480.         else
  1481.         {
  1482.             _zoneValidateCounter--;
  1483.             if (_zoneValidateCounter >= 0)
  1484.                 return;
  1485.            
  1486.             _zoneValidateCounter = 4;
  1487.         }
  1488.        
  1489.         getWorldRegion().revalidateZones(this);
  1490.        
  1491.         if (Config.ALLOW_WATER)
  1492.             checkWaterState();
  1493.        
  1494.         if (isInsideZone(ZoneId.SIEGE))
  1495.         {
  1496.             if (_lastCompassZone == ExSetCompassZoneCode.SIEGEWARZONE2)
  1497.                 return;
  1498.            
  1499.             _lastCompassZone = ExSetCompassZoneCode.SIEGEWARZONE2;
  1500.             sendPacket(new ExSetCompassZoneCode(ExSetCompassZoneCode.SIEGEWARZONE2));
  1501.         }
  1502.         else if (isInsideZone(ZoneId.PVP))
  1503.         {
  1504.             if (_lastCompassZone == ExSetCompassZoneCode.PVPZONE)
  1505.                 return;
  1506.            
  1507.             _lastCompassZone = ExSetCompassZoneCode.PVPZONE;
  1508.             sendPacket(new ExSetCompassZoneCode(ExSetCompassZoneCode.PVPZONE));
  1509.         }
  1510.         else if (isIn7sDungeon())
  1511.         {
  1512.             if (_lastCompassZone == ExSetCompassZoneCode.SEVENSIGNSZONE)
  1513.                 return;
  1514.            
  1515.             _lastCompassZone = ExSetCompassZoneCode.SEVENSIGNSZONE;
  1516.             sendPacket(new ExSetCompassZoneCode(ExSetCompassZoneCode.SEVENSIGNSZONE));
  1517.         }
  1518.         else if (isInsideZone(ZoneId.PEACE))
  1519.         {
  1520.             if (_lastCompassZone == ExSetCompassZoneCode.PEACEZONE)
  1521.                 return;
  1522.            
  1523.             _lastCompassZone = ExSetCompassZoneCode.PEACEZONE;
  1524.             sendPacket(new ExSetCompassZoneCode(ExSetCompassZoneCode.PEACEZONE));
  1525.         }
  1526.         else
  1527.         {
  1528.             if (_lastCompassZone == ExSetCompassZoneCode.GENERALZONE)
  1529.                 return;
  1530.            
  1531.             if (_lastCompassZone == ExSetCompassZoneCode.SIEGEWARZONE2)
  1532.                 updatePvPStatus();
  1533.            
  1534.             _lastCompassZone = ExSetCompassZoneCode.GENERALZONE;
  1535.             sendPacket(new ExSetCompassZoneCode(ExSetCompassZoneCode.GENERALZONE));
  1536.         }
  1537.     }
  1538.    
  1539.     /**
  1540.      * @return True if the L2PcInstance can Craft Dwarven Recipes.
  1541.      */
  1542.     public boolean hasDwarvenCraft()
  1543.     {
  1544.         return getSkillLevel(L2Skill.SKILL_CREATE_DWARVEN) >= 1;
  1545.     }
  1546.    
  1547.     public int getDwarvenCraft()
  1548.     {
  1549.         return getSkillLevel(L2Skill.SKILL_CREATE_DWARVEN);
  1550.     }
  1551.    
  1552.     /**
  1553.      * @return True if the L2PcInstance can Craft Dwarven Recipes.
  1554.      */
  1555.     public boolean hasCommonCraft()
  1556.     {
  1557.         return getSkillLevel(L2Skill.SKILL_CREATE_COMMON) >= 1;
  1558.     }
  1559.    
  1560.     public int getCommonCraft()
  1561.     {
  1562.         return getSkillLevel(L2Skill.SKILL_CREATE_COMMON);
  1563.     }
  1564.    
  1565.     /**
  1566.      * @return the PK counter of the L2PcInstance.
  1567.      */
  1568.     public int getPkKills()
  1569.     {
  1570.         return _pkKills;
  1571.     }
  1572.    
  1573.     /**
  1574.      * Set the PK counter of the L2PcInstance.
  1575.      * @param pkKills A number.
  1576.      */
  1577.     public void setPkKills(int pkKills)
  1578.     {
  1579.         _pkKills = pkKills;
  1580.     }
  1581.    
  1582.     /**
  1583.      * @return The _deleteTimer of the L2PcInstance.
  1584.      */
  1585.     public long getDeleteTimer()
  1586.     {
  1587.         return _deleteTimer;
  1588.     }
  1589.    
  1590.     /**
  1591.      * Set the _deleteTimer of the L2PcInstance.
  1592.      * @param deleteTimer Time in ms.
  1593.      */
  1594.     public void setDeleteTimer(long deleteTimer)
  1595.     {
  1596.         _deleteTimer = deleteTimer;
  1597.     }
  1598.    
  1599.     /**
  1600.      * @return The current weight of the L2PcInstance.
  1601.      */
  1602.     public int getCurrentLoad()
  1603.     {
  1604.         return _inventory.getTotalWeight();
  1605.     }
  1606.    
  1607.     /**
  1608.      * @return The date of last update of recomPoints.
  1609.      */
  1610.     public long getLastRecomUpdate()
  1611.     {
  1612.         return _lastRecomUpdate;
  1613.     }
  1614.    
  1615.     public void setLastRecomUpdate(long date)
  1616.     {
  1617.         _lastRecomUpdate = date;
  1618.     }
  1619.    
  1620.     /**
  1621.      * @return The number of recommandation obtained by the L2PcInstance.
  1622.      */
  1623.     public int getRecomHave()
  1624.     {
  1625.         return _recomHave;
  1626.     }
  1627.    
  1628.     /**
  1629.      * Increment the number of recommandation obtained by the L2PcInstance (Max : 255).
  1630.      */
  1631.     protected void incRecomHave()
  1632.     {
  1633.         if (_recomHave < 255)
  1634.             _recomHave++;
  1635.     }
  1636.    
  1637.     /**
  1638.      * Set the number of recommandations obtained by the L2PcInstance (Max : 255).
  1639.      * @param value Number of recommandations obtained.
  1640.      */
  1641.     public void setRecomHave(int value)
  1642.     {
  1643.         if (value > 255)
  1644.             _recomHave = 255;
  1645.         else if (value < 0)
  1646.             _recomHave = 0;
  1647.         else
  1648.             _recomHave = value;
  1649.     }
  1650.    
  1651.     /**
  1652.      * @return The number of recommandation that the L2PcInstance can give.
  1653.      */
  1654.     public int getRecomLeft()
  1655.     {
  1656.         return _recomLeft;
  1657.     }
  1658.    
  1659.     /**
  1660.      * Increment the number of recommandation that the L2PcInstance can give.
  1661.      */
  1662.     protected void decRecomLeft()
  1663.     {
  1664.         if (_recomLeft > 0)
  1665.             _recomLeft--;
  1666.     }
  1667.    
  1668.     public void giveRecom(L2PcInstance target)
  1669.     {
  1670.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1671.         {
  1672.             PreparedStatement statement = con.prepareStatement(ADD_CHAR_RECOM);
  1673.             statement.setInt(1, getObjectId());
  1674.             statement.setInt(2, target.getObjectId());
  1675.             statement.execute();
  1676.             statement.close();
  1677.         }
  1678.         catch (Exception e)
  1679.         {
  1680.             _log.warning("Could not update char recommendations: " + e);
  1681.         }
  1682.        
  1683.         target.incRecomHave();
  1684.         decRecomLeft();
  1685.         _recomChars.add(target.getObjectId());
  1686.     }
  1687.    
  1688.     public boolean canRecom(L2PcInstance target)
  1689.     {
  1690.         return !_recomChars.contains(target.getObjectId());
  1691.     }
  1692.    
  1693.     /**
  1694.      * Set the exp of the L2PcInstance before a death
  1695.      * @param exp
  1696.      */
  1697.     public void setExpBeforeDeath(long exp)
  1698.     {
  1699.         _expBeforeDeath = exp;
  1700.     }
  1701.    
  1702.     public long getExpBeforeDeath()
  1703.     {
  1704.         return _expBeforeDeath;
  1705.     }
  1706.    
  1707.     /**
  1708.      * Return the Karma of the L2PcInstance.
  1709.      */
  1710.     @Override
  1711.     public int getKarma()
  1712.     {
  1713.         return _karma;
  1714.     }
  1715.    
  1716.     /**
  1717.      * Set the Karma of the L2PcInstance and send StatusUpdate (broadcast).
  1718.      * @param karma A value.
  1719.      */
  1720.     public void setKarma(int karma)
  1721.     {
  1722.         if (karma < 0)
  1723.             karma = 0;
  1724.        
  1725.         if (_karma > 0 && karma == 0)
  1726.         {
  1727.             sendPacket(new UserInfo(this));
  1728.             broadcastRelationsChanges();
  1729.         }
  1730.        
  1731.         // send message with new karma value
  1732.         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOUR_KARMA_HAS_BEEN_CHANGED_TO_S1).addNumber(karma));
  1733.        
  1734.         _karma = karma;
  1735.         broadcastKarma();
  1736.     }
  1737.    
  1738.     /**
  1739.      * Weight Limit = (CON Modifier*69000)*Skills
  1740.      * @return The max weight that the L2PcInstance can load.
  1741.      */
  1742.     public int getMaxLoad()
  1743.     {
  1744.         int con = getCON();
  1745.         if (con < 1)
  1746.             return 31000;
  1747.        
  1748.         if (con > 59)
  1749.             return 176000;
  1750.        
  1751.         double baseLoad = Math.pow(1.029993928, con) * 30495.627366;
  1752.         return (int) calcStat(Stats.MAX_LOAD, baseLoad * Config.ALT_WEIGHT_LIMIT, this, null);
  1753.     }
  1754.    
  1755.     public int getExpertiseArmorPenalty()
  1756.     {
  1757.         return _expertiseArmorPenalty;
  1758.     }
  1759.    
  1760.     public boolean getExpertiseWeaponPenalty()
  1761.     {
  1762.         return _expertiseWeaponPenalty;
  1763.     }
  1764.    
  1765.     public int getWeightPenalty()
  1766.     {
  1767.         return _curWeightPenalty;
  1768.     }
  1769.    
  1770.     /**
  1771.      * Update the overloaded status of the L2PcInstance.
  1772.      */
  1773.     public void refreshOverloaded()
  1774.     {
  1775.         int maxLoad = getMaxLoad();
  1776.         if (maxLoad > 0)
  1777.         {
  1778.             int weightproc = getCurrentLoad() * 1000 / maxLoad;
  1779.             int newWeightPenalty;
  1780.            
  1781.             if (weightproc < 500)
  1782.                 newWeightPenalty = 0;
  1783.             else if (weightproc < 666)
  1784.                 newWeightPenalty = 1;
  1785.             else if (weightproc < 800)
  1786.                 newWeightPenalty = 2;
  1787.             else if (weightproc < 1000)
  1788.                 newWeightPenalty = 3;
  1789.             else
  1790.                 newWeightPenalty = 4;
  1791.            
  1792.             if (_curWeightPenalty != newWeightPenalty)
  1793.             {
  1794.                 _curWeightPenalty = newWeightPenalty;
  1795.                
  1796.                 if (newWeightPenalty > 0)
  1797.                 {
  1798.                     super.addSkill(SkillTable.getInstance().getInfo(4270, newWeightPenalty));
  1799.                     setIsOverloaded(getCurrentLoad() > maxLoad);
  1800.                 }
  1801.                 else
  1802.                 {
  1803.                     super.removeSkill(getKnownSkill(4270));
  1804.                     setIsOverloaded(false);
  1805.                 }
  1806.                
  1807.                 sendPacket(new UserInfo(this));
  1808.                 sendPacket(new EtcStatusUpdate(this));
  1809.                 broadcastCharInfo();
  1810.             }
  1811.         }
  1812.     }
  1813.    
  1814.     /**
  1815.      * Refresh expertise level ; weapon got one rank, when armor got 4 ranks.<br>
  1816.      */
  1817.     public void refreshExpertisePenalty()
  1818.     {
  1819.         int armorPenalty = 0;
  1820.         boolean weaponPenalty = false;
  1821.        
  1822.         for (L2ItemInstance item : getInventory().getItems())
  1823.         {
  1824.             if (item != null && item.isEquipped() && item.getItemType() != L2EtcItemType.ARROW && item.getItem().getCrystalType() > getExpertiseIndex())
  1825.             {
  1826.                 if (item.isWeapon())
  1827.                     weaponPenalty = true;
  1828.                 else
  1829.                     armorPenalty += (item.getItem().getBodyPart() == L2Item.SLOT_FULL_ARMOR) ? 2 : 1;
  1830.             }
  1831.         }
  1832.        
  1833.         armorPenalty = Math.min(armorPenalty, 4);
  1834.        
  1835.         // Found a different state than previous ; update it.
  1836.         if (_expertiseWeaponPenalty != weaponPenalty || _expertiseArmorPenalty != armorPenalty)
  1837.         {
  1838.             _expertiseWeaponPenalty = weaponPenalty;
  1839.             _expertiseArmorPenalty = armorPenalty;
  1840.            
  1841.             // Passive skill "Grade Penalty" is either granted or dropped.
  1842.             if (_expertiseWeaponPenalty || _expertiseArmorPenalty > 0)
  1843.                 super.addSkill(SkillTable.getInstance().getInfo(4267, 1));
  1844.             else
  1845.                 super.removeSkill(getKnownSkill(4267));
  1846.            
  1847.             sendSkillList();
  1848.             sendPacket(new EtcStatusUpdate(this));
  1849.         }
  1850.     }
  1851.    
  1852.     /**
  1853.      * Equip or unequip the item.
  1854.      * <UL>
  1855.      * <LI>If item is equipped, shots are applied if automation is on.</LI>
  1856.      * <LI>If item is unequipped, shots are discharged.</LI>
  1857.      * </UL>
  1858.      * @param item The item to charge/discharge.
  1859.      * @param abortAttack If true, the current attack will be aborted in order to equip the item.
  1860.      */
  1861.     public void useEquippableItem(L2ItemInstance item, boolean abortAttack)
  1862.     {
  1863.         L2ItemInstance[] items = null;
  1864.         final boolean isEquipped = item.isEquipped();
  1865.         final int oldInvLimit = getInventoryLimit();
  1866.         SystemMessage sm = null;
  1867.        
  1868.         if (item.getItem() instanceof L2Weapon)
  1869.             item.unChargeAllShots();
  1870.        
  1871.         if (isEquipped)
  1872.         {
  1873.             if (item.getEnchantLevel() > 0)
  1874.                 sm = SystemMessage.getSystemMessage(SystemMessageId.EQUIPMENT_S1_S2_REMOVED).addNumber(item.getEnchantLevel()).addItemName(item);
  1875.             else
  1876.                 sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISARMED).addItemName(item);
  1877.            
  1878.             sendPacket(sm);
  1879.            
  1880.             int slot = getInventory().getSlotFromItem(item);
  1881.             items = getInventory().unEquipItemInBodySlotAndRecord(slot);
  1882.         }
  1883.         else
  1884.         {
  1885.             items = getInventory().equipItemAndRecord(item);
  1886.            
  1887.             if (item.isEquipped())
  1888.             {
  1889.                 if (item.getEnchantLevel() > 0)
  1890.                     sm = SystemMessage.getSystemMessage(SystemMessageId.S1_S2_EQUIPPED).addNumber(item.getEnchantLevel()).addItemName(item);
  1891.                 else
  1892.                     sm = SystemMessage.getSystemMessage(SystemMessageId.S1_EQUIPPED).addItemName(item);
  1893.                
  1894.                 sendPacket(sm);
  1895.                
  1896.                 if ((item.getItem().getBodyPart() & L2Item.SLOT_ALLWEAPON) != 0)
  1897.                     rechargeShots(true, true);
  1898.             }
  1899.             else
  1900.                 sendPacket(SystemMessageId.CANNOT_EQUIP_ITEM_DUE_TO_BAD_CONDITION);
  1901.         }
  1902.         refreshExpertisePenalty();
  1903.         broadcastUserInfo();
  1904.        
  1905.         InventoryUpdate iu = new InventoryUpdate();
  1906.         iu.addItems(Arrays.asList(items));
  1907.         sendPacket(iu);
  1908.        
  1909.         if (abortAttack)
  1910.             abortAttack();
  1911.        
  1912.         if (getInventoryLimit() != oldInvLimit)
  1913.             sendPacket(new ExStorageMaxCount(this));
  1914.     }
  1915.    
  1916.     /**
  1917.      * @return PvP Kills of the L2PcInstance (number of player killed during a PvP).
  1918.      */
  1919.     public int getPvpKills()
  1920.     {
  1921.         return _pvpKills;
  1922.     }
  1923.    
  1924.     /**
  1925.      * Set PvP Kills of the L2PcInstance (number of player killed during a PvP).
  1926.      * @param pvpKills A value.
  1927.      */
  1928.     public void setPvpKills(int pvpKills)
  1929.     {
  1930.         _pvpKills = pvpKills;
  1931.     }
  1932.    
  1933.     /**
  1934.      * @return The ClassId object of the L2PcInstance contained in L2PcTemplate.
  1935.      */
  1936.     public ClassId getClassId()
  1937.     {
  1938.         return getTemplate().classId;
  1939.     }
  1940.    
  1941.     /**
  1942.      * Set the template of the L2PcInstance.
  1943.      * @param Id The Identifier of the L2PcTemplate to set to the L2PcInstance
  1944.      */
  1945.     public void setClassId(int Id)
  1946.     {
  1947.         if (!_subclassLock.tryLock())
  1948.             return;
  1949.        
  1950.         try
  1951.         {
  1952.             if (getLvlJoinedAcademy() != 0 && _clan != null && PlayerClass.values()[Id].getLevel() == ClassLevel.Third)
  1953.             {
  1954.                 if (getLvlJoinedAcademy() <= 16)
  1955.                     _clan.addReputationScore(400);
  1956.                 else if (getLvlJoinedAcademy() >= 39)
  1957.                     _clan.addReputationScore(170);
  1958.                 else
  1959.                     _clan.addReputationScore((400 - (getLvlJoinedAcademy() - 16) * 10));
  1960.                
  1961.                 setLvlJoinedAcademy(0);
  1962.                
  1963.                 // Oust pledge member from the academy, because he has finished his 2nd class transfer.
  1964.                 _clan.broadcastToOnlineMembers(new PledgeShowMemberListDelete(getName()), SystemMessage.getSystemMessage(SystemMessageId.CLAN_MEMBER_S1_EXPELLED).addString(getName()));
  1965.                 _clan.removeClanMember(getObjectId(), 0);
  1966.                 sendPacket(SystemMessageId.ACADEMY_MEMBERSHIP_TERMINATED);
  1967.                
  1968.                 // receive graduation gift : academy circlet
  1969.                 addItem("Gift", 8181, 1, this, true);
  1970.             }
  1971.            
  1972.             if (isSubClassActive())
  1973.                 getSubClasses().get(_classIndex).setClassId(Id);
  1974.            
  1975.             broadcastPacket(new MagicSkillUse(this, this, 5103, 1, 1000, 0));
  1976.             setClassTemplate(Id);
  1977.            
  1978.             // Update class icon in party and clan
  1979.             if (isInParty())
  1980.                 getParty().broadcastToPartyMembers(new PartySmallWindowUpdate(this));
  1981.            
  1982.             if (getClan() != null)
  1983.                 getClan().broadcastToOnlineMembers(new PledgeShowMemberListUpdate(this));
  1984.            
  1985.             if (Config.AUTO_LEARN_SKILLS)
  1986.                 rewardSkills();
  1987.         }
  1988.         finally
  1989.         {
  1990.             _subclassLock.unlock();
  1991.         }
  1992.     }
  1993.    
  1994.     /**
  1995.      * @return the Experience of the L2PcInstance.
  1996.      */
  1997.     public long getExp()
  1998.     {
  1999.         return getStat().getExp();
  2000.     }
  2001.    
  2002.     public void setActiveEnchantItem(L2ItemInstance scroll)
  2003.     {
  2004.         _activeEnchantItem = scroll;
  2005.     }
  2006.    
  2007.     public L2ItemInstance getActiveEnchantItem()
  2008.     {
  2009.         return _activeEnchantItem;
  2010.     }
  2011.    
  2012.     /**
  2013.      * Set the fists weapon of the L2PcInstance (used when no weapon is equipped).
  2014.      * @param weaponItem The fists L2Weapon to set to the L2PcInstance
  2015.      */
  2016.     public void setFistsWeaponItem(L2Weapon weaponItem)
  2017.     {
  2018.         _fistsWeaponItem = weaponItem;
  2019.     }
  2020.    
  2021.     /**
  2022.      * @return The fists weapon of the L2PcInstance (used when no weapon is equipped).
  2023.      */
  2024.     public L2Weapon getFistsWeaponItem()
  2025.     {
  2026.         return _fistsWeaponItem;
  2027.     }
  2028.    
  2029.     /**
  2030.      * @param classId The classId to test.
  2031.      * @return The fists weapon of the L2PcInstance Class (used when no weapon is equipped).
  2032.      */
  2033.     public static L2Weapon findFistsWeaponItem(int classId)
  2034.     {
  2035.         L2Weapon weaponItem = null;
  2036.         if ((classId >= 0x00) && (classId <= 0x09))
  2037.         {
  2038.             // human fighter fists
  2039.             L2Item temp = ItemTable.getInstance().getTemplate(246);
  2040.             weaponItem = (L2Weapon) temp;
  2041.         }
  2042.         else if ((classId >= 0x0a) && (classId <= 0x11))
  2043.         {
  2044.             // human mage fists
  2045.             L2Item temp = ItemTable.getInstance().getTemplate(251);
  2046.             weaponItem = (L2Weapon) temp;
  2047.         }
  2048.         else if ((classId >= 0x12) && (classId <= 0x18))
  2049.         {
  2050.             // elven fighter fists
  2051.             L2Item temp = ItemTable.getInstance().getTemplate(244);
  2052.             weaponItem = (L2Weapon) temp;
  2053.         }
  2054.         else if ((classId >= 0x19) && (classId <= 0x1e))
  2055.         {
  2056.             // elven mage fists
  2057.             L2Item temp = ItemTable.getInstance().getTemplate(249);
  2058.             weaponItem = (L2Weapon) temp;
  2059.         }
  2060.         else if ((classId >= 0x1f) && (classId <= 0x25))
  2061.         {
  2062.             // dark elven fighter fists
  2063.             L2Item temp = ItemTable.getInstance().getTemplate(245);
  2064.             weaponItem = (L2Weapon) temp;
  2065.         }
  2066.         else if ((classId >= 0x26) && (classId <= 0x2b))
  2067.         {
  2068.             // dark elven mage fists
  2069.             L2Item temp = ItemTable.getInstance().getTemplate(250);
  2070.             weaponItem = (L2Weapon) temp;
  2071.         }
  2072.         else if ((classId >= 0x2c) && (classId <= 0x30))
  2073.         {
  2074.             // orc fighter fists
  2075.             L2Item temp = ItemTable.getInstance().getTemplate(248);
  2076.             weaponItem = (L2Weapon) temp;
  2077.         }
  2078.         else if ((classId >= 0x31) && (classId <= 0x34))
  2079.         {
  2080.             // orc mage fists
  2081.             L2Item temp = ItemTable.getInstance().getTemplate(252);
  2082.             weaponItem = (L2Weapon) temp;
  2083.         }
  2084.         else if ((classId >= 0x35) && (classId <= 0x39))
  2085.         {
  2086.             // dwarven fists
  2087.             L2Item temp = ItemTable.getInstance().getTemplate(247);
  2088.             weaponItem = (L2Weapon) temp;
  2089.         }
  2090.        
  2091.         return weaponItem;
  2092.     }
  2093.    
  2094.     /**
  2095.      * This method is kinda polymorph :<BR>
  2096.      * <BR>
  2097.      * <li>it gives proper Expertise, Dwarven && Common Craft skill level ;</li> <li>it controls the Lucky skill (remove at lvl 10) ;</li> <li>it finally sends the skill list.</li>
  2098.      */
  2099.     public void rewardSkills()
  2100.     {
  2101.         // Get the Level of the L2PcInstance
  2102.         int lvl = getLevel();
  2103.        
  2104.         // Remove the Lucky skill once reached lvl 10.
  2105.         if (getSkillLevel(L2Skill.SKILL_LUCKY) > 0 && lvl >= 10)
  2106.             removeSkill(FrequentSkill.LUCKY.getSkill());
  2107.        
  2108.         // Calculate the current higher Expertise of the L2PcInstance
  2109.         for (int i = 0; i < EXPERTISE_LEVELS.length; i++)
  2110.         {
  2111.             if (lvl >= EXPERTISE_LEVELS[i])
  2112.                 setExpertiseIndex(i);
  2113.         }
  2114.        
  2115.         // Add the Expertise skill corresponding to its Expertise level
  2116.         if (getExpertiseIndex() > 0)
  2117.         {
  2118.             L2Skill skill = SkillTable.getInstance().getInfo(239, getExpertiseIndex());
  2119.             addSkill(skill, true);
  2120.         }
  2121.        
  2122.         // Active skill dwarven craft
  2123.         if (getSkillLevel(1321) < 1 && getClassId().equalsOrChildOf(ClassId.dwarvenFighter))
  2124.         {
  2125.             L2Skill skill = FrequentSkill.DWARVEN_CRAFT.getSkill();
  2126.             addSkill(skill, true);
  2127.         }
  2128.        
  2129.         // Active skill common craft
  2130.         if (getSkillLevel(1322) < 1)
  2131.         {
  2132.             L2Skill skill = FrequentSkill.COMMON_CRAFT.getSkill();
  2133.             addSkill(skill, true);
  2134.         }
  2135.        
  2136.         for (int i = 0; i < COMMON_CRAFT_LEVELS.length; i++)
  2137.         {
  2138.             if (lvl >= COMMON_CRAFT_LEVELS[i] && getSkillLevel(1320) < (i + 1))
  2139.             {
  2140.                 L2Skill skill = SkillTable.getInstance().getInfo(1320, (i + 1));
  2141.                 addSkill(skill, true);
  2142.             }
  2143.         }
  2144.        
  2145.         // Auto-Learn skills if activated
  2146.         if (Config.AUTO_LEARN_SKILLS)
  2147.             giveAvailableSkills();
  2148.        
  2149.         sendSkillList();
  2150.     }
  2151.    
  2152.     /**
  2153.      * Regive all skills which aren't saved to database, like Noble, Hero, Clan Skills.<br>
  2154.      * <b>Do not call this on enterworld or char load.</b>.
  2155.      */
  2156.     private void regiveTemporarySkills()
  2157.     {
  2158.         // Add noble skills if noble.
  2159.         if (isNoble())
  2160.             setNoble(true, false);
  2161.        
  2162.         // Add Hero skills if hero.
  2163.         if (isHero())
  2164.             setHero(true);
  2165.        
  2166.         // Add clan skills.
  2167.         if (getClan() != null && getClan().getReputationScore() >= 0)
  2168.         {
  2169.             for (L2Skill sk : getClan().getClanSkills())
  2170.             {
  2171.                 if (sk.getMinPledgeClass() <= getPledgeClass())
  2172.                     addSkill(sk, false);
  2173.             }
  2174.         }
  2175.        
  2176.         // Reload passive skills from armors / jewels / weapons
  2177.         getInventory().reloadEquippedItems();
  2178.        
  2179.         // Add Death Penalty Buff Level
  2180.         restoreDeathPenaltyBuffLevel();
  2181.     }
  2182.    
  2183.     /**
  2184.      * Give all available skills to the player.
  2185.      * @return The number of given skills.
  2186.      */
  2187.     public int giveAvailableSkills()
  2188.     {
  2189.         int result = 0;
  2190.         for (L2SkillLearn sl : SkillTreeTable.getInstance().getAllAvailableSkills(this, getClassId()))
  2191.         {
  2192.             addSkill(SkillTable.getInstance().getInfo(sl.getId(), sl.getLevel()), true);
  2193.             result++;
  2194.         }
  2195.         return result;
  2196.     }
  2197.    
  2198.     /**
  2199.      * @return The Race object of the L2PcInstance.
  2200.      */
  2201.     public Race getRace()
  2202.     {
  2203.         if (!isSubClassActive())
  2204.             return getTemplate().race;
  2205.        
  2206.         L2PcTemplate charTemp = CharTemplateTable.getInstance().getTemplate(_baseClass);
  2207.         return charTemp.race;
  2208.     }
  2209.    
  2210.     public L2Radar getRadar()
  2211.     {
  2212.         return _radar;
  2213.     }
  2214.    
  2215.     /**
  2216.      * @return the SP amount of the L2PcInstance.
  2217.      */
  2218.     public int getSp()
  2219.     {
  2220.         return getStat().getSp();
  2221.     }
  2222.    
  2223.     /**
  2224.      * @param castleId The castle to check.
  2225.      * @return True if this L2PcInstance is a clan leader in ownership of the passed castle.
  2226.      */
  2227.     public boolean isCastleLord(int castleId)
  2228.     {
  2229.         L2Clan clan = getClan();
  2230.        
  2231.         // player has clan and is the clan leader, check the castle info
  2232.         if ((clan != null) && (clan.getLeader().getPlayerInstance() == this))
  2233.         {
  2234.             // if the clan has a castle and it is actually the queried castle, return true
  2235.             Castle castle = CastleManager.getInstance().getCastleByOwner(clan);
  2236.             if ((castle != null) && (castle == CastleManager.getInstance().getCastleById(castleId)))
  2237.                 return true;
  2238.         }
  2239.        
  2240.         return false;
  2241.     }
  2242.    
  2243.     /**
  2244.      * @return The Clan Identifier of the L2PcInstance.
  2245.      */
  2246.     public int getClanId()
  2247.     {
  2248.         return _clanId;
  2249.     }
  2250.    
  2251.     /**
  2252.      * @return The Clan Crest Identifier of the L2PcInstance or 0.
  2253.      */
  2254.     public int getClanCrestId()
  2255.     {
  2256.         if (_clan != null)
  2257.             return _clan.getCrestId();
  2258.        
  2259.         return 0;
  2260.     }
  2261.    
  2262.     /**
  2263.      * @return The Clan CrestLarge Identifier or 0
  2264.      */
  2265.     public int getClanCrestLargeId()
  2266.     {
  2267.         if (_clan != null)
  2268.             return _clan.getCrestLargeId();
  2269.        
  2270.         return 0;
  2271.     }
  2272.    
  2273.     public long getClanJoinExpiryTime()
  2274.     {
  2275.         return _clanJoinExpiryTime;
  2276.     }
  2277.    
  2278.     public void setClanJoinExpiryTime(long time)
  2279.     {
  2280.         _clanJoinExpiryTime = time;
  2281.     }
  2282.    
  2283.     public long getClanCreateExpiryTime()
  2284.     {
  2285.         return _clanCreateExpiryTime;
  2286.     }
  2287.    
  2288.     public void setClanCreateExpiryTime(long time)
  2289.     {
  2290.         _clanCreateExpiryTime = time;
  2291.     }
  2292.    
  2293.     public void setOnlineTime(long time)
  2294.     {
  2295.         _onlineTime = time;
  2296.         _onlineBeginTime = System.currentTimeMillis();
  2297.     }
  2298.    
  2299.     /**
  2300.      * Return the PcInventory Inventory of the L2PcInstance contained in _inventory.
  2301.      */
  2302.     @Override
  2303.     public PcInventory getInventory()
  2304.     {
  2305.         return _inventory;
  2306.     }
  2307.    
  2308.     /**
  2309.      * Delete a ShortCut of the L2PcInstance _shortCuts.
  2310.      * @param objectId The shortcut id.
  2311.      */
  2312.     public void removeItemFromShortCut(int objectId)
  2313.     {
  2314.         _shortCuts.deleteShortCutByObjectId(objectId);
  2315.     }
  2316.    
  2317.     /**
  2318.      * @return True if the L2PcInstance is sitting.
  2319.      */
  2320.     public boolean isSitting()
  2321.     {
  2322.         return _waitTypeSitting;
  2323.     }
  2324.    
  2325.     /**
  2326.      * Set _waitTypeSitting to given value.
  2327.      * @param state A boolean.
  2328.      */
  2329.     public void setIsSitting(boolean state)
  2330.     {
  2331.         _waitTypeSitting = state;
  2332.     }
  2333.    
  2334.     /**
  2335.      * Sit down the L2PcInstance, set the AI Intention to REST and send a Server->Client ChangeWaitType packet (broadcast)
  2336.      */
  2337.     public void sitDown()
  2338.     {
  2339.         sitDown(true);
  2340.     }
  2341.    
  2342.     public void sitDown(boolean checkCast)
  2343.     {
  2344.         if (checkCast && isCastingNow())
  2345.             return;
  2346.        
  2347.         if (!_waitTypeSitting && !isAttackingDisabled() && !isOutOfControl() && !isImmobilized())
  2348.         {
  2349.             breakAttack();
  2350.             setIsSitting(true);
  2351.             broadcastPacket(new ChangeWaitType(this, ChangeWaitType.WT_SITTING));
  2352.            
  2353.             // Schedule a sit down task to wait for the animation to finish
  2354.             getAI().setIntention(CtrlIntention.REST);
  2355.             ThreadPoolManager.getInstance().scheduleGeneral(new SitDownTask(), 2500);
  2356.             setIsParalyzed(true);
  2357.         }
  2358.     }
  2359.    
  2360.     /**
  2361.      * Sit down Task
  2362.      */
  2363.     protected class SitDownTask implements Runnable
  2364.     {
  2365.         @Override
  2366.         public void run()
  2367.         {
  2368.             setIsParalyzed(false);
  2369.         }
  2370.     }
  2371.    
  2372.     /**
  2373.      * Stand up Task
  2374.      */
  2375.     protected class StandUpTask implements Runnable
  2376.     {
  2377.         @Override
  2378.         public void run()
  2379.         {
  2380.             setIsSitting(false);
  2381.             getAI().setIntention(CtrlIntention.IDLE);
  2382.         }
  2383.     }
  2384.    
  2385.     /**
  2386.      * Stand up the L2PcInstance, set the AI Intention to IDLE and send a Server->Client ChangeWaitType packet (broadcast)
  2387.      */
  2388.     public void standUp()
  2389.     {
  2390.         if (_waitTypeSitting && !isInStoreMode() && !isAlikeDead())
  2391.         {
  2392.             if (_effects.isAffected(L2EffectFlag.RELAXING))
  2393.                 stopEffects(L2EffectType.RELAXING);
  2394.            
  2395.             broadcastPacket(new ChangeWaitType(this, ChangeWaitType.WT_STANDING));
  2396.             // Schedule a stand up task to wait for the animation to finish
  2397.             ThreadPoolManager.getInstance().scheduleGeneral(new StandUpTask(), 2500);
  2398.         }
  2399.     }
  2400.    
  2401.     /**
  2402.      * Stands up and close any opened shop window, if any.
  2403.      */
  2404.     public void forceStandUp()
  2405.     {
  2406.         // Cancels any shop types.
  2407.         if (isInStoreMode())
  2408.         {
  2409.             setPrivateStoreType(STORE_PRIVATE_NONE);
  2410.             broadcastUserInfo();
  2411.         }
  2412.        
  2413.         // Stand up.
  2414.         if (isSitting())
  2415.             standUp();
  2416.     }
  2417.    
  2418.     /**
  2419.      * @return The PcWarehouse object of the L2PcInstance.
  2420.      */
  2421.     public PcWarehouse getWarehouse()
  2422.     {
  2423.         if (_warehouse == null)
  2424.         {
  2425.             _warehouse = new PcWarehouse(this);
  2426.             _warehouse.restore();
  2427.         }
  2428.         return _warehouse;
  2429.     }
  2430.    
  2431.     /**
  2432.      * Free memory used by Warehouse
  2433.      */
  2434.     public void clearWarehouse()
  2435.     {
  2436.         if (_warehouse != null)
  2437.             _warehouse.deleteMe();
  2438.        
  2439.         _warehouse = null;
  2440.     }
  2441.    
  2442.     /**
  2443.      * @return The PcFreight object of the L2PcInstance.
  2444.      */
  2445.     public PcFreight getFreight()
  2446.     {
  2447.         if (_freight == null)
  2448.         {
  2449.             _freight = new PcFreight(this);
  2450.             _freight.restore();
  2451.         }
  2452.         return _freight;
  2453.     }
  2454.    
  2455.     /**
  2456.      * Free memory used by Freight
  2457.      */
  2458.     public void clearFreight()
  2459.     {
  2460.         if (_freight != null)
  2461.             _freight.deleteMe();
  2462.        
  2463.         _freight = null;
  2464.     }
  2465.    
  2466.     /**
  2467.      * @param objectId The id of the owner.
  2468.      * @return deposited PcFreight object for the objectId or create new if not existing.
  2469.      */
  2470.     public PcFreight getDepositedFreight(int objectId)
  2471.     {
  2472.         for (PcFreight freight : _depositedFreight)
  2473.         {
  2474.             if (freight != null && freight.getOwnerId() == objectId)
  2475.                 return freight;
  2476.         }
  2477.        
  2478.         PcFreight freight = new PcFreight(null);
  2479.         freight.doQuickRestore(objectId);
  2480.         _depositedFreight.add(freight);
  2481.         return freight;
  2482.     }
  2483.    
  2484.     /**
  2485.      * Clear memory used by deposited freight
  2486.      */
  2487.     public void clearDepositedFreight()
  2488.     {
  2489.         for (PcFreight freight : _depositedFreight)
  2490.         {
  2491.             if (freight != null)
  2492.                 freight.deleteMe();
  2493.         }
  2494.         _depositedFreight.clear();
  2495.     }
  2496.    
  2497.     /**
  2498.      * @return The Identifier of the L2PcInstance.
  2499.      */
  2500.     public int getCharId()
  2501.     {
  2502.         return _charId;
  2503.     }
  2504.    
  2505.     /**
  2506.      * Set the Identifier of the L2PcInstance.
  2507.      * @param charId The CharId.
  2508.      */
  2509.     public void setCharId(int charId)
  2510.     {
  2511.         _charId = charId;
  2512.     }
  2513.    
  2514.     /**
  2515.      * @return The Adena amount of the L2PcInstance.
  2516.      */
  2517.     public int getAdena()
  2518.     {
  2519.         return _inventory.getAdena();
  2520.     }
  2521.    
  2522.     /**
  2523.      * @return The Ancient Adena amount of the L2PcInstance.
  2524.      */
  2525.     public int getAncientAdena()
  2526.     {
  2527.         return _inventory.getAncientAdena();
  2528.     }
  2529.    
  2530.     /**
  2531.      * Add adena to Inventory of the L2PcInstance and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2532.      * @param process String Identifier of process triggering this action
  2533.      * @param count int Quantity of adena to be added
  2534.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2535.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2536.      */
  2537.     public void addAdena(String process, int count, L2Object reference, boolean sendMessage)
  2538.     {
  2539.         if (sendMessage)
  2540.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.EARNED_S1_ADENA).addNumber(count));
  2541.        
  2542.         if (count > 0)
  2543.         {
  2544.             _inventory.addAdena(process, count, this, reference);
  2545.            
  2546.             InventoryUpdate iu = new InventoryUpdate();
  2547.             iu.addItem(_inventory.getAdenaInstance());
  2548.             sendPacket(iu);
  2549.         }
  2550.     }
  2551.    
  2552.     /**
  2553.      * Reduce adena in Inventory of the L2PcInstance and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2554.      * @param process String Identifier of process triggering this action
  2555.      * @param count int Quantity of adena to be reduced
  2556.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2557.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2558.      * @return boolean informing if the action was successfull
  2559.      */
  2560.     public boolean reduceAdena(String process, int count, L2Object reference, boolean sendMessage)
  2561.     {
  2562.         if (count > getAdena())
  2563.         {
  2564.             if (sendMessage)
  2565.                 sendPacket(SystemMessageId.YOU_NOT_ENOUGH_ADENA);
  2566.            
  2567.             return false;
  2568.         }
  2569.        
  2570.         if (count > 0)
  2571.         {
  2572.             L2ItemInstance adenaItem = _inventory.getAdenaInstance();
  2573.             if (!_inventory.reduceAdena(process, count, this, reference))
  2574.                 return false;
  2575.            
  2576.             // Send update packet
  2577.             InventoryUpdate iu = new InventoryUpdate();
  2578.             iu.addItem(adenaItem);
  2579.             sendPacket(iu);
  2580.            
  2581.             if (sendMessage)
  2582.                 sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED_ADENA).addNumber(count));
  2583.         }
  2584.         return true;
  2585.     }
  2586.    
  2587.     /**
  2588.      * Add ancient adena to Inventory of the L2PcInstance and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2589.      * @param process String Identifier of process triggering this action
  2590.      * @param count int Quantity of ancient adena to be added
  2591.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2592.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2593.      */
  2594.     public void addAncientAdena(String process, int count, L2Object reference, boolean sendMessage)
  2595.     {
  2596.         if (sendMessage)
  2597.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.EARNED_S2_S1_S).addItemName(PcInventory.ANCIENT_ADENA_ID).addNumber(count));
  2598.        
  2599.         if (count > 0)
  2600.         {
  2601.             _inventory.addAncientAdena(process, count, this, reference);
  2602.            
  2603.             InventoryUpdate iu = new InventoryUpdate();
  2604.             iu.addItem(_inventory.getAncientAdenaInstance());
  2605.             sendPacket(iu);
  2606.         }
  2607.     }
  2608.    
  2609.     /**
  2610.      * Reduce ancient adena in Inventory of the L2PcInstance and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2611.      * @param process String Identifier of process triggering this action
  2612.      * @param count int Quantity of ancient adena to be reduced
  2613.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2614.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2615.      * @return boolean informing if the action was successfull
  2616.      */
  2617.     public boolean reduceAncientAdena(String process, int count, L2Object reference, boolean sendMessage)
  2618.     {
  2619.         if (count > getAncientAdena())
  2620.         {
  2621.             if (sendMessage)
  2622.                 sendPacket(SystemMessageId.YOU_NOT_ENOUGH_ADENA);
  2623.            
  2624.             return false;
  2625.         }
  2626.        
  2627.         if (count > 0)
  2628.         {
  2629.             L2ItemInstance ancientAdenaItem = _inventory.getAncientAdenaInstance();
  2630.             if (!_inventory.reduceAncientAdena(process, count, this, reference))
  2631.                 return false;
  2632.            
  2633.             InventoryUpdate iu = new InventoryUpdate();
  2634.             iu.addItem(ancientAdenaItem);
  2635.             sendPacket(iu);
  2636.            
  2637.             if (sendMessage)
  2638.             {
  2639.                 if (count > 1)
  2640.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED).addItemName(PcInventory.ANCIENT_ADENA_ID).addItemNumber(count));
  2641.                 else
  2642.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED).addItemName(PcInventory.ANCIENT_ADENA_ID));
  2643.             }
  2644.         }
  2645.         return true;
  2646.     }
  2647.    
  2648.     /**
  2649.      * Adds item to inventory and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2650.      * @param process String Identifier of process triggering this action
  2651.      * @param item L2ItemInstance to be added
  2652.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2653.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2654.      */
  2655.     public void addItem(String process, L2ItemInstance item, L2Object reference, boolean sendMessage)
  2656.     {
  2657.         if (item.getCount() > 0)
  2658.         {
  2659.             // Sends message to client if requested
  2660.             if (sendMessage)
  2661.             {
  2662.                 if (item.getCount() > 1)
  2663.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_PICKED_UP_S2_S1).addItemName(item).addNumber(item.getCount()));
  2664.                 else if (item.getEnchantLevel() > 0)
  2665.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_PICKED_UP_A_S1_S2).addNumber(item.getEnchantLevel()).addItemName(item));
  2666.                 else
  2667.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_PICKED_UP_S1).addItemName(item));
  2668.             }
  2669.            
  2670.             // Add the item to inventory
  2671.             L2ItemInstance newitem = _inventory.addItem(process, item, this, reference);
  2672.            
  2673.             // Send inventory update packet
  2674.             InventoryUpdate playerIU = new InventoryUpdate();
  2675.             playerIU.addItem(newitem);
  2676.             sendPacket(playerIU);
  2677.            
  2678.             // Update current load as well
  2679.             StatusUpdate su = new StatusUpdate(this);
  2680.             su.addAttribute(StatusUpdate.CUR_LOAD, getCurrentLoad());
  2681.             sendPacket(su);
  2682.            
  2683.             // If over capacity, drop the item
  2684.             if (!_inventory.validateCapacity(0, item.isQuestItem()) && newitem.isDropable() && (!newitem.isStackable() || newitem.getLastChange() != L2ItemInstance.MODIFIED))
  2685.                 dropItem("InvDrop", newitem, null, true, true);
  2686.             // Cursed Weapon
  2687.             else if (CursedWeaponsManager.getInstance().isCursed(newitem.getItemId()))
  2688.                 CursedWeaponsManager.getInstance().activate(this, newitem);
  2689.             // If you pickup arrows and a bow is equipped, try to equip them if no arrows is currently equipped.
  2690.             else if (item.getItem().getItemType() == L2EtcItemType.ARROW && getAttackType() == L2WeaponType.BOW && getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND) == null)
  2691.                 checkAndEquipArrows();
  2692.         }
  2693.     }
  2694.    
  2695.     /**
  2696.      * Adds item to Inventory and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2697.      * @param process String Identifier of process triggering this action
  2698.      * @param itemId int Item Identifier of the item to be added
  2699.      * @param count int Quantity of items to be added
  2700.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2701.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2702.      * @return The created L2ItemInstance.
  2703.      */
  2704.     public L2ItemInstance addItem(String process, int itemId, int count, L2Object reference, boolean sendMessage)
  2705.     {
  2706.         if (count > 0)
  2707.         {
  2708.             // Retrieve the template of the item.
  2709.             final L2Item item = ItemTable.getInstance().getTemplate(itemId);
  2710.             if (item == null)
  2711.             {
  2712.                 _log.log(Level.SEVERE, "Item id " + itemId + "doesn't exist, so it can't be added.");
  2713.                 return null;
  2714.             }
  2715.            
  2716.             // Sends message to client if requested.
  2717.             if (sendMessage && ((!isCastingNow() && item.getItemType() == L2EtcItemType.HERB) || item.getItemType() != L2EtcItemType.HERB))
  2718.             {
  2719.                 if (count > 1)
  2720.                 {
  2721.                     if (process.equalsIgnoreCase("Sweep") || process.equalsIgnoreCase("Quest"))
  2722.                         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.EARNED_S2_S1_S).addItemName(itemId).addItemNumber(count));
  2723.                     else
  2724.                         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_PICKED_UP_S2_S1).addItemName(itemId).addItemNumber(count));
  2725.                 }
  2726.                 else
  2727.                 {
  2728.                     if (process.equalsIgnoreCase("Sweep") || process.equalsIgnoreCase("Quest"))
  2729.                         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.EARNED_ITEM_S1).addItemName(itemId));
  2730.                     else
  2731.                         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_PICKED_UP_S1).addItemName(itemId));
  2732.                 }
  2733.             }
  2734.            
  2735.             // If the item is herb type, dont add it to inventory.
  2736.             if (item.getItemType() == L2EtcItemType.HERB)
  2737.             {
  2738.                 if (!isCastingNow())
  2739.                 {
  2740.                     final L2ItemInstance herb = new L2ItemInstance(_charId, itemId);
  2741.                    
  2742.                     final IItemHandler handler = ItemHandler.getInstance().getItemHandler(herb.getEtcItem());
  2743.                     if (handler != null)
  2744.                     {
  2745.                         handler.useItem(this, herb, false);
  2746.                         if (_herbstask >= 100)
  2747.                             _herbstask -= 100;
  2748.                     }
  2749.                 }
  2750.                 else
  2751.                 {
  2752.                     _herbstask += 100;
  2753.                     ThreadPoolManager.getInstance().scheduleAi(new HerbTask(process, itemId, count, reference, sendMessage), _herbstask);
  2754.                 }
  2755.             }
  2756.             else
  2757.             {
  2758.                 // Add the item to inventory
  2759.                 final L2ItemInstance createdItem = _inventory.addItem(process, itemId, count, this, reference);
  2760.                
  2761.                 // If over capacity, drop the item
  2762.                 if (!_inventory.validateCapacity(0, item.isQuestItem()) && createdItem.isDropable() && (!createdItem.isStackable() || createdItem.getLastChange() != L2ItemInstance.MODIFIED))
  2763.                     dropItem("InvDrop", createdItem, null, true);
  2764.                 // Cursed Weapon
  2765.                 else if (CursedWeaponsManager.getInstance().isCursed(createdItem.getItemId()))
  2766.                     CursedWeaponsManager.getInstance().activate(this, createdItem);
  2767.                 // If you pickup arrows and a bow is equipped, try to equip them if no arrows is currently equipped.
  2768.                 else if (item.getItemType() == L2EtcItemType.ARROW && getAttackType() == L2WeaponType.BOW && getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND) == null)
  2769.                     checkAndEquipArrows();
  2770.                
  2771.                 return createdItem;
  2772.             }
  2773.         }
  2774.         return null;
  2775.     }
  2776.    
  2777.     /**
  2778.      * Destroy item from inventory and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2779.      * @param process String Identifier of process triggering this action
  2780.      * @param item L2ItemInstance to be destroyed
  2781.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2782.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2783.      * @return boolean informing if the action was successfull
  2784.      */
  2785.     public boolean destroyItem(String process, L2ItemInstance item, L2Object reference, boolean sendMessage)
  2786.     {
  2787.         return this.destroyItem(process, item, item.getCount(), reference, sendMessage);
  2788.     }
  2789.    
  2790.     /**
  2791.      * Destroy item from inventory and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2792.      * @param process String Identifier of process triggering this action
  2793.      * @param item L2ItemInstance to be destroyed
  2794.      * @param count int Quantity of ancient adena to be reduced
  2795.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2796.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2797.      * @return boolean informing if the action was successfull
  2798.      */
  2799.     public boolean destroyItem(String process, L2ItemInstance item, int count, L2Object reference, boolean sendMessage)
  2800.     {
  2801.         item = _inventory.destroyItem(process, item, count, this, reference);
  2802.        
  2803.         if (item == null)
  2804.         {
  2805.             if (sendMessage)
  2806.                 sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  2807.            
  2808.             return false;
  2809.         }
  2810.        
  2811.         // Send inventory update packet
  2812.         InventoryUpdate playerIU = new InventoryUpdate();
  2813.         playerIU.addItem(item);
  2814.         sendPacket(playerIU);
  2815.        
  2816.         // Update current load as well
  2817.         StatusUpdate su = new StatusUpdate(this);
  2818.         su.addAttribute(StatusUpdate.CUR_LOAD, getCurrentLoad());
  2819.         sendPacket(su);
  2820.        
  2821.         // Sends message to client if requested
  2822.         if (sendMessage)
  2823.         {
  2824.             if (count > 1)
  2825.                 sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED).addItemName(item).addItemNumber(count));
  2826.             else
  2827.                 sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED).addItemName(item));
  2828.         }
  2829.         return true;
  2830.     }
  2831.    
  2832.     /**
  2833.      * Destroys item from inventory and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2834.      * @param process String Identifier of process triggering this action
  2835.      * @param objectId int Item Instance identifier of the item to be destroyed
  2836.      * @param count int Quantity of items to be destroyed
  2837.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2838.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2839.      * @return boolean informing if the action was successfull
  2840.      */
  2841.     @Override
  2842.     public boolean destroyItem(String process, int objectId, int count, L2Object reference, boolean sendMessage)
  2843.     {
  2844.         L2ItemInstance item = _inventory.getItemByObjectId(objectId);
  2845.        
  2846.         if (item == null)
  2847.         {
  2848.             if (sendMessage)
  2849.                 sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  2850.            
  2851.             return false;
  2852.         }
  2853.         return this.destroyItem(process, item, count, reference, sendMessage);
  2854.     }
  2855.    
  2856.     /**
  2857.      * Destroys shots from inventory without logging and only occasional saving to database. Sends a Server->Client InventoryUpdate packet to the L2PcInstance.
  2858.      * @param process String Identifier of process triggering this action
  2859.      * @param objectId int Item Instance identifier of the item to be destroyed
  2860.      * @param count int Quantity of items to be destroyed
  2861.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2862.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2863.      * @return boolean informing if the action was successfull
  2864.      */
  2865.     public boolean destroyItemWithoutTrace(String process, int objectId, int count, L2Object reference, boolean sendMessage)
  2866.     {
  2867.         L2ItemInstance item = _inventory.getItemByObjectId(objectId);
  2868.        
  2869.         if (item == null || item.getCount() < count)
  2870.         {
  2871.             if (sendMessage)
  2872.                 sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  2873.            
  2874.             return false;
  2875.         }
  2876.        
  2877.         return this.destroyItem(null, item, count, reference, sendMessage);
  2878.     }
  2879.    
  2880.     /**
  2881.      * Destroy item from inventory by using its <B>itemId</B> and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2882.      * @param process String Identifier of process triggering this action
  2883.      * @param itemId int Item identifier of the item to be destroyed
  2884.      * @param count int Quantity of items to be destroyed
  2885.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2886.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2887.      * @return boolean informing if the action was successfull
  2888.      */
  2889.     @Override
  2890.     public boolean destroyItemByItemId(String process, int itemId, int count, L2Object reference, boolean sendMessage)
  2891.     {
  2892.         if (itemId == 57)
  2893.             return reduceAdena(process, count, reference, sendMessage);
  2894.        
  2895.         L2ItemInstance item = _inventory.getItemByItemId(itemId);
  2896.        
  2897.         if (item == null || item.getCount() < count || _inventory.destroyItemByItemId(process, itemId, count, this, reference) == null)
  2898.         {
  2899.             if (sendMessage)
  2900.                 sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  2901.            
  2902.             return false;
  2903.         }
  2904.        
  2905.         // Send inventory update packet
  2906.         InventoryUpdate playerIU = new InventoryUpdate();
  2907.         playerIU.addItem(item);
  2908.         sendPacket(playerIU);
  2909.        
  2910.         // Update current load as well
  2911.         StatusUpdate su = new StatusUpdate(this);
  2912.         su.addAttribute(StatusUpdate.CUR_LOAD, getCurrentLoad());
  2913.         sendPacket(su);
  2914.        
  2915.         // Sends message to client if requested
  2916.         if (sendMessage)
  2917.         {
  2918.             if (count > 1)
  2919.                 sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED).addItemName(itemId).addItemNumber(count));
  2920.             else
  2921.                 sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED).addItemName(itemId));
  2922.         }
  2923.         return true;
  2924.     }
  2925.    
  2926.     /**
  2927.      * Transfers item to another ItemContainer and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2928.      * @param process String Identifier of process triggering this action
  2929.      * @param objectId int Item Identifier of the item to be transfered
  2930.      * @param count int Quantity of items to be transfered
  2931.      * @param target Inventory the Inventory target.
  2932.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2933.      * @return L2ItemInstance corresponding to the new item or the updated item in inventory
  2934.      */
  2935.     public L2ItemInstance transferItem(String process, int objectId, int count, Inventory target, L2Object reference)
  2936.     {
  2937.         final L2ItemInstance oldItem = checkItemManipulation(objectId, count);
  2938.         if (oldItem == null)
  2939.             return null;
  2940.        
  2941.         final L2ItemInstance newItem = getInventory().transferItem(process, objectId, count, target, this, reference);
  2942.         if (newItem == null)
  2943.             return null;
  2944.        
  2945.         // Send inventory update packet
  2946.         InventoryUpdate playerIU = new InventoryUpdate();
  2947.        
  2948.         if (oldItem.getCount() > 0 && oldItem != newItem)
  2949.             playerIU.addModifiedItem(oldItem);
  2950.         else
  2951.             playerIU.addRemovedItem(oldItem);
  2952.        
  2953.         sendPacket(playerIU);
  2954.        
  2955.         // Update current load as well
  2956.         StatusUpdate playerSU = new StatusUpdate(this);
  2957.         playerSU.addAttribute(StatusUpdate.CUR_LOAD, getCurrentLoad());
  2958.         sendPacket(playerSU);
  2959.        
  2960.         // Send target update packet
  2961.         if (target instanceof PcInventory)
  2962.         {
  2963.             final L2PcInstance targetPlayer = ((PcInventory) target).getOwner();
  2964.            
  2965.             InventoryUpdate playerIU2 = new InventoryUpdate();
  2966.             if (newItem.getCount() > count)
  2967.                 playerIU2.addModifiedItem(newItem);
  2968.             else
  2969.                 playerIU2.addNewItem(newItem);
  2970.             targetPlayer.sendPacket(playerIU2);
  2971.            
  2972.             // Update current load as well
  2973.             playerSU = new StatusUpdate(targetPlayer);
  2974.             playerSU.addAttribute(StatusUpdate.CUR_LOAD, targetPlayer.getCurrentLoad());
  2975.             targetPlayer.sendPacket(playerSU);
  2976.         }
  2977.         else if (target instanceof PetInventory)
  2978.         {
  2979.             PetInventoryUpdate petIU = new PetInventoryUpdate();
  2980.             if (newItem.getCount() > count)
  2981.                 petIU.addModifiedItem(newItem);
  2982.             else
  2983.                 petIU.addNewItem(newItem);
  2984.             ((PetInventory) target).getOwner().getOwner().sendPacket(petIU);
  2985.         }
  2986.         return newItem;
  2987.     }
  2988.    
  2989.     /**
  2990.      * Drop item from inventory and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  2991.      * @param process String Identifier of process triggering this action
  2992.      * @param item L2ItemInstance to be dropped
  2993.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  2994.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  2995.      * @param protectItem whether or not dropped item must be protected temporary against other players
  2996.      * @return boolean informing if the action was successfull
  2997.      */
  2998.     public boolean dropItem(String process, L2ItemInstance item, L2Object reference, boolean sendMessage, boolean protectItem)
  2999.     {
  3000.         item = _inventory.dropItem(process, item, this, reference);
  3001.        
  3002.         if (item == null)
  3003.         {
  3004.             if (sendMessage)
  3005.                 sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  3006.            
  3007.             return false;
  3008.         }
  3009.        
  3010.         item.dropMe(this, getX() + Rnd.get(50) - 25, getY() + Rnd.get(50) - 25, getZ() + 20);
  3011.        
  3012.         if (Config.AUTODESTROY_ITEM_AFTER > 0 && Config.DESTROY_DROPPED_PLAYER_ITEM && !Config.LIST_PROTECTED_ITEMS.contains(item.getItemId()))
  3013.         {
  3014.             if ((item.isEquipable() && Config.DESTROY_EQUIPABLE_PLAYER_ITEM) || !item.isEquipable())
  3015.                 ItemsAutoDestroy.getInstance().addItem(item);
  3016.         }
  3017.        
  3018.         if (Config.DESTROY_DROPPED_PLAYER_ITEM)
  3019.         {
  3020.             if (!item.isEquipable() || (item.isEquipable() && Config.DESTROY_EQUIPABLE_PLAYER_ITEM))
  3021.                 item.setProtected(false);
  3022.             else
  3023.                 item.setProtected(true);
  3024.         }
  3025.         else
  3026.             item.setProtected(true);
  3027.        
  3028.         // retail drop protection
  3029.         if (protectItem)
  3030.             item.getDropProtection().protect(this);
  3031.        
  3032.         // Send inventory update packet
  3033.         InventoryUpdate playerIU = new InventoryUpdate();
  3034.         playerIU.addItem(item);
  3035.         sendPacket(playerIU);
  3036.        
  3037.         // Update current load as well
  3038.         StatusUpdate su = new StatusUpdate(this);
  3039.         su.addAttribute(StatusUpdate.CUR_LOAD, getCurrentLoad());
  3040.         sendPacket(su);
  3041.        
  3042.         // Sends message to client if requested
  3043.         if (sendMessage)
  3044.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_DROPPED_S1).addItemName(item));
  3045.        
  3046.         return true;
  3047.     }
  3048.    
  3049.     public boolean dropItem(String process, L2ItemInstance item, L2Object reference, boolean sendMessage)
  3050.     {
  3051.         return dropItem(process, item, reference, sendMessage, false);
  3052.     }
  3053.    
  3054.     /**
  3055.      * Drop item from inventory by using its <B>objectID</B> and send a Server->Client InventoryUpdate packet to the L2PcInstance.
  3056.      * @param process String Identifier of process triggering this action
  3057.      * @param objectId int Item Instance identifier of the item to be dropped
  3058.      * @param count int Quantity of items to be dropped
  3059.      * @param x int coordinate for drop X
  3060.      * @param y int coordinate for drop Y
  3061.      * @param z int coordinate for drop Z
  3062.      * @param reference L2Object Object referencing current action like NPC selling item or previous item in transformation
  3063.      * @param sendMessage boolean Specifies whether to send message to Client about this action
  3064.      * @param protectItem boolean Activates drop protection on that item if true
  3065.      * @return L2ItemInstance corresponding to the new item or the updated item in inventory
  3066.      */
  3067.     public L2ItemInstance dropItem(String process, int objectId, int count, int x, int y, int z, L2Object reference, boolean sendMessage, boolean protectItem)
  3068.     {
  3069.         L2ItemInstance invitem = _inventory.getItemByObjectId(objectId);
  3070.         L2ItemInstance item = _inventory.dropItem(process, objectId, count, this, reference);
  3071.        
  3072.         if (item == null)
  3073.         {
  3074.             if (sendMessage)
  3075.                 sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  3076.            
  3077.             return null;
  3078.         }
  3079.        
  3080.         item.dropMe(this, x, y, z);
  3081.        
  3082.         if (Config.AUTODESTROY_ITEM_AFTER > 0 && Config.DESTROY_DROPPED_PLAYER_ITEM && !Config.LIST_PROTECTED_ITEMS.contains(item.getItemId()))
  3083.         {
  3084.             if ((item.isEquipable() && Config.DESTROY_EQUIPABLE_PLAYER_ITEM) || !item.isEquipable())
  3085.                 ItemsAutoDestroy.getInstance().addItem(item);
  3086.         }
  3087.        
  3088.         if (Config.DESTROY_DROPPED_PLAYER_ITEM)
  3089.         {
  3090.             if (!item.isEquipable() || (item.isEquipable() && Config.DESTROY_EQUIPABLE_PLAYER_ITEM))
  3091.                 item.setProtected(false);
  3092.             else
  3093.                 item.setProtected(true);
  3094.         }
  3095.         else
  3096.             item.setProtected(true);
  3097.        
  3098.         // retail drop protection
  3099.         if (protectItem)
  3100.             item.getDropProtection().protect(this);
  3101.        
  3102.         // Send inventory update packet
  3103.         InventoryUpdate playerIU = new InventoryUpdate();
  3104.         playerIU.addItem(invitem);
  3105.         sendPacket(playerIU);
  3106.        
  3107.         // Update current load as well
  3108.         StatusUpdate su = new StatusUpdate(this);
  3109.         su.addAttribute(StatusUpdate.CUR_LOAD, getCurrentLoad());
  3110.         sendPacket(su);
  3111.        
  3112.         // Sends message to client if requested
  3113.         if (sendMessage)
  3114.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_DROPPED_S1).addItemName(item));
  3115.        
  3116.         return item;
  3117.     }
  3118.    
  3119.     public L2ItemInstance checkItemManipulation(int objectId, int count)
  3120.     {
  3121.         if (L2World.getInstance().findObject(objectId) == null)
  3122.             return null;
  3123.        
  3124.         final L2ItemInstance item = getInventory().getItemByObjectId(objectId);
  3125.        
  3126.         if (item == null || item.getOwnerId() != getObjectId())
  3127.             return null;
  3128.        
  3129.         if (count < 1 || (count > 1 && !item.isStackable()))
  3130.             return null;
  3131.        
  3132.         if (count > item.getCount())
  3133.             return null;
  3134.        
  3135.         // Pet is summoned and not the item that summoned the pet AND not the buggle from strider you're mounting
  3136.         if (getPet() != null && getPet().getControlItemId() == objectId || getMountObjectID() == objectId)
  3137.             return null;
  3138.        
  3139.         if (getActiveEnchantItem() != null && getActiveEnchantItem().getObjectId() == objectId)
  3140.             return null;
  3141.        
  3142.         // We cannot put a Weapon with Augmention in WH while casting (Possible Exploit)
  3143.         if (item.isAugmented() && (isCastingNow() || isCastingSimultaneouslyNow()))
  3144.             return null;
  3145.        
  3146.         return item;
  3147.     }
  3148.    
  3149.     /**
  3150.      * Set _protectEndTime according settings.
  3151.      * @param protect boolean Drop timer or activate it.
  3152.      */
  3153.     public void setProtection(boolean protect)
  3154.     {
  3155.         if (Config.DEVELOPER && (protect || _protectEndTime > 0))
  3156.             _log.warning(getName() + ": Protection " + (protect ? "ON " + (GameTimeController.getGameTicks() + Config.PLAYER_SPAWN_PROTECTION * GameTimeController.TICKS_PER_SECOND) : "OFF") + " (currently " + GameTimeController.getGameTicks() + ")");
  3157.        
  3158.         _protectEndTime = protect ? GameTimeController.getGameTicks() + Config.PLAYER_SPAWN_PROTECTION * GameTimeController.TICKS_PER_SECOND : 0;
  3159.     }
  3160.    
  3161.     public boolean isSpawnProtected()
  3162.     {
  3163.         return _protectEndTime > GameTimeController.getGameTicks();
  3164.     }
  3165.    
  3166.     /**
  3167.      * Set protection from agro mobs when getting up from fake death, according settings.
  3168.      * @param protect boolean Drop timer or activate it.
  3169.      */
  3170.     public void setRecentFakeDeath(boolean protect)
  3171.     {
  3172.         _recentFakeDeathEndTime = protect ? GameTimeController.getGameTicks() + Config.PLAYER_FAKEDEATH_UP_PROTECTION * GameTimeController.TICKS_PER_SECOND : 0;
  3173.     }
  3174.    
  3175.     public boolean isRecentFakeDeath()
  3176.     {
  3177.         return _recentFakeDeathEndTime > GameTimeController.getGameTicks();
  3178.     }
  3179.    
  3180.     public final boolean isFakeDeath()
  3181.     {
  3182.         return _isFakeDeath;
  3183.     }
  3184.    
  3185.     public final void setIsFakeDeath(boolean value)
  3186.     {
  3187.         _isFakeDeath = value;
  3188.     }
  3189.    
  3190.     @Override
  3191.     public final boolean isAlikeDead()
  3192.     {
  3193.         if (super.isAlikeDead())
  3194.             return true;
  3195.        
  3196.         return isFakeDeath();
  3197.     }
  3198.    
  3199.     /**
  3200.      * @return The client owner of this char.
  3201.      */
  3202.     public L2GameClient getClient()
  3203.     {
  3204.         return _client;
  3205.     }
  3206.    
  3207.     public void setClient(L2GameClient client)
  3208.     {
  3209.         _client = client;
  3210.     }
  3211.    
  3212.     /**
  3213.      * Close the active connection with the client.
  3214.      * @param closeClient
  3215.      */
  3216.     private void closeNetConnection(boolean closeClient)
  3217.     {
  3218.         L2GameClient client = _client;
  3219.         if (client != null)
  3220.         {
  3221.             if (client.isDetached())
  3222.                 client.cleanMe(true);
  3223.             else
  3224.             {
  3225.                 if (!client.getConnection().isClosed())
  3226.                 {
  3227.                     if (closeClient)
  3228.                         client.close(LeaveWorld.STATIC_PACKET);
  3229.                     else
  3230.                         client.close(ServerClose.STATIC_PACKET);
  3231.                 }
  3232.             }
  3233.         }
  3234.     }
  3235.    
  3236.     public Point3D getCurrentSkillWorldPosition()
  3237.     {
  3238.         return _currentSkillWorldPosition;
  3239.     }
  3240.    
  3241.     public void setCurrentSkillWorldPosition(Point3D worldPosition)
  3242.     {
  3243.         _currentSkillWorldPosition = worldPosition;
  3244.     }
  3245.    
  3246.     /**
  3247.      * @see net.sf.l2j.gameserver.model.actor.L2Character#enableSkill(net.sf.l2j.gameserver.model.L2Skill)
  3248.      */
  3249.     @Override
  3250.     public void enableSkill(L2Skill skill)
  3251.     {
  3252.         super.enableSkill(skill);
  3253.         _reuseTimeStamps.remove(skill.getReuseHashCode());
  3254.     }
  3255.    
  3256.     /**
  3257.      * @see net.sf.l2j.gameserver.model.actor.L2Character#checkDoCastConditions(net.sf.l2j.gameserver.model.L2Skill)
  3258.      */
  3259.     @Override
  3260.     protected boolean checkDoCastConditions(L2Skill skill)
  3261.     {
  3262.         if (!super.checkDoCastConditions(skill))
  3263.             return false;
  3264.        
  3265.         if (skill.getSkillType() == L2SkillType.SUMMON)
  3266.         {
  3267.             if (!((L2SkillSummon) skill).isCubic() && (getPet() != null || isMounted()))
  3268.             {
  3269.                 sendPacket(SystemMessageId.SUMMON_ONLY_ONE);
  3270.                 return false;
  3271.             }
  3272.         }
  3273.        
  3274.         // Can't use Hero and resurrect skills during Olympiad
  3275.         if (isInOlympiadMode() && (skill.isHeroSkill() || skill.getSkillType() == L2SkillType.RESURRECT))
  3276.         {
  3277.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.THIS_SKILL_IS_NOT_AVAILABLE_FOR_THE_OLYMPIAD_EVENT));
  3278.             return false;
  3279.         }
  3280.        
  3281.         // Check if the spell uses charges
  3282.         final int charges = getCharges();
  3283.         if (skill.getMaxCharges() == 0 && charges < skill.getNumCharges())
  3284.         {
  3285.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill));
  3286.             return false;
  3287.         }
  3288.        
  3289.         return true;
  3290.     }
  3291.    
  3292.     /**
  3293.      * Manage actions when a player click on this L2PcInstance.<BR>
  3294.      * <BR>
  3295.      * <B><U> Actions on first click on the L2PcInstance (Select it)</U> :</B><BR>
  3296.      * <BR>
  3297.      * <li>Set the target of the player</li> <li>Send MyTargetSelected to the player (display the select window)</li><BR>
  3298.      * <BR>
  3299.      * <B><U> Actions on second click on the L2PcInstance (Follow it/Attack it/Intercat with it)</U> :</B><BR>
  3300.      * <BR>
  3301.      * <li>Send MyTargetSelected to the player (display the select window)</li> <li>If this L2PcInstance has a Private Store, notify the player AI with INTERACT</li> <li>If this L2PcInstance is autoAttackable, notify the player AI with ATTACK</li><BR>
  3302.      * <BR>
  3303.      * <li>If this L2PcInstance is NOT autoAttackable, notify the player AI with FOLLOW</li><BR>
  3304.      * <BR>
  3305.      * <B><U> Example of use </U> :</B><BR>
  3306.      * <BR>
  3307.      * <li>Client packet : Action, AttackRequest</li><BR>
  3308.      * <BR>
  3309.      * @param player The player that start an action on this L2PcInstance
  3310.      */
  3311.     @Override
  3312.     public void onAction(L2PcInstance player)
  3313.     {
  3314.         // Set the target of the player
  3315.         if (player.getTarget() != this)
  3316.             player.setTarget(this);
  3317.         else
  3318.         {
  3319.             // Check if this L2PcInstance has a Private Store
  3320.             if (isInStoreMode())
  3321.             {
  3322.                 player.getAI().setIntention(CtrlIntention.INTERACT, this);
  3323.                 return;
  3324.             }
  3325.            
  3326.             // Check if this L2PcInstance is autoAttackable
  3327.             if (isAutoAttackable(player))
  3328.             {
  3329.                 // Player with lvl < 21 can't attack a cursed weapon holder and a cursed weapon holder can't attack players with lvl < 21
  3330.                 if ((isCursedWeaponEquipped() && player.getLevel() < 21) || (player.isCursedWeaponEquipped() && getLevel() < 21))
  3331.                 {
  3332.                     player.sendPacket(ActionFailed.STATIC_PACKET);
  3333.                     return;
  3334.                 }
  3335.                
  3336.                 if (Config.GEODATA == 0 || GeoData.getInstance().canSeeTarget(player, this))
  3337.                 {
  3338.                     player.getAI().setIntention(CtrlIntention.ATTACK, this);
  3339.                     player.onActionRequest();
  3340.                 }
  3341.             }
  3342.             else
  3343.             {
  3344.                 // avoids to stuck when clicking two or more times
  3345.                 player.sendPacket(ActionFailed.STATIC_PACKET);
  3346.                
  3347.                 if (player != this && (Config.GEODATA == 0 || GeoData.getInstance().canSeeTarget(player, this)))
  3348.                     player.getAI().setIntention(CtrlIntention.FOLLOW, this);
  3349.             }
  3350.         }
  3351.     }
  3352.    
  3353.     /**
  3354.      * @param barPixels
  3355.      * @return true if cp update should be done, false if not
  3356.      */
  3357.     private boolean needCpUpdate(int barPixels)
  3358.     {
  3359.         double currentCp = getCurrentCp();
  3360.        
  3361.         if (currentCp <= 1.0 || getMaxCp() < barPixels)
  3362.             return true;
  3363.        
  3364.         if (currentCp <= _cpUpdateDecCheck || currentCp >= _cpUpdateIncCheck)
  3365.         {
  3366.             if (currentCp == getMaxCp())
  3367.             {
  3368.                 _cpUpdateIncCheck = currentCp + 1;
  3369.                 _cpUpdateDecCheck = currentCp - _cpUpdateInterval;
  3370.             }
  3371.             else
  3372.             {
  3373.                 double doubleMulti = currentCp / _cpUpdateInterval;
  3374.                 int intMulti = (int) doubleMulti;
  3375.                
  3376.                 _cpUpdateDecCheck = _cpUpdateInterval * (doubleMulti < intMulti ? intMulti-- : intMulti);
  3377.                 _cpUpdateIncCheck = _cpUpdateDecCheck + _cpUpdateInterval;
  3378.             }
  3379.            
  3380.             return true;
  3381.         }
  3382.        
  3383.         return false;
  3384.     }
  3385.    
  3386.     /**
  3387.      * @param barPixels
  3388.      * @return true if mp update should be done, false if not
  3389.      */
  3390.     private boolean needMpUpdate(int barPixels)
  3391.     {
  3392.         double currentMp = getCurrentMp();
  3393.        
  3394.         if (currentMp <= 1.0 || getMaxMp() < barPixels)
  3395.             return true;
  3396.        
  3397.         if (currentMp <= _mpUpdateDecCheck || currentMp >= _mpUpdateIncCheck)
  3398.         {
  3399.             if (currentMp == getMaxMp())
  3400.             {
  3401.                 _mpUpdateIncCheck = currentMp + 1;
  3402.                 _mpUpdateDecCheck = currentMp - _mpUpdateInterval;
  3403.             }
  3404.             else
  3405.             {
  3406.                 double doubleMulti = currentMp / _mpUpdateInterval;
  3407.                 int intMulti = (int) doubleMulti;
  3408.                
  3409.                 _mpUpdateDecCheck = _mpUpdateInterval * (doubleMulti < intMulti ? intMulti-- : intMulti);
  3410.                 _mpUpdateIncCheck = _mpUpdateDecCheck + _mpUpdateInterval;
  3411.             }
  3412.            
  3413.             return true;
  3414.         }
  3415.        
  3416.         return false;
  3417.     }
  3418.    
  3419.     /**
  3420.      * Send packet StatusUpdate with current HP,MP and CP to the L2PcInstance and only current HP, MP and Level to all other L2PcInstance of the Party.<BR>
  3421.      * <BR>
  3422.      * <B><U> Actions</U> :</B><BR>
  3423.      * <BR>
  3424.      * <li>Send the Server->Client packet StatusUpdate with current HP, MP and CP to this L2PcInstance</li><BR>
  3425.      * <li>Send the Server->Client packet PartySmallWindowUpdate with current HP, MP and Level to all other L2PcInstance of the Party</li><BR>
  3426.      * <BR>
  3427.      * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method DOESN'T SEND current HP and MP to all L2PcInstance of the _statusListener</B></FONT><BR>
  3428.      * <BR>
  3429.      */
  3430.     @Override
  3431.     public void broadcastStatusUpdate()
  3432.     {
  3433.         // Send the Server->Client packet StatusUpdate with current HP, MP and CP to this L2PcInstance
  3434.         StatusUpdate su = new StatusUpdate(this);
  3435.         su.addAttribute(StatusUpdate.CUR_HP, (int) getCurrentHp());
  3436.         su.addAttribute(StatusUpdate.CUR_MP, (int) getCurrentMp());
  3437.         su.addAttribute(StatusUpdate.CUR_CP, (int) getCurrentCp());
  3438.         su.addAttribute(StatusUpdate.MAX_CP, getMaxCp());
  3439.         sendPacket(su);
  3440.        
  3441.         final boolean needCpUpdate = needCpUpdate(352);
  3442.         final boolean needHpUpdate = needHpUpdate(352);
  3443.         // Check if a party is in progress and party window update is usefull
  3444.         L2Party party = _party;
  3445.         if (party != null && (needCpUpdate || needHpUpdate || needMpUpdate(352)))
  3446.         {
  3447.             if (Config.DEBUG)
  3448.                 _log.fine("Send status for party window of " + getObjectId() + "(" + getName() + ") to his party. CP: " + getCurrentCp() + " HP: " + getCurrentHp() + " MP: " + getCurrentMp());
  3449.             // Send the Server->Client packet PartySmallWindowUpdate with current HP, MP and Level to all other L2PcInstance of the Party
  3450.             PartySmallWindowUpdate update = new PartySmallWindowUpdate(this);
  3451.             party.broadcastToPartyMembers(this, update);
  3452.         }
  3453.        
  3454.         if (isInOlympiadMode() && isOlympiadStart() && (needCpUpdate || needHpUpdate))
  3455.         {
  3456.             final OlympiadGameTask game = OlympiadGameManager.getInstance().getOlympiadTask(getOlympiadGameId());
  3457.             if (game != null && game.isBattleStarted())
  3458.                 game.getZone().broadcastStatusUpdate(this);
  3459.         }
  3460.        
  3461.         // In duel, MP updated only with CP or HP
  3462.         if (isInDuel() && (needCpUpdate || needHpUpdate))
  3463.         {
  3464.             ExDuelUpdateUserInfo update = new ExDuelUpdateUserInfo(this);
  3465.             DuelManager.getInstance().broadcastToOppositeTeam(this, update);
  3466.         }
  3467.     }
  3468.    
  3469.     /**
  3470.      * Broadcast informations from a user to himself and his knownlist.<BR>
  3471.      * If player is morphed, it sends informations from the template the player is using.<BR>
  3472.      * <BR>
  3473.      * <B><U> Actions</U> :</B><BR>
  3474.      * <li>Send a UserInfo packet (public and private data) to this L2PcInstance.</li> <li>Send a CharInfo packet (public data only) to L2PcInstance's knownlist.</li>
  3475.      */
  3476.     public final void broadcastUserInfo()
  3477.     {
  3478.         sendPacket(new UserInfo(this));
  3479.        
  3480.         if (getPoly().isMorphed())
  3481.             Broadcast.toKnownPlayers(this, new AbstractNpcInfo.PcMorphInfo(this, getPoly().getNpcTemplate()));
  3482.         else
  3483.             broadcastCharInfo();
  3484.     }
  3485.    
  3486.     public final void broadcastCharInfo()
  3487.     {
  3488.         for (L2PcInstance player : getKnownList().getKnownType(L2PcInstance.class))
  3489.         {
  3490.             player.sendPacket(new CharInfo(this));
  3491.            
  3492.             final int relation = getRelation(player);
  3493.             player.sendPacket(new RelationChanged(this, relation, isAutoAttackable(player)));
  3494.             if (getPet() != null)
  3495.                 player.sendPacket(new RelationChanged(getPet(), relation, isAutoAttackable(player)));
  3496.         }
  3497.     }
  3498.    
  3499.     /**
  3500.      * @return the Alliance Identifier of the L2PcInstance.
  3501.      */
  3502.     public int getAllyId()
  3503.     {
  3504.         if (_clan == null)
  3505.             return 0;
  3506.        
  3507.         return _clan.getAllyId();
  3508.     }
  3509.    
  3510.     public int getAllyCrestId()
  3511.     {
  3512.         if (getClanId() == 0)
  3513.             return 0;
  3514.        
  3515.         if (getClan().getAllyId() == 0)
  3516.             return 0;
  3517.        
  3518.         return getClan().getAllyCrestId();
  3519.     }
  3520.    
  3521.     /**
  3522.      * Send a packet to the L2PcInstance.
  3523.      */
  3524.     @Override
  3525.     public void sendPacket(L2GameServerPacket packet)
  3526.     {
  3527.         if (_client != null)
  3528.             _client.sendPacket(packet);
  3529.     }
  3530.    
  3531.     /**
  3532.      * Send SystemMessage packet.
  3533.      * @param id SystemMessageId
  3534.      */
  3535.     @Override
  3536.     public void sendPacket(SystemMessageId id)
  3537.     {
  3538.         sendPacket(SystemMessage.getSystemMessage(id));
  3539.     }
  3540.    
  3541.     /**
  3542.      * Manage Interact Task with another L2PcInstance.<BR>
  3543.      * <BR>
  3544.      * Turn the character in front of the target.<BR>
  3545.      * In case of private stores, send the related packet.
  3546.      * @param target The L2Character targeted
  3547.      */
  3548.     public void doInteract(L2Character target)
  3549.     {
  3550.         if (target instanceof L2PcInstance)
  3551.         {
  3552.             L2PcInstance temp = (L2PcInstance) target;
  3553.             sendPacket(new MoveToPawn(this, temp, L2Npc.INTERACTION_DISTANCE));
  3554.            
  3555.             switch (temp.getPrivateStoreType())
  3556.             {
  3557.                 case STORE_PRIVATE_SELL:
  3558.                 case STORE_PRIVATE_PACKAGE_SELL:
  3559.                     sendPacket(new PrivateStoreListSell(this, temp));
  3560.                     break;
  3561.                
  3562.                 case STORE_PRIVATE_BUY:
  3563.                     sendPacket(new PrivateStoreListBuy(this, temp));
  3564.                     break;
  3565.                
  3566.                 case STORE_PRIVATE_MANUFACTURE:
  3567.                     sendPacket(new RecipeShopSellList(this, temp));
  3568.                     break;
  3569.             }
  3570.         }
  3571.         else
  3572.         {
  3573.             // _interactTarget=null should never happen but one never knows ^^;
  3574.             if (target != null)
  3575.                 target.onAction(this);
  3576.         }
  3577.     }
  3578.    
  3579.     /**
  3580.      * Manage AutoLoot Task.<BR>
  3581.      * <BR>
  3582.      * <B><U> Actions</U> :</B><BR>
  3583.      * <BR>
  3584.      * <li>Send a System Message to the L2PcInstance : YOU_PICKED_UP_S1_ADENA or YOU_PICKED_UP_S1_S2</li> <li>Add the Item to the L2PcInstance inventory</li> <li>Send InventoryUpdate to this L2PcInstance with NewItem (use a new slot) or ModifiedItem (increase amount)</li> <li>Send StatusUpdate to
  3585.      * this L2PcInstance with current weight</li><BR>
  3586.      * <BR>
  3587.      * <FONT COLOR=#FF0000><B> <U>Caution</U> : If a Party is in progress, distribute Items between party members</B></FONT><BR>
  3588.      * <BR>
  3589.      * @param target The reference Object.
  3590.      * @param item The dropped RewardItem.
  3591.      */
  3592.     public void doAutoLoot(L2Attackable target, L2Attackable.RewardItem item)
  3593.     {
  3594.         if (isInParty())
  3595.             getParty().distributeItem(this, item, false, target);
  3596.         else if (item.getItemId() == 57)
  3597.             addAdena("Loot", item.getCount(), target, true);
  3598.         else
  3599.             addItem("Loot", item.getItemId(), item.getCount(), target, true);
  3600.     }
  3601.    
  3602.     /**
  3603.      * Manage Pickup Task.<BR>
  3604.      * <BR>
  3605.      * <B><U> Actions</U> :</B><BR>
  3606.      * <BR>
  3607.      * <li>Send StopMove to this L2PcInstance</li> <li>Remove the L2ItemInstance from the world and send server->client GetItem packets</li> <li>Send a System Message to the L2PcInstance : YOU_PICKED_UP_S1_ADENA or YOU_PICKED_UP_S1_S2</li> <li>Add the Item to the L2PcInstance inventory</li> <li>Send
  3608.      * InventoryUpdate to this L2PcInstance with NewItem (use a new slot) or ModifiedItem (increase amount)</li> <li>Send StatusUpdate to this L2PcInstance with current weight</li><BR>
  3609.      * <BR>
  3610.      * <FONT COLOR=#FF0000><B> <U>Caution</U> : If a Party is in progress, distribute Items between party members</B></FONT><BR>
  3611.      * <BR>
  3612.      * @param object The L2ItemInstance to pick up
  3613.      */
  3614.     protected void doPickupItem(L2Object object)
  3615.     {
  3616.         if (isAlikeDead() || isFakeDeath())
  3617.             return;
  3618.        
  3619.         // Set the AI Intention to IDLE
  3620.         getAI().setIntention(CtrlIntention.IDLE);
  3621.        
  3622.         // Check if the L2Object to pick up is a L2ItemInstance
  3623.         if (!(object instanceof L2ItemInstance))
  3624.         {
  3625.             // dont try to pickup anything that is not an item :)
  3626.             _log.warning(getName() + " tried to pickup a wrong target: " + object);
  3627.             return;
  3628.         }
  3629.        
  3630.         L2ItemInstance target = (L2ItemInstance) object;
  3631.        
  3632.         // Send ActionFailed to this L2PcInstance
  3633.         sendPacket(ActionFailed.STATIC_PACKET);
  3634.         sendPacket(new StopMove(this));
  3635.        
  3636.         synchronized (target)
  3637.         {
  3638.             // Check if the target to pick up is visible
  3639.             if (!target.isVisible())
  3640.                 return;
  3641.            
  3642.             if (!target.getDropProtection().tryPickUp(this))
  3643.             {
  3644.                 sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FAILED_TO_PICKUP_S1).addItemName(target.getItemId()));
  3645.                 return;
  3646.             }
  3647.            
  3648.             if (((isInParty() && getParty().getLootDistribution() == L2Party.ITEM_LOOTER) || !isInParty()) && !_inventory.validateCapacity(target))
  3649.             {
  3650.                 sendPacket(SystemMessageId.SLOTS_FULL);
  3651.                 return;
  3652.             }
  3653.            
  3654.             if (getActiveTradeList() != null)
  3655.             {
  3656.                 sendPacket(SystemMessageId.CANNOT_PICKUP_OR_USE_ITEM_WHILE_TRADING);
  3657.                 return;
  3658.             }
  3659.            
  3660.             if (target.getOwnerId() != 0 && target.getOwnerId() != getObjectId() && !isInLooterParty(target.getOwnerId()))
  3661.             {
  3662.                 if (target.getItemId() == 57)
  3663.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FAILED_TO_PICKUP_S1_ADENA).addNumber(target.getCount()));
  3664.                 else if (target.getCount() > 1)
  3665.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FAILED_TO_PICKUP_S2_S1_S).addItemName(target).addNumber(target.getCount()));
  3666.                 else
  3667.                     sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FAILED_TO_PICKUP_S1).addItemName(target));
  3668.                
  3669.                 return;
  3670.             }
  3671.            
  3672.             if (target.getItemLootShedule() != null && (target.getOwnerId() == getObjectId() || isInLooterParty(target.getOwnerId())))
  3673.                 target.resetOwnerTimer();
  3674.            
  3675.             // Remove the L2ItemInstance from the world and send server->client GetItem packets
  3676.             target.pickupMe(this);
  3677.            
  3678.             if (Config.SAVE_DROPPED_ITEM) // item must be removed from ItemsOnGroundManager if is active
  3679.                 ItemsOnGroundManager.getInstance().removeObject(target);
  3680.         }
  3681.        
  3682.         // Auto use herbs - pick up
  3683.         if (target.getItemType() == L2EtcItemType.HERB)
  3684.         {
  3685.             IItemHandler handler = ItemHandler.getInstance().getItemHandler(target.getEtcItem());
  3686.             if (handler != null)
  3687.                 handler.useItem(this, target, false);
  3688.            
  3689.             ItemTable.getInstance().destroyItem("Consume", target, this, null);
  3690.         }
  3691.         // Cursed Weapons are not distributed
  3692.         else if (CursedWeaponsManager.getInstance().isCursed(target.getItemId()))
  3693.         {
  3694.             addItem("Pickup", target, null, true);
  3695.         }
  3696.         else
  3697.         {
  3698.             // if item is instance of L2ArmorType or L2WeaponType broadcast an "Attention" system message
  3699.             if (target.getItemType() instanceof L2ArmorType || target.getItemType() instanceof L2WeaponType)
  3700.             {
  3701.                 if (target.getEnchantLevel() > 0)
  3702.                 {
  3703.                     SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.ATTENTION_S1_PICKED_UP_S2_S3);
  3704.                     msg.addString(getName());
  3705.                     msg.addNumber(target.getEnchantLevel());
  3706.                     msg.addItemName(target.getItemId());
  3707.                     broadcastPacket(msg, 1400);
  3708.                 }
  3709.                 else
  3710.                 {
  3711.                     SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.ATTENTION_S1_PICKED_UP_S2);
  3712.                     msg.addString(getName());
  3713.                     msg.addItemName(target.getItemId());
  3714.                     broadcastPacket(msg, 1400);
  3715.                 }
  3716.             }
  3717.            
  3718.             // Check if a Party is in progress
  3719.             if (isInParty())
  3720.                 getParty().distributeItem(this, target);
  3721.             // Target is adena
  3722.             else if (target.getItemId() == 57 && getInventory().getAdenaInstance() != null)
  3723.             {
  3724.                 addAdena("Pickup", target.getCount(), null, true);
  3725.                 ItemTable.getInstance().destroyItem("Pickup", target, this, null);
  3726.             }
  3727.             // Target is regular item
  3728.             else
  3729.                 addItem("Pickup", target, null, true);
  3730.         }
  3731.     }
  3732.    
  3733.     public boolean canOpenPrivateStore()
  3734.     {
  3735.         return !isAlikeDead() && !isInOlympiadMode() && !isMounted() && isInsideZone(ZoneId.PRIVATESTORE) && !isCastingNow();
  3736.     }
  3737.    
  3738.     public void tryOpenPrivateBuyStore()
  3739.     {
  3740.         if (canOpenPrivateStore())
  3741.         {
  3742.             if (getPrivateStoreType() == STORE_PRIVATE_BUY || getPrivateStoreType() == STORE_PRIVATE_MANAGE)
  3743.                 setPrivateStoreType(STORE_PRIVATE_NONE);
  3744.            
  3745.             if (getPrivateStoreType() == STORE_PRIVATE_NONE)
  3746.             {
  3747.                 if (isSitting())
  3748.                     standUp();
  3749.                
  3750.                 setPrivateStoreType(STORE_PRIVATE_MANAGE);
  3751.                 sendPacket(new PrivateStoreManageListBuy(this));
  3752.             }
  3753.         }
  3754.         else
  3755.         {
  3756.             if (!isInsideZone(ZoneId.PRIVATESTORE))
  3757.                 sendPacket(SystemMessageId.NO_PRIVATE_STORE_HERE);
  3758.            
  3759.             sendPacket(ActionFailed.STATIC_PACKET);
  3760.         }
  3761.     }
  3762.    
  3763.     public void tryOpenPrivateSellStore(boolean isPackageSale)
  3764.     {
  3765.         if (canOpenPrivateStore())
  3766.         {
  3767.             if (getPrivateStoreType() == STORE_PRIVATE_SELL || getPrivateStoreType() == STORE_PRIVATE_SELL + 1 || getPrivateStoreType() == STORE_PRIVATE_PACKAGE_SELL)
  3768.                 setPrivateStoreType(STORE_PRIVATE_NONE);
  3769.            
  3770.             if (getPrivateStoreType() == STORE_PRIVATE_NONE)
  3771.             {
  3772.                 if (isSitting())
  3773.                     standUp();
  3774.                
  3775.                 setPrivateStoreType(STORE_PRIVATE_SELL + 1);
  3776.                 sendPacket(new PrivateStoreManageListSell(this, isPackageSale));
  3777.             }
  3778.         }
  3779.         else
  3780.         {
  3781.             if (!isInsideZone(ZoneId.PRIVATESTORE))
  3782.                 sendPacket(SystemMessageId.NO_PRIVATE_STORE_HERE);
  3783.            
  3784.             sendPacket(ActionFailed.STATIC_PACKET);
  3785.         }
  3786.     }
  3787.    
  3788.     public void tryOpenWorkshop(boolean isDwarven)
  3789.     {
  3790.         if (canOpenPrivateStore())
  3791.         {
  3792.             if (isInStoreMode())
  3793.                 setPrivateStoreType(STORE_PRIVATE_NONE);
  3794.            
  3795.             if (getPrivateStoreType() == STORE_PRIVATE_NONE)
  3796.             {
  3797.                 if (isSitting())
  3798.                     standUp();
  3799.                
  3800.                 if (getCreateList() == null)
  3801.                     setCreateList(new L2ManufactureList());
  3802.                
  3803.                 sendPacket(new RecipeShopManageList(this, isDwarven));
  3804.             }
  3805.         }
  3806.         else
  3807.         {
  3808.             if (!isInsideZone(ZoneId.PRIVATESTORE))
  3809.                 sendPacket(SystemMessageId.NO_PRIVATE_WORKSHOP_HERE);
  3810.            
  3811.             sendPacket(ActionFailed.STATIC_PACKET);
  3812.         }
  3813.     }
  3814.    
  3815.     /**
  3816.      * Set a target.
  3817.      * <ul>
  3818.      * <li>Remove the L2PcInstance from the _statusListener of the old target if it was a L2Character</li>
  3819.      * <li>Add the L2PcInstance to the _statusListener of the new target if it's a L2Character</li>
  3820.      * <li>Target the new L2Object (add the target to the L2PcInstance _target, _knownObject and L2PcInstance to _KnownObject of the L2Object)</li>
  3821.      * </ul>
  3822.      * @param newTarget The L2Object to target
  3823.      */
  3824.     @Override
  3825.     public void setTarget(L2Object newTarget)
  3826.     {
  3827.         if (newTarget != null)
  3828.         {
  3829.             boolean isParty = (((newTarget instanceof L2PcInstance) && isInParty() && getParty().getPartyMembers().contains(newTarget)));
  3830.            
  3831.             // Check if the new target is visible
  3832.             if (!isParty && (!newTarget.isVisible() || Math.abs(newTarget.getZ() - getZ()) > 1000))
  3833.                 newTarget = null;
  3834.         }
  3835.        
  3836.         // Can't target and attack festival monsters if not participant
  3837.         if ((newTarget instanceof L2FestivalMonsterInstance) && !isFestivalParticipant())
  3838.             newTarget = null;
  3839.         // Can't target and attack rift invaders if not in the same room
  3840.         else if (isInParty() && getParty().isInDimensionalRift())
  3841.         {
  3842.             byte riftType = getParty().getDimensionalRift().getType();
  3843.             byte riftRoom = getParty().getDimensionalRift().getCurrentRoom();
  3844.            
  3845.             if (newTarget != null && !DimensionalRiftManager.getInstance().getRoom(riftType, riftRoom).checkIfInZone(newTarget.getX(), newTarget.getY(), newTarget.getZ()))
  3846.                 newTarget = null;
  3847.         }
  3848.        
  3849.         // Get the current target
  3850.         L2Object oldTarget = getTarget();
  3851.        
  3852.         if (oldTarget != null)
  3853.         {
  3854.             if (oldTarget.equals(newTarget))
  3855.                 return; // no target change
  3856.                
  3857.             // Remove the L2PcInstance from the _statusListener of the old target if it was a L2Character
  3858.             if (oldTarget instanceof L2Character)
  3859.                 ((L2Character) oldTarget).removeStatusListener(this);
  3860.         }
  3861.        
  3862.         // Add the L2PcInstance to the _statusListener of the new target if it's a L2Character
  3863.         if (newTarget instanceof L2Character)
  3864.         {
  3865.             final L2Character target = (L2Character) newTarget;
  3866.            
  3867.             target.addStatusListener(this);
  3868.            
  3869.             // Show the client his new target.
  3870.             if (target.isAutoAttackable(this))
  3871.             {
  3872.                 // Show the client his new target.
  3873.                 sendPacket(new MyTargetSelected(target.getObjectId(), getLevel() - target.getLevel()));
  3874.                
  3875.                 // Send max/current hp.
  3876.                 final StatusUpdate su = new StatusUpdate(target);
  3877.                 su.addAttribute(StatusUpdate.MAX_HP, target.getMaxHp());
  3878.                 su.addAttribute(StatusUpdate.CUR_HP, (int) target.getCurrentHp());
  3879.                 sendPacket(su);
  3880.             }
  3881.             else
  3882.                 sendPacket(new MyTargetSelected(target.getObjectId(), 0));
  3883.            
  3884.             Broadcast.toKnownPlayers(this, new TargetSelected(getObjectId(), newTarget.getObjectId(), getX(), getY(), getZ()));
  3885.         }
  3886.        
  3887.         if (newTarget == null && getTarget() != null)
  3888.         {
  3889.             broadcastPacket(new TargetUnselected(this));
  3890.             setCurrentFolkNPC(null);
  3891.         }
  3892.         else
  3893.         {
  3894.             // Rehabilitates that useful check.
  3895.             if (newTarget instanceof L2NpcInstance)
  3896.                 setCurrentFolkNPC((L2Npc) newTarget);
  3897.         }
  3898.        
  3899.         // Target the new L2Object (add the target to the L2PcInstance _target, _knownObject and L2PcInstance to _KnownObject of the L2Object)
  3900.         super.setTarget(newTarget);
  3901.     }
  3902.    
  3903.     /**
  3904.      * Return the active weapon instance (always equipped in the right hand).<BR>
  3905.      * <BR>
  3906.      */
  3907.     @Override
  3908.     public L2ItemInstance getActiveWeaponInstance()
  3909.     {
  3910.         return getInventory().getPaperdollItem(Inventory.PAPERDOLL_RHAND);
  3911.     }
  3912.    
  3913.     /**
  3914.      * Return the active weapon item (always equipped in the right hand).<BR>
  3915.      * <BR>
  3916.      */
  3917.     @Override
  3918.     public L2Weapon getActiveWeaponItem()
  3919.     {
  3920.         L2ItemInstance weapon = getActiveWeaponInstance();
  3921.        
  3922.         if (weapon == null)
  3923.             return getFistsWeaponItem();
  3924.        
  3925.         return (L2Weapon) weapon.getItem();
  3926.     }
  3927.    
  3928.     public L2ItemInstance getChestArmorInstance()
  3929.     {
  3930.         return getInventory().getPaperdollItem(Inventory.PAPERDOLL_CHEST);
  3931.     }
  3932.    
  3933.     public L2Armor getActiveChestArmorItem()
  3934.     {
  3935.         L2ItemInstance armor = getChestArmorInstance();
  3936.        
  3937.         if (armor == null)
  3938.             return null;
  3939.        
  3940.         return (L2Armor) armor.getItem();
  3941.     }
  3942.    
  3943.     public boolean isWearingHeavyArmor()
  3944.     {
  3945.         L2ItemInstance armor = getChestArmorInstance();
  3946.        
  3947.         if ((L2ArmorType) armor.getItemType() == L2ArmorType.HEAVY)
  3948.             return true;
  3949.        
  3950.         return false;
  3951.     }
  3952.    
  3953.     public boolean isWearingLightArmor()
  3954.     {
  3955.         L2ItemInstance armor = getChestArmorInstance();
  3956.        
  3957.         if ((L2ArmorType) armor.getItemType() == L2ArmorType.LIGHT)
  3958.             return true;
  3959.        
  3960.         return false;
  3961.     }
  3962.    
  3963.     public boolean isWearingMagicArmor()
  3964.     {
  3965.         L2ItemInstance armor = getChestArmorInstance();
  3966.        
  3967.         if ((L2ArmorType) armor.getItemType() == L2ArmorType.MAGIC)
  3968.             return true;
  3969.        
  3970.         return false;
  3971.     }
  3972.    
  3973.     public boolean isMarried()
  3974.     {
  3975.         return _married;
  3976.     }
  3977.    
  3978.     public void setMarried(boolean state)
  3979.     {
  3980.         _married = state;
  3981.     }
  3982.    
  3983.     public void setUnderMarryRequest(boolean state)
  3984.     {
  3985.         _marryrequest = state;
  3986.     }
  3987.    
  3988.     public boolean isUnderMarryRequest()
  3989.     {
  3990.         return _marryrequest;
  3991.     }
  3992.    
  3993.     public int getCoupleId()
  3994.     {
  3995.         return _coupleId;
  3996.     }
  3997.    
  3998.     public void setCoupleId(int coupleId)
  3999.     {
  4000.         _coupleId = coupleId;
  4001.     }
  4002.    
  4003.     public void setRequesterId(int requesterId)
  4004.     {
  4005.         _requesterId = requesterId;
  4006.     }
  4007.    
  4008.     public void EngageAnswer(int answer)
  4009.     {
  4010.         if (!_marryrequest || _requesterId == 0)
  4011.             return;
  4012.        
  4013.         L2PcInstance ptarget = L2World.getInstance().getPlayer(_requesterId);
  4014.         if (ptarget != null)
  4015.         {
  4016.             if (answer == 1)
  4017.             {
  4018.                 // Create the couple
  4019.                 CoupleManager.getInstance().createCouple(ptarget, this);
  4020.                
  4021.                 // Then "finish the job"
  4022.                 L2WeddingManagerInstance.justMarried(ptarget, this);
  4023.             }
  4024.             else
  4025.             {
  4026.                 setUnderMarryRequest(false);
  4027.                 sendMessage("You declined your partner's marriage request.");
  4028.                
  4029.                 ptarget.setUnderMarryRequest(false);
  4030.                 ptarget.sendMessage("Your partner declined your marriage request.");
  4031.             }
  4032.         }
  4033.     }
  4034.    
  4035.     /**
  4036.      * Return the secondary weapon instance (always equipped in the left hand).<BR>
  4037.      * <BR>
  4038.      */
  4039.     @Override
  4040.     public L2ItemInstance getSecondaryWeaponInstance()
  4041.     {
  4042.         return getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
  4043.     }
  4044.    
  4045.     /**
  4046.      * Return the secondary L2Item item (always equiped in the left hand).<BR>
  4047.      * Arrows, shield,...<BR>
  4048.      */
  4049.     @Override
  4050.     public L2Item getSecondaryWeaponItem()
  4051.     {
  4052.         L2ItemInstance item = getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
  4053.         if (item != null)
  4054.             return item.getItem();
  4055.        
  4056.         return null;
  4057.     }
  4058.    
  4059.     /**
  4060.      * Kill the L2Character, Apply Death Penalty, Manage gain/loss Karma and Item Drop.<BR>
  4061.      * <BR>
  4062.      * <B><U> Actions</U> :</B><BR>
  4063.      * <BR>
  4064.      * <li>Reduce the Experience of the L2PcInstance in function of the calculated Death Penalty</li> <li>If necessary, unsummon the Pet of the killed L2PcInstance</li> <li>Manage Karma gain for attacker and Karam loss for the killed L2PcInstance</li> <li>If the killed L2PcInstance has Karma, manage
  4065.      * Drop Item</li> <li>Kill the L2PcInstance</li><BR>
  4066.      * <BR>
  4067.      * @param killer The L2Character who attacks
  4068.      */
  4069.     @Override
  4070.     public boolean doDie(L2Character killer)
  4071.     {
  4072.         // Kill the L2PcInstance
  4073.         if (!super.doDie(killer))
  4074.             return false;
  4075.        
  4076.         if (isMounted())
  4077.             stopFeed();
  4078.        
  4079.         synchronized (this)
  4080.         {
  4081.             if (isFakeDeath())
  4082.                 stopFakeDeath(true);
  4083.         }
  4084.        
  4085.         if (killer != null)
  4086.         {
  4087.             L2PcInstance pk = killer.getActingPlayer();
  4088.            
  4089.             // Clear resurrect xp calculation
  4090.             setExpBeforeDeath(0);
  4091.            
  4092.             if (isCursedWeaponEquipped())
  4093.                 CursedWeaponsManager.getInstance().drop(_cursedWeaponEquippedId, killer);
  4094.             else
  4095.             {
  4096.                 if (pk == null || !pk.isCursedWeaponEquipped())
  4097.                 {
  4098.                     onDieDropItem(killer); // Check if any item should be dropped
  4099.                    
  4100.                     // if the area isn't an arena
  4101.                     if (!isInArena())
  4102.                     {
  4103.                         // if both victim and attacker got clans & aren't academicians
  4104.                         if (pk != null && pk.getClan() != null && getClan() != null && !isAcademyMember() && !pk.isAcademyMember())
  4105.                         {
  4106.                             // if clans got mutual war, then use the reputation calcul
  4107.                             if (_clan.isAtWarWith(pk.getClanId()) && pk.getClan().isAtWarWith(_clan.getClanId()))
  4108.                             {
  4109.                                 if (AntiFeedManager.getInstance().check(killer, this))
  4110.                                 {
  4111.                                     // when your reputation score is 0 or below, the other clan cannot acquire any reputation points
  4112.                                     if (getClan().getReputationScore() > 0)
  4113.                                         pk.getClan().addReputationScore(1);
  4114.                                     // when the opposing sides reputation score is 0 or below, your clans reputation score doesn't decrease
  4115.                                     if (pk.getClan().getReputationScore() > 0)
  4116.                                         _clan.takeReputationScore(1);
  4117.                                 }
  4118.                             }
  4119.                         }
  4120.                     }
  4121.                    
  4122.                     // Reduce player's xp and karma.
  4123.                     if (Config.ALT_GAME_DELEVEL && (getSkillLevel(L2Skill.SKILL_LUCKY) < 0 || getStat().getLevel() > 9))
  4124.                         deathPenalty(pk != null && getClan() != null && (getClan().isAtWarWith(pk.getClanId()) || pk.getClan().isAtWarWith(getClanId())), pk != null, killer instanceof L2SiegeGuardInstance);
  4125.                 }
  4126.             }
  4127.         }
  4128.        
  4129.         // Unsummon Cubics
  4130.         if (!_cubics.isEmpty())
  4131.         {
  4132.             for (L2CubicInstance cubic : _cubics.values())
  4133.             {
  4134.                 cubic.stopAction();
  4135.                 cubic.cancelDisappear();
  4136.             }
  4137.            
  4138.             _cubics.clear();
  4139.         }
  4140.        
  4141.         if (_fusionSkill != null)
  4142.             abortCast();
  4143.        
  4144.         for (L2Character character : getKnownList().getKnownType(L2Character.class))
  4145.             if (character.getFusionSkill() != null && character.getFusionSkill().getTarget() == this)
  4146.                 character.abortCast();
  4147.        
  4148.         if (isInParty() && getParty().isInDimensionalRift())
  4149.             getParty().getDimensionalRift().getDeadMemberList().add(this);
  4150.        
  4151.         // calculate death penalty buff
  4152.         calculateDeathPenaltyBuffLevel(killer);
  4153.        
  4154.         stopWaterTask();
  4155.        
  4156.         AntiFeedManager.getInstance().setLastDeathTime(getObjectId());
  4157.        
  4158.         if (isPhoenixBlessed() || (isAffected(L2EffectFlag.CHARM_OF_COURAGE) && isInSiege()))
  4159.             reviveRequest(this, null, false);
  4160.        
  4161.         // Icons update in order to get retained buffs list
  4162.         updateEffectIcons();
  4163.        
  4164.         return true;
  4165.     }
  4166.    
  4167.     private void onDieDropItem(L2Character killer)
  4168.     {
  4169.         if (killer == null)
  4170.             return;
  4171.        
  4172.         L2PcInstance pk = killer.getActingPlayer();
  4173.         if (getKarma() <= 0 && pk != null && pk.getClan() != null && getClan() != null && pk.getClan().isAtWarWith(getClanId()))
  4174.             return;
  4175.        
  4176.         if ((!isInsideZone(ZoneId.PVP) || pk == null) && (!isGM() || Config.KARMA_DROP_GM))
  4177.         {
  4178.             boolean isKillerNpc = (killer instanceof L2Npc);
  4179.             int pkLimit = Config.KARMA_PK_LIMIT;
  4180.            
  4181.             int dropEquip = 0;
  4182.             int dropEquipWeapon = 0;
  4183.             int dropItem = 0;
  4184.             int dropLimit = 0;
  4185.             int dropPercent = 0;
  4186.            
  4187.             if (getKarma() > 0 && getPkKills() >= pkLimit)
  4188.             {
  4189.                 dropPercent = Config.KARMA_RATE_DROP;
  4190.                 dropEquip = Config.KARMA_RATE_DROP_EQUIP;
  4191.                 dropEquipWeapon = Config.KARMA_RATE_DROP_EQUIP_WEAPON;
  4192.                 dropItem = Config.KARMA_RATE_DROP_ITEM;
  4193.                 dropLimit = Config.KARMA_DROP_LIMIT;
  4194.             }
  4195.             else if (isKillerNpc && getLevel() > 4 && !isFestivalParticipant())
  4196.             {
  4197.                 dropPercent = Config.PLAYER_RATE_DROP;
  4198.                 dropEquip = Config.PLAYER_RATE_DROP_EQUIP;
  4199.                 dropEquipWeapon = Config.PLAYER_RATE_DROP_EQUIP_WEAPON;
  4200.                 dropItem = Config.PLAYER_RATE_DROP_ITEM;
  4201.                 dropLimit = Config.PLAYER_DROP_LIMIT;
  4202.             }
  4203.            
  4204.             if (dropPercent > 0 && Rnd.get(100) < dropPercent)
  4205.             {
  4206.                 int dropCount = 0;
  4207.                 int itemDropPercent = 0;
  4208.                
  4209.                 for (L2ItemInstance itemDrop : getInventory().getItems())
  4210.                 {
  4211.                     // Don't drop those following things
  4212.                     if (!itemDrop.isDropable() || itemDrop.isShadowItem() || itemDrop.getItemId() == 57 || itemDrop.getItem().getType2() == L2Item.TYPE2_QUEST || getPet() != null && getPet().getControlItemId() == itemDrop.getItemId() || Arrays.binarySearch(Config.KARMA_LIST_NONDROPPABLE_ITEMS, itemDrop.getItemId()) >= 0 || Arrays.binarySearch(Config.KARMA_LIST_NONDROPPABLE_PET_ITEMS, itemDrop.getItemId()) >= 0)
  4213.                         continue;
  4214.                    
  4215.                     if (itemDrop.isEquipped())
  4216.                     {
  4217.                         // Set proper chance according to Item type of equipped Item
  4218.                         itemDropPercent = itemDrop.getItem().getType2() == L2Item.TYPE2_WEAPON ? dropEquipWeapon : dropEquip;
  4219.                         getInventory().unEquipItemInSlot(itemDrop.getLocationSlot());
  4220.                     }
  4221.                     else
  4222.                         itemDropPercent = dropItem; // Item in inventory
  4223.                        
  4224.                     // NOTE: Each time an item is dropped, the chance of another item being dropped gets lesser (dropCount * 2)
  4225.                     if (Rnd.get(100) < itemDropPercent)
  4226.                     {
  4227.                         dropItem("DieDrop", itemDrop, killer, true);
  4228.                        
  4229.                         if (++dropCount >= dropLimit)
  4230.                             break;
  4231.                     }
  4232.                 }
  4233.             }
  4234.         }
  4235.     }
  4236.    
  4237.     public void updateKarmaLoss(long exp)
  4238.     {
  4239.         if (!isCursedWeaponEquipped() && getKarma() > 0)
  4240.         {
  4241.             int karmaLost = Formulas.calculateKarmaLost(getLevel(), Math.round(exp));
  4242.             if (karmaLost > 0)
  4243.                 setKarma(getKarma() - karmaLost);
  4244.         }
  4245.     }
  4246.    
  4247.     /**
  4248.      * This method is used to update PvP counter, or PK counter / add Karma if necessary.<br>
  4249.      * It also updates clan kills/deaths counters on siege.
  4250.      * @param target The L2Playable victim.
  4251.      */
  4252.     public void onKillUpdatePvPKarma(L2Playable target)
  4253.     {
  4254.         if (target == null)
  4255.             return;
  4256.        
  4257.         final L2PcInstance targetPlayer = target.getActingPlayer();
  4258.         if (targetPlayer == null || targetPlayer == this)
  4259.             return;
  4260.        
  4261.         // Don't rank up the CW if it was a summon.
  4262.         if (isCursedWeaponEquipped() && target instanceof L2PcInstance)
  4263.         {
  4264.             CursedWeaponsManager.getInstance().increaseKills(_cursedWeaponEquippedId);
  4265.             return;
  4266.         }
  4267.        
  4268.         // If in duel and you kill (only can kill l2summon), do nothing
  4269.         if (isInDuel() && targetPlayer.isInDuel())
  4270.             return;
  4271.        
  4272.         // If in pvp zone, do nothing.
  4273.         if (isInsideZone(ZoneId.PVP) && targetPlayer.isInsideZone(ZoneId.PVP))
  4274.         {
  4275.             // Until the zone was a siege zone. Check also if victim was a player. Randomers aren't counted.
  4276.             if (target instanceof L2PcInstance && getSiegeState() > 0 && targetPlayer.getSiegeState() > 0 && getSiegeState() != targetPlayer.getSiegeState())
  4277.             {
  4278.                 // Now check clan relations.
  4279.                 final L2Clan killerClan = getClan();
  4280.                 if (killerClan != null)
  4281.                     killerClan.setSiegeKills(killerClan.getSiegeKills() + 1);
  4282.                
  4283.                 final L2Clan targetClan = targetPlayer.getClan();
  4284.                 if (targetClan != null)
  4285.                     targetClan.setSiegeDeaths(targetClan.getSiegeDeaths() + 1);
  4286.             }
  4287.             return;
  4288.         }
  4289.        
  4290.         // Check if it's pvp (cases : regular, wars, victim is PKer)
  4291.         if (checkIfPvP(target) || (targetPlayer.getClan() != null && getClan() != null && getClan().isAtWarWith(targetPlayer.getClanId()) && targetPlayer.getClan().isAtWarWith(getClanId()) && targetPlayer.getPledgeType() != L2Clan.SUBUNIT_ACADEMY && getPledgeType() != L2Clan.SUBUNIT_ACADEMY) || (targetPlayer.getKarma() > 0 && Config.KARMA_AWARD_PK_KILL))
  4292.         {
  4293.             if (target instanceof L2PcInstance && AntiFeedManager.getInstance().check(this, target))
  4294.             {
  4295.                 // Add PvP point to attacker.
  4296.                 setPvpKills(getPvpKills() + 1);
  4297.                
  4298.                 if (Config.ALLOW_PVP_REWARD)
  4299.                 {
  4300.                    for (int[] item : Config.PVP_REWARD_ITEM)                                    
  4301.                     addItem("", item[0], item[1], this, true);
  4302.                     sendMessage("You will be rewarded for pvp kill!");
  4303.                 }
  4304.                
  4305.                 // Send a Server->Client UserInfo packet to attacker with its Karma and PK Counter
  4306.                 sendPacket(new UserInfo(this));
  4307.             }
  4308.         }
  4309.        
  4310.         // Otherwise, killer is considered as a PKer.
  4311.         else if (targetPlayer.getKarma() == 0 && targetPlayer.getPvpFlag() == 0)
  4312.         {
  4313.             // PK Points are increased only if you kill a player.
  4314.             if (target instanceof L2PcInstance)
  4315.                 setPkKills(getPkKills() + 1);
  4316.            
  4317.             if (Config.ALLOW_PK_REWARD)
  4318.             {
  4319.                        for (int[] item : Config.PK_REWARD_ITEM)                                    
  4320.                        addItem("", item[0], item[1], this, true);
  4321.                        sendMessage("You will be rewarded for pk kill!");
  4322.             }
  4323.             // Calculate new karma.
  4324.             setKarma(getKarma() + Formulas.calculateKarmaGain(getPkKills(), target instanceof L2Summon));
  4325.            
  4326.             // Send a Server->Client UserInfo packet to attacker with its Karma and PK Counter
  4327.             sendPacket(new UserInfo(this));
  4328.         }
  4329.     }
  4330.    
  4331.     public void updatePvPStatus()
  4332.     {
  4333.         if (isInsideZone(ZoneId.PVP))
  4334.             return;
  4335.        
  4336.         PvpFlagTaskManager.getInstance().addPvpFlagTask(this, System.currentTimeMillis() + Config.PVP_NORMAL_TIME);
  4337.        
  4338.         if (getPvpFlag() == 0)
  4339.             updatePvPFlag(1);
  4340.     }
  4341.    
  4342.     public void updatePvPStatus(L2Character target)
  4343.     {
  4344.         final L2PcInstance player = target.getActingPlayer();
  4345.         if (player == null)
  4346.             return;
  4347.        
  4348.         if (isInDuel() && player.getDuelId() == getDuelId())
  4349.             return;
  4350.        
  4351.         if ((!isInsideZone(ZoneId.PVP) || !target.isInsideZone(ZoneId.PVP)) && player.getKarma() == 0)
  4352.         {
  4353.             PvpFlagTaskManager.getInstance().addPvpFlagTask(this, System.currentTimeMillis() + ((checkIfPvP(player)) ? Config.PVP_PVP_TIME : Config.PVP_NORMAL_TIME));
  4354.            
  4355.             if (getPvpFlag() == 0)
  4356.                 updatePvPFlag(1);
  4357.         }
  4358.     }
  4359.    
  4360.     /**
  4361.      * Restore the experience this L2PcInstance has lost and sends a Server->Client StatusUpdate packet.
  4362.      * @param restorePercent The specified % of restored experience.
  4363.      */
  4364.     public void restoreExp(double restorePercent)
  4365.     {
  4366.         if (getExpBeforeDeath() > 0)
  4367.         {
  4368.             getStat().addExp((int) Math.round((getExpBeforeDeath() - getExp()) * restorePercent / 100));
  4369.             setExpBeforeDeath(0);
  4370.         }
  4371.     }
  4372.    
  4373.     /**
  4374.      * Reduce the Experience (and level if necessary) of the L2PcInstance in function of the calculated Death Penalty.
  4375.      * <ul>
  4376.      * <li>Calculate the Experience loss</li>
  4377.      * <li>Set the value of _expBeforeDeath</li>
  4378.      * <li>Set the new Experience value of the L2PcInstance and Decrease its level if necessary</li>
  4379.      * <li>Send a Server->Client StatusUpdate packet with its new Experience</li>
  4380.      * </ul>
  4381.      * @param atWar If true, use clan war penalty system instead of regular system.
  4382.      * @param killedByPlayable Used to see if victim loses XP or not.
  4383.      * @param killedBySiegeNpc Used to see if victim loses XP or not.
  4384.      */
  4385.     public void deathPenalty(boolean atWar, boolean killedByPlayable, boolean killedBySiegeNpc)
  4386.     {
  4387.         // No xp loss inside pvp zone unless
  4388.         // - it's a siege zone and you're NOT participating
  4389.         // - you're killed by a non-pc whose not belong to the siege
  4390.         if (isInsideZone(ZoneId.PVP))
  4391.         {
  4392.             // No xp loss for siege participants inside siege zone.
  4393.             if (isInsideZone(ZoneId.SIEGE))
  4394.             {
  4395.                 if (isInSiege() && (killedByPlayable || killedBySiegeNpc))
  4396.                     return;
  4397.             }
  4398.             // No xp loss for arenas participants killed by playable.
  4399.             else if (killedByPlayable)
  4400.                 return;
  4401.         }
  4402.        
  4403.         // Get the level of the L2PcInstance
  4404.         final int lvl = getLevel();
  4405.        
  4406.         // The death steal you some Exp
  4407.         double percentLost = 7.0;
  4408.         if (getLevel() >= 76)
  4409.             percentLost = 2.0;
  4410.         else if (getLevel() >= 40)
  4411.             percentLost = 4.0;
  4412.        
  4413.         if (getKarma() > 0)
  4414.             percentLost *= Config.RATE_KARMA_EXP_LOST;
  4415.        
  4416.         if (isFestivalParticipant() || atWar || isInsideZone(ZoneId.SIEGE))
  4417.             percentLost /= 4.0;
  4418.        
  4419.         // Calculate the Experience loss
  4420.         long lostExp = 0;
  4421.        
  4422.         if (lvl < Experience.MAX_LEVEL)
  4423.             lostExp = Math.round((getStat().getExpForLevel(lvl + 1) - getStat().getExpForLevel(lvl)) * percentLost / 100);
  4424.         else
  4425.             lostExp = Math.round((getStat().getExpForLevel(Experience.MAX_LEVEL) - getStat().getExpForLevel(Experience.MAX_LEVEL - 1)) * percentLost / 100);
  4426.        
  4427.         // Get the Experience before applying penalty
  4428.         setExpBeforeDeath(getExp());
  4429.        
  4430.         if (Config.DEBUG)
  4431.             _log.fine(getName() + " died and lost " + lostExp + " experience.");
  4432.        
  4433.         // Set new karma
  4434.         updateKarmaLoss(lostExp);
  4435.        
  4436.         // Set the new Experience value of the L2PcInstance
  4437.         getStat().addExp(-lostExp);
  4438.     }
  4439.    
  4440.     public boolean isPartyWaiting()
  4441.     {
  4442.         return PartyMatchWaitingList.getInstance().getPlayers().contains(this);
  4443.     }
  4444.    
  4445.     public void setPartyRoom(int id)
  4446.     {
  4447.         _partyroom = id;
  4448.     }
  4449.    
  4450.     public int getPartyRoom()
  4451.     {
  4452.         return _partyroom;
  4453.     }
  4454.    
  4455.     public boolean isInPartyMatchRoom()
  4456.     {
  4457.         return _partyroom > 0;
  4458.     }
  4459.    
  4460.     /**
  4461.      * Manage the increase level task of a L2PcInstance (Max MP, Max MP, Recommandation, Expertise and beginner skills...).<BR>
  4462.      * <BR>
  4463.      * <B><U> Actions</U> :</B><BR>
  4464.      * <BR>
  4465.      * <li>Send a Server->Client System Message to the L2PcInstance : YOU_INCREASED_YOUR_LEVEL</li> <li>Send StatusUpdate to the L2PcInstance with new LEVEL, MAX_HP and MAX_MP</li> <li>Set the current HP and MP of the L2PcInstance, Launch/Stop a HP/MP/CP Regeneration Task and send StatusUpdate
  4466.      * packet to all other L2PcInstance to inform (exclusive broadcast)</li> <li>Recalculate the party level</li> <li>Recalculate the number of Recommandation that the L2PcInstance can give</li> <li>Give Expertise skill of this level and remove beginner Lucky skill</li><BR>
  4467.      * <BR>
  4468.      */
  4469.     public void increaseLevel()
  4470.     {
  4471.         // Set the current HP and MP of the L2Character, Launch/Stop a HP/MP/CP Regeneration Task and send StatusUpdate packet to all other L2PcInstance to inform (exclusive broadcast)
  4472.         setCurrentHpMp(getMaxHp(), getMaxMp());
  4473.         setCurrentCp(getMaxCp());
  4474.     }
  4475.    
  4476.     /**
  4477.      * Stop all timers related to that L2PcInstance.
  4478.      */
  4479.     public void stopAllTimers()
  4480.     {
  4481.         stopHpMpRegeneration();
  4482.         stopWaterTask();
  4483.         stopFeed();
  4484.         clearPetData();
  4485.         storePetFood(_mountNpcId);
  4486.         stopPunishTask(true);
  4487.         stopChargeTask();
  4488.         getInventory().stopShadowTimers();
  4489.        
  4490.         AttackStanceTaskManager.getInstance().removeAttackStanceTask(this);
  4491.         PvpFlagTaskManager.getInstance().removePvpFlagTask(this);
  4492.         TakeBreakTaskManager.getInstance().removeTakeBreakTask(this);
  4493.     }
  4494.    
  4495.     /**
  4496.      * Return the L2Summon of the L2PcInstance or null.
  4497.      */
  4498.     @Override
  4499.     public L2Summon getPet()
  4500.     {
  4501.         return _summon;
  4502.     }
  4503.    
  4504.     /**
  4505.      * @return {@code true} if the player has a pet, {@code false} otherwise
  4506.      */
  4507.     public boolean hasPet()
  4508.     {
  4509.         return _summon instanceof L2PetInstance;
  4510.     }
  4511.    
  4512.     /**
  4513.      * @return {@code true} if the player has a summon, {@code false} otherwise
  4514.      */
  4515.     public boolean hasServitor()
  4516.     {
  4517.         return _summon instanceof L2SummonInstance;
  4518.     }
  4519.    
  4520.     /**
  4521.      * Set the L2Summon of the L2PcInstance.
  4522.      * @param summon The Object.
  4523.      */
  4524.     public void setPet(L2Summon summon)
  4525.     {
  4526.         _summon = summon;
  4527.     }
  4528.    
  4529.     /**
  4530.      * @return the L2TamedBeast of the L2PcInstance or null.
  4531.      */
  4532.     public L2TamedBeastInstance getTrainedBeast()
  4533.     {
  4534.         return _tamedBeast;
  4535.     }
  4536.    
  4537.     /**
  4538.      * Set the L2TamedBeast of the L2PcInstance.
  4539.      * @param tamedBeast The Object.
  4540.      */
  4541.     public void setTrainedBeast(L2TamedBeastInstance tamedBeast)
  4542.     {
  4543.         _tamedBeast = tamedBeast;
  4544.     }
  4545.    
  4546.     /**
  4547.      * @return the L2PcInstance requester of a transaction (ex : FriendInvite, JoinAlly, JoinParty...).
  4548.      */
  4549.     public L2Request getRequest()
  4550.     {
  4551.         return _request;
  4552.     }
  4553.    
  4554.     /**
  4555.      * Set the L2PcInstance requester of a transaction (ex : FriendInvite, JoinAlly, JoinParty...).
  4556.      * @param requester
  4557.      */
  4558.     public void setActiveRequester(L2PcInstance requester)
  4559.     {
  4560.         _activeRequester = requester;
  4561.     }
  4562.    
  4563.     /**
  4564.      * @return the L2PcInstance requester of a transaction (ex : FriendInvite, JoinAlly, JoinParty...).
  4565.      */
  4566.     public L2PcInstance getActiveRequester()
  4567.     {
  4568.         L2PcInstance requester = _activeRequester;
  4569.         if (requester != null)
  4570.         {
  4571.             if (requester.isRequestExpired() && _activeTradeList == null)
  4572.                 _activeRequester = null;
  4573.         }
  4574.         return _activeRequester;
  4575.     }
  4576.    
  4577.     /**
  4578.      * @return True if a request is in progress.
  4579.      */
  4580.     public boolean isProcessingRequest()
  4581.     {
  4582.         return getActiveRequester() != null || _requestExpireTime > GameTimeController.getGameTicks();
  4583.     }
  4584.    
  4585.     /**
  4586.      * @return True if a transaction <B>(trade OR request)</B> is in progress.
  4587.      */
  4588.     public boolean isProcessingTransaction()
  4589.     {
  4590.         return getActiveRequester() != null || _activeTradeList != null || _requestExpireTime > GameTimeController.getGameTicks();
  4591.     }
  4592.    
  4593.     /**
  4594.      * Set the _requestExpireTime of that L2PcInstance, and set his partner as the active requester.
  4595.      * @param partner The partner to make checks on.
  4596.      */
  4597.     public void onTransactionRequest(L2PcInstance partner)
  4598.     {
  4599.         _requestExpireTime = GameTimeController.getGameTicks() + REQUEST_TIMEOUT * GameTimeController.TICKS_PER_SECOND;
  4600.         partner.setActiveRequester(this);
  4601.     }
  4602.    
  4603.     /**
  4604.      * @return true if last request is expired.
  4605.      */
  4606.     public boolean isRequestExpired()
  4607.     {
  4608.         return !(_requestExpireTime > GameTimeController.getGameTicks());
  4609.     }
  4610.    
  4611.     /**
  4612.      * Select the Warehouse to be used in next activity.
  4613.      */
  4614.     public void onTransactionResponse()
  4615.     {
  4616.         _requestExpireTime = 0;
  4617.     }
  4618.    
  4619.     /**
  4620.      * Select the Warehouse to be used in next activity.
  4621.      * @param warehouse An active warehouse.
  4622.      */
  4623.     public void setActiveWarehouse(ItemContainer warehouse)
  4624.     {
  4625.         _activeWarehouse = warehouse;
  4626.     }
  4627.    
  4628.     /**
  4629.      * @return The active Warehouse.
  4630.      */
  4631.     public ItemContainer getActiveWarehouse()
  4632.     {
  4633.         return _activeWarehouse;
  4634.     }
  4635.    
  4636.     /**
  4637.      * Set the TradeList to be used in next activity.
  4638.      * @param tradeList The TradeList to be used.
  4639.      */
  4640.     public void setActiveTradeList(TradeList tradeList)
  4641.     {
  4642.         _activeTradeList = tradeList;
  4643.     }
  4644.    
  4645.     /**
  4646.      * @return The active TradeList.
  4647.      */
  4648.     public TradeList getActiveTradeList()
  4649.     {
  4650.         return _activeTradeList;
  4651.     }
  4652.    
  4653.     public void onTradeStart(L2PcInstance partner)
  4654.     {
  4655.         _activeTradeList = new TradeList(this);
  4656.         _activeTradeList.setPartner(partner);
  4657.        
  4658.         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.BEGIN_TRADE_WITH_S1).addString(partner.getName()));
  4659.         sendPacket(new TradeStart(this));
  4660.     }
  4661.    
  4662.     public void onTradeConfirm(L2PcInstance partner)
  4663.     {
  4664.         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_CONFIRMED_TRADE).addString(partner.getName()));
  4665.        
  4666.         partner.sendPacket(TradePressOwnOk.STATIC_PACKET);
  4667.         sendPacket(TradePressOtherOk.STATIC_PACKET);
  4668.     }
  4669.    
  4670.     public void onTradeCancel(L2PcInstance partner)
  4671.     {
  4672.         if (_activeTradeList == null)
  4673.             return;
  4674.        
  4675.         _activeTradeList.lock();
  4676.         _activeTradeList = null;
  4677.        
  4678.         sendPacket(new SendTradeDone(0));
  4679.         SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.S1_CANCELED_TRADE);
  4680.         msg.addString(partner.getName());
  4681.         sendPacket(msg);
  4682.     }
  4683.    
  4684.     public void onTradeFinish(boolean successfull)
  4685.     {
  4686.         _activeTradeList = null;
  4687.         sendPacket(new SendTradeDone(1));
  4688.         if (successfull)
  4689.             sendPacket(SystemMessageId.TRADE_SUCCESSFUL);
  4690.     }
  4691.    
  4692.     public void startTrade(L2PcInstance partner)
  4693.     {
  4694.         onTradeStart(partner);
  4695.         partner.onTradeStart(this);
  4696.     }
  4697.    
  4698.     public void cancelActiveTrade()
  4699.     {
  4700.         if (_activeTradeList == null)
  4701.             return;
  4702.        
  4703.         L2PcInstance partner = _activeTradeList.getPartner();
  4704.         if (partner != null)
  4705.             partner.onTradeCancel(this);
  4706.        
  4707.         onTradeCancel(this);
  4708.     }
  4709.    
  4710.     /**
  4711.      * @return The _createList object of the L2PcInstance.
  4712.      */
  4713.     public L2ManufactureList getCreateList()
  4714.     {
  4715.         return _createList;
  4716.     }
  4717.    
  4718.     /**
  4719.      * Set the _createList object of the L2PcInstance.
  4720.      * @param list
  4721.      */
  4722.     public void setCreateList(L2ManufactureList list)
  4723.     {
  4724.         _createList = list;
  4725.     }
  4726.    
  4727.     /**
  4728.      * @return The _sellList object of the L2PcInstance.
  4729.      */
  4730.     public TradeList getSellList()
  4731.     {
  4732.         if (_sellList == null)
  4733.             _sellList = new TradeList(this);
  4734.        
  4735.         return _sellList;
  4736.     }
  4737.    
  4738.     /**
  4739.      * @return the _buyList object of the L2PcInstance.
  4740.      */
  4741.     public TradeList getBuyList()
  4742.     {
  4743.         if (_buyList == null)
  4744.             _buyList = new TradeList(this);
  4745.        
  4746.         return _buyList;
  4747.     }
  4748.    
  4749.     /**
  4750.      * Set the Private Store type of the L2PcInstance.
  4751.      * @param type The value : 0 = none, 1 = sell, 2 = sellmanage, 3 = buy, 4 = buymanage, 5 = manufacture.
  4752.      */
  4753.     public void setPrivateStoreType(int type)
  4754.     {
  4755.         _privateStore = type;
  4756.        
  4757.         if (Config.OFFLINE_DISCONNECT_FINISHED && _privateStore == STORE_PRIVATE_NONE && inOfflineShopMode() && (getClient() == null || getClient().isDetached()))
  4758.         {
  4759.             deleteMe();
  4760.         }
  4761.     }
  4762.    
  4763.     /**
  4764.      * @return The Private Store type of the L2PcInstance.
  4765.      */
  4766.     public int getPrivateStoreType()
  4767.     {
  4768.         return _privateStore;
  4769.     }
  4770.    
  4771.     /**
  4772.      * Set the _skillLearningClassId object of the L2PcInstance.
  4773.      * @param classId The parameter.
  4774.      */
  4775.     public void setSkillLearningClassId(ClassId classId)
  4776.     {
  4777.         _skillLearningClassId = classId;
  4778.     }
  4779.    
  4780.     /**
  4781.      * @return The _skillLearningClassId object of the L2PcInstance.
  4782.      */
  4783.     public ClassId getSkillLearningClassId()
  4784.     {
  4785.         return _skillLearningClassId;
  4786.     }
  4787.    
  4788.     /**
  4789.      * Set the _clan object, _clanId, _clanLeader Flag and title of the L2PcInstance.
  4790.      * @param clan The Clan object which is used to feed L2PcInstance values.
  4791.      */
  4792.     public void setClan(L2Clan clan)
  4793.     {
  4794.         _clan = clan;
  4795.         setTitle("");
  4796.        
  4797.         if (clan == null)
  4798.         {
  4799.             _clanId = 0;
  4800.             _clanPrivileges = 0;
  4801.             _pledgeType = 0;
  4802.             _powerGrade = 0;
  4803.             _lvlJoinedAcademy = 0;
  4804.             _apprentice = 0;
  4805.             _sponsor = 0;
  4806.             return;
  4807.         }
  4808.        
  4809.         if (!clan.isMember(getObjectId()))
  4810.         {
  4811.             // char has been kicked from clan
  4812.             setClan(null);
  4813.             return;
  4814.         }
  4815.        
  4816.         _clanId = clan.getClanId();
  4817.     }
  4818.    
  4819.     /**
  4820.      * @return The _clan object of the L2PcInstance.
  4821.      */
  4822.     public L2Clan getClan()
  4823.     {
  4824.         return _clan;
  4825.     }
  4826.    
  4827.     /**
  4828.      * @return True if the L2PcInstance is the leader of its clan.
  4829.      */
  4830.     public boolean isClanLeader()
  4831.     {
  4832.         if (getClan() == null)
  4833.             return false;
  4834.        
  4835.         return getObjectId() == getClan().getLeaderId();
  4836.     }
  4837.    
  4838.     /**
  4839.      * Reduce the number of arrows owned by the L2PcInstance and send it Server->Client Packet InventoryUpdate or ItemList (to unequip if the last arrow was consummed).<BR>
  4840.      * <BR>
  4841.      */
  4842.     @Override
  4843.     protected void reduceArrowCount()
  4844.     {
  4845.         L2ItemInstance arrows = getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
  4846.        
  4847.         if (arrows == null)
  4848.         {
  4849.             getInventory().unEquipItemInSlot(Inventory.PAPERDOLL_LHAND);
  4850.             _arrowItem = null;
  4851.             sendPacket(new ItemList(this, false));
  4852.             return;
  4853.         }
  4854.        
  4855.         // Adjust item quantity
  4856.         if (arrows.getCount() > 1)
  4857.         {
  4858.             synchronized (arrows)
  4859.             {
  4860.                 arrows.changeCountWithoutTrace(-1, this, null);
  4861.                 arrows.setLastChange(L2ItemInstance.MODIFIED);
  4862.                
  4863.                 // could do also without saving, but let's save approx 1 of 10
  4864.                 if (GameTimeController.getGameTicks() % 10 == 0)
  4865.                     arrows.updateDatabase();
  4866.                 _inventory.refreshWeight();
  4867.             }
  4868.         }
  4869.         else
  4870.         {
  4871.             // Destroy entire item and save to database
  4872.             _inventory.destroyItem("Consume", arrows, this, null);
  4873.            
  4874.             getInventory().unEquipItemInSlot(Inventory.PAPERDOLL_LHAND);
  4875.             _arrowItem = null;
  4876.            
  4877.             if (Config.DEBUG)
  4878.                 _log.fine("removed arrows count");
  4879.            
  4880.             sendPacket(new ItemList(this, false));
  4881.             return;
  4882.         }
  4883.        
  4884.         InventoryUpdate iu = new InventoryUpdate();
  4885.         iu.addModifiedItem(arrows);
  4886.         sendPacket(iu);
  4887.     }
  4888.    
  4889.     /**
  4890.      * Equip arrows needed in left hand and send ItemList to the L2PcINstance then return True.<BR>
  4891.      * <BR>
  4892.      */
  4893.     @Override
  4894.     protected boolean checkAndEquipArrows()
  4895.     {
  4896.         // Check if nothing is equipped in left hand
  4897.         if (getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND) == null)
  4898.         {
  4899.             // Get the L2ItemInstance of the arrows needed for this bow
  4900.             _arrowItem = getInventory().findArrowForBow(getActiveWeaponItem());
  4901.            
  4902.             if (_arrowItem != null)
  4903.             {
  4904.                 // Equip arrows needed in left hand
  4905.                 getInventory().setPaperdollItem(Inventory.PAPERDOLL_LHAND, _arrowItem);
  4906.                
  4907.                 // Send ItemList to this L2PcINstance to update left hand equipement
  4908.                 ItemList il = new ItemList(this, false);
  4909.                 sendPacket(il);
  4910.             }
  4911.         }
  4912.         else
  4913.         {
  4914.             // Get the L2ItemInstance of arrows equipped in left hand
  4915.             _arrowItem = getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
  4916.         }
  4917.        
  4918.         return _arrowItem != null;
  4919.     }
  4920.    
  4921.     /**
  4922.      * Disarm the player's weapon and shield.
  4923.      * @return true if successful, false otherwise.
  4924.      */
  4925.     public boolean disarmWeapons()
  4926.     {
  4927.         // Don't allow disarming a cursed weapon
  4928.         if (isCursedWeaponEquipped())
  4929.             return false;
  4930.        
  4931.         // Unequip the weapon
  4932.         L2ItemInstance wpn = getInventory().getPaperdollItem(Inventory.PAPERDOLL_RHAND);
  4933.         if (wpn != null)
  4934.         {
  4935.             L2ItemInstance[] unequipped = getInventory().unEquipItemInBodySlotAndRecord(wpn.getItem().getBodyPart());
  4936.             InventoryUpdate iu = new InventoryUpdate();
  4937.             for (L2ItemInstance itm : unequipped)
  4938.                 iu.addModifiedItem(itm);
  4939.             sendPacket(iu);
  4940.            
  4941.             abortAttack();
  4942.             broadcastUserInfo();
  4943.            
  4944.             // this can be 0 if the user pressed the right mousebutton twice very fast
  4945.             if (unequipped.length > 0)
  4946.             {
  4947.                 SystemMessage sm;
  4948.                 if (unequipped[0].getEnchantLevel() > 0)
  4949.                     sm = SystemMessage.getSystemMessage(SystemMessageId.EQUIPMENT_S1_S2_REMOVED).addNumber(unequipped[0].getEnchantLevel()).addItemName(unequipped[0]);
  4950.                 else
  4951.                     sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISARMED).addItemName(unequipped[0]);
  4952.                
  4953.                 sendPacket(sm);
  4954.             }
  4955.         }
  4956.        
  4957.         // Unequip the shield
  4958.         L2ItemInstance sld = getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
  4959.         if (sld != null)
  4960.         {
  4961.             L2ItemInstance[] unequipped = getInventory().unEquipItemInBodySlotAndRecord(sld.getItem().getBodyPart());
  4962.             InventoryUpdate iu = new InventoryUpdate();
  4963.             for (L2ItemInstance itm : unequipped)
  4964.                 iu.addModifiedItem(itm);
  4965.             sendPacket(iu);
  4966.            
  4967.             abortAttack();
  4968.             broadcastUserInfo();
  4969.            
  4970.             // this can be 0 if the user pressed the right mousebutton twice very fast
  4971.             if (unequipped.length > 0)
  4972.             {
  4973.                 SystemMessage sm;
  4974.                 if (unequipped[0].getEnchantLevel() > 0)
  4975.                     sm = SystemMessage.getSystemMessage(SystemMessageId.EQUIPMENT_S1_S2_REMOVED).addNumber(unequipped[0].getEnchantLevel()).addItemName(unequipped[0]);
  4976.                 else
  4977.                     sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISARMED).addItemName(unequipped[0]);
  4978.                
  4979.                 sendPacket(sm);
  4980.             }
  4981.         }
  4982.         return true;
  4983.     }
  4984.    
  4985.     public boolean mount(L2Summon pet)
  4986.     {
  4987.         if (!disarmWeapons())
  4988.             return false;
  4989.        
  4990.         stopAllToggles();
  4991.         Ride mount = new Ride(getObjectId(), Ride.ACTION_MOUNT, pet.getTemplate().getNpcId());
  4992.         setMount(pet.getNpcId(), pet.getLevel(), mount.getMountType());
  4993.         setMountObjectID(pet.getControlItemId());
  4994.         clearPetData();
  4995.         startFeed(pet.getNpcId());
  4996.         broadcastPacket(mount);
  4997.        
  4998.         // Notify self and others about speed change
  4999.         broadcastUserInfo();
  5000.        
  5001.         pet.unSummon(this);
  5002.         return true;
  5003.     }
  5004.    
  5005.     public boolean mount(int npcId, int controlItemId, boolean useFood)
  5006.     {
  5007.         if (!disarmWeapons())
  5008.             return false;
  5009.        
  5010.         stopAllToggles();
  5011.         Ride mount = new Ride(getObjectId(), Ride.ACTION_MOUNT, npcId);
  5012.         if (setMount(npcId, getLevel(), mount.getMountType()))
  5013.         {
  5014.             clearPetData();
  5015.             setMountObjectID(controlItemId);
  5016.             broadcastPacket(mount);
  5017.            
  5018.             // Notify self and others about speed change
  5019.             broadcastUserInfo();
  5020.            
  5021.             if (useFood)
  5022.                 startFeed(npcId);
  5023.            
  5024.             return true;
  5025.         }
  5026.         return false;
  5027.     }
  5028.    
  5029.     public boolean mountPlayer(L2Summon summon)
  5030.     {
  5031.         if (summon != null && summon.isMountable() && !isMounted() && !isBetrayed())
  5032.         {
  5033.             if (isDead()) // A strider cannot be ridden when dead.
  5034.             {
  5035.                 sendPacket(SystemMessageId.STRIDER_CANT_BE_RIDDEN_WHILE_DEAD);
  5036.                 return false;
  5037.             }
  5038.            
  5039.             if (summon.isDead()) // A dead strider cannot be ridden.
  5040.             {
  5041.                 sendPacket(SystemMessageId.DEAD_STRIDER_CANT_BE_RIDDEN);
  5042.                 return false;
  5043.             }
  5044.            
  5045.             if (summon.isInCombat() || summon.isRooted()) // A strider in battle cannot be ridden.
  5046.             {
  5047.                 sendPacket(SystemMessageId.STRIDER_IN_BATLLE_CANT_BE_RIDDEN);
  5048.                 return false;
  5049.             }
  5050.            
  5051.             if (isInCombat()) // A strider cannot be ridden while in battle
  5052.             {
  5053.                 sendPacket(SystemMessageId.STRIDER_CANT_BE_RIDDEN_WHILE_IN_BATTLE);
  5054.                 return false;
  5055.             }
  5056.            
  5057.             if (isSitting()) // A strider can be ridden only when standing
  5058.             {
  5059.                 sendPacket(SystemMessageId.STRIDER_CAN_BE_RIDDEN_ONLY_WHILE_STANDING);
  5060.                 return false;
  5061.             }
  5062.            
  5063.             if (isFishing()) // You can't mount, dismount, break and drop items while fishing
  5064.             {
  5065.                 sendPacket(SystemMessageId.CANNOT_DO_WHILE_FISHING_2);
  5066.                 return false;
  5067.             }
  5068.            
  5069.             if (isCursedWeaponEquipped()) // You can't mount, dismount, break and drop items while weilding a cursed weapon
  5070.             {
  5071.                 sendPacket(SystemMessageId.STRIDER_CANT_BE_RIDDEN_WHILE_IN_BATTLE);
  5072.                 return false;
  5073.             }
  5074.            
  5075.             if (!Util.checkIfInRange(200, this, summon, true))
  5076.             {
  5077.                 sendPacket(SystemMessageId.TOO_FAR_AWAY_FROM_STRIDER_TO_MOUNT);
  5078.                 return false;
  5079.             }
  5080.            
  5081.             if (summon.isHungry())
  5082.             {
  5083.                 sendPacket(SystemMessageId.HUNGRY_STRIDER_NOT_MOUNT);
  5084.                 return false;
  5085.             }
  5086.            
  5087.             if (!summon.isDead() && !isMounted())
  5088.                 mount(summon);
  5089.         }
  5090.         else if (isMounted())
  5091.         {
  5092.             if (getMountType() == 2 && isInsideZone(ZoneId.NO_LANDING))
  5093.             {
  5094.                 sendPacket(SystemMessageId.NO_DISMOUNT_HERE);
  5095.                 return false;
  5096.             }
  5097.            
  5098.             if (isHungry())
  5099.             {
  5100.                 sendPacket(SystemMessageId.HUNGRY_STRIDER_NOT_MOUNT);
  5101.                 return false;
  5102.             }
  5103.            
  5104.             dismount();
  5105.         }
  5106.         return true;
  5107.     }
  5108.    
  5109.     public boolean dismount()
  5110.     {
  5111.         sendPacket(new SetupGauge(3, 0, 0));
  5112.         int petId = _mountNpcId;
  5113.         if (setMount(0, 0, 0))
  5114.         {
  5115.             stopFeed();
  5116.             clearPetData();
  5117.            
  5118.             broadcastPacket(new Ride(getObjectId(), Ride.ACTION_DISMOUNT, 0));
  5119.            
  5120.             setMountObjectID(0);
  5121.             storePetFood(petId);
  5122.            
  5123.             // Notify self and others about speed change
  5124.             broadcastUserInfo();
  5125.             return true;
  5126.         }
  5127.         return false;
  5128.     }
  5129.    
  5130.     public void storePetFood(int petId)
  5131.     {
  5132.         if (_controlItemId != 0 && petId != 0)
  5133.         {
  5134.             try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5135.             {
  5136.                 PreparedStatement statement = con.prepareStatement("UPDATE pets SET fed=? WHERE item_obj_id = ?");
  5137.                 statement.setInt(1, getCurrentFeed());
  5138.                 statement.setInt(2, _controlItemId);
  5139.                 statement.executeUpdate();
  5140.                 statement.close();
  5141.                 _controlItemId = 0;
  5142.             }
  5143.             catch (Exception e)
  5144.             {
  5145.                 _log.log(Level.SEVERE, "Failed to store Pet [NpcId: " + petId + "] data", e);
  5146.             }
  5147.         }
  5148.     }
  5149.    
  5150.     protected class FeedTask implements Runnable
  5151.     {
  5152.         @Override
  5153.         public void run()
  5154.         {
  5155.             try
  5156.             {
  5157.                 if (!isMounted())
  5158.                 {
  5159.                     stopFeed();
  5160.                     return;
  5161.                 }
  5162.                
  5163.                 if (getCurrentFeed() > getFeedConsume())
  5164.                 {
  5165.                     // eat
  5166.                     setCurrentFeed(getCurrentFeed() - getFeedConsume());
  5167.                 }
  5168.                 else
  5169.                 {
  5170.                     // go back to pet control item, or simply said, unsummon it
  5171.                     setCurrentFeed(0);
  5172.                     stopFeed();
  5173.                     dismount();
  5174.                     sendPacket(SystemMessageId.OUT_OF_FEED_MOUNT_CANCELED);
  5175.                 }
  5176.                
  5177.                 int[] foodIds = getPetData(getMountNpcId()).getFood();
  5178.                 if (foodIds.length == 0)
  5179.                     return;
  5180.                
  5181.                 L2ItemInstance food = null;
  5182.                 for (int id : foodIds)
  5183.                 {
  5184.                     food = getInventory().getItemByItemId(id);
  5185.                     if (food != null)
  5186.                         break;
  5187.                 }
  5188.                
  5189.                 if (food != null && isHungry())
  5190.                 {
  5191.                     IItemHandler handler = ItemHandler.getInstance().getItemHandler(food.getEtcItem());
  5192.                     if (handler != null)
  5193.                     {
  5194.                         handler.useItem(L2PcInstance.this, food, false);
  5195.                         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.PET_TOOK_S1_BECAUSE_HE_WAS_HUNGRY).addItemName(food));
  5196.                     }
  5197.                 }
  5198.             }
  5199.             catch (Exception e)
  5200.             {
  5201.                 _log.log(Level.SEVERE, "Mounted Pet [NpcId: " + getMountNpcId() + "] a feed task error has occurred", e);
  5202.             }
  5203.         }
  5204.     }
  5205.    
  5206.     protected synchronized void startFeed(int npcId)
  5207.     {
  5208.         _canFeed = npcId > 0;
  5209.         if (!isMounted())
  5210.             return;
  5211.        
  5212.         if (getPet() != null)
  5213.         {
  5214.             setCurrentFeed(((L2PetInstance) getPet()).getCurrentFed());
  5215.             _controlItemId = getPet().getControlItemId();
  5216.             sendPacket(new SetupGauge(3, getCurrentFeed() * 10000 / getFeedConsume(), getMaxFeed() * 10000 / getFeedConsume()));
  5217.             if (!isDead())
  5218.                 _mountFeedTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FeedTask(), 10000, 10000);
  5219.         }
  5220.         else if (_canFeed)
  5221.         {
  5222.             setCurrentFeed(getMaxFeed());
  5223.             sendPacket(new SetupGauge(3, getCurrentFeed() * 10000 / getFeedConsume(), getMaxFeed() * 10000 / getFeedConsume()));
  5224.             if (!isDead())
  5225.                 _mountFeedTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FeedTask(), 10000, 10000);
  5226.         }
  5227.     }
  5228.    
  5229.     protected synchronized void stopFeed()
  5230.     {
  5231.         if (_mountFeedTask != null)
  5232.         {
  5233.             _mountFeedTask.cancel(false);
  5234.             _mountFeedTask = null;
  5235.            
  5236.             if (Config.DEBUG)
  5237.                 _log.fine("Pet [#" + _mountNpcId + "] feed task stop");
  5238.         }
  5239.     }
  5240.    
  5241.     private final void clearPetData()
  5242.     {
  5243.         _data = null;
  5244.     }
  5245.    
  5246.     protected final L2PetData getPetData(int npcId)
  5247.     {
  5248.         if (_data == null)
  5249.             _data = PetDataTable.getInstance().getPetData(npcId);
  5250.         return _data;
  5251.     }
  5252.    
  5253.     private final L2PetLevelData getPetLevelData(int npcId)
  5254.     {
  5255.         if (_leveldata == null)
  5256.             _leveldata = PetDataTable.getInstance().getPetData(npcId).getPetLevelData(getMountLevel());
  5257.         return _leveldata;
  5258.     }
  5259.    
  5260.     public int getCurrentFeed()
  5261.     {
  5262.         return _curFeed;
  5263.     }
  5264.    
  5265.     protected int getFeedConsume()
  5266.     {
  5267.         return (isAttackingNow()) ? getPetLevelData(_mountNpcId).getPetFeedBattle() : getPetLevelData(_mountNpcId).getPetFeedNormal();
  5268.     }
  5269.    
  5270.     public void setCurrentFeed(int num)
  5271.     {
  5272.         _curFeed = (num > getMaxFeed()) ? getMaxFeed() : num;
  5273.         sendPacket(new SetupGauge(3, getCurrentFeed() * 10000 / getFeedConsume(), getMaxFeed() * 10000 / getFeedConsume()));
  5274.     }
  5275.    
  5276.     private int getMaxFeed()
  5277.     {
  5278.         return getPetLevelData(_mountNpcId).getPetMaxFeed();
  5279.     }
  5280.    
  5281.     protected boolean isHungry()
  5282.     {
  5283.         return _canFeed ? (getCurrentFeed() < (getPetLevelData(getMountNpcId()).getPetMaxFeed() * 0.55)) : false;
  5284.     }
  5285.    
  5286.     /**
  5287.      * @return the type of attack, depending of the worn weapon.
  5288.      */
  5289.     @Override
  5290.     public L2WeaponType getAttackType()
  5291.     {
  5292.         final L2Weapon weapon = getActiveWeaponItem();
  5293.         if (weapon != null)
  5294.             return weapon.getItemType();
  5295.        
  5296.         return L2WeaponType.FIST;
  5297.     }
  5298.    
  5299.     public void setUptime(long time)
  5300.     {
  5301.         _uptime = time;
  5302.     }
  5303.    
  5304.     public long getUptime()
  5305.     {
  5306.         return System.currentTimeMillis() - _uptime;
  5307.     }
  5308.    
  5309.     /**
  5310.      * Return True if the L2PcInstance is invulnerable.
  5311.      */
  5312.     @Override
  5313.     public boolean isInvul()
  5314.     {
  5315.         return super.isInvul() || _protectEndTime > GameTimeController.getGameTicks();
  5316.     }
  5317.    
  5318.     /**
  5319.      * Return True if the L2PcInstance has a Party in progress.
  5320.      */
  5321.     @Override
  5322.     public boolean isInParty()
  5323.     {
  5324.         return _party != null;
  5325.     }
  5326.    
  5327.     /**
  5328.      * Set the _party object of the L2PcInstance (without joining it).
  5329.      * @param party The object.
  5330.      */
  5331.     public void setParty(L2Party party)
  5332.     {
  5333.         _party = party;
  5334.     }
  5335.    
  5336.     /**
  5337.      * Set the _party object of the L2PcInstance AND join it.
  5338.      * @param party
  5339.      */
  5340.     public void joinParty(L2Party party)
  5341.     {
  5342.         if (party != null)
  5343.         {
  5344.             _party = party;
  5345.             party.addPartyMember(this);
  5346.         }
  5347.     }
  5348.    
  5349.     /**
  5350.      * Manage the Leave Party task of the L2PcInstance.
  5351.      */
  5352.     public void leaveParty()
  5353.     {
  5354.         if (isInParty())
  5355.         {
  5356.             _party.removePartyMember(this);
  5357.             _party = null;
  5358.         }
  5359.     }
  5360.    
  5361.     /**
  5362.      * Return the _party object of the L2PcInstance.
  5363.      */
  5364.     @Override
  5365.     public L2Party getParty()
  5366.     {
  5367.         return _party;
  5368.     }
  5369.    
  5370.     /**
  5371.      * Return True if the L2PcInstance is a GM.
  5372.      */
  5373.     @Override
  5374.     public boolean isGM()
  5375.     {
  5376.         return getAccessLevel().isGm();
  5377.     }
  5378.    
  5379.     /**
  5380.      * Set the _accessLevel of the L2PcInstance.
  5381.      * @param level
  5382.      */
  5383.     public void setAccessLevel(int level)
  5384.     {
  5385.         if (level == AccessLevels._masterAccessLevelNum)
  5386.         {
  5387.             _log.warning(getName() + " has logged in with Master access level.");
  5388.             _accessLevel = AccessLevels._masterAccessLevel;
  5389.         }
  5390.         else if (level == AccessLevels._userAccessLevelNum)
  5391.             _accessLevel = AccessLevels._userAccessLevel;
  5392.         else
  5393.         {
  5394.             L2AccessLevel accessLevel = AccessLevels.getInstance().getAccessLevel(level);
  5395.            
  5396.             if (accessLevel == null)
  5397.             {
  5398.                 if (level < 0)
  5399.                 {
  5400.                     AccessLevels.getInstance().addBanAccessLevel(level);
  5401.                     _accessLevel = AccessLevels.getInstance().getAccessLevel(level);
  5402.                 }
  5403.                 else
  5404.                 {
  5405.                     _log.warning("Server tried to set unregistered access level " + level + " to " + getName() + ". His access level have been reseted to user level.");
  5406.                     _accessLevel = AccessLevels._userAccessLevel;
  5407.                 }
  5408.             }
  5409.             else
  5410.             {
  5411.                 _accessLevel = accessLevel;
  5412.                 setTitle(_accessLevel.getName());
  5413.             }
  5414.         }
  5415.        
  5416.         getAppearance().setNameColor(_accessLevel.getNameColor());
  5417.         getAppearance().setTitleColor(_accessLevel.getTitleColor());
  5418.         broadcastUserInfo();
  5419.        
  5420.         CharNameTable.getInstance().addName(this);
  5421.     }
  5422.    
  5423.     public void setAccountAccesslevel(int level)
  5424.     {
  5425.     //  LoginServerThread.getInstance().sendAccessLevel(getAccountName(), level);
  5426.     }
  5427.    
  5428.     /**
  5429.      * @return the _accessLevel of the L2PcInstance.
  5430.      */
  5431.     public L2AccessLevel getAccessLevel()
  5432.     {
  5433.         if (Config.EVERYBODY_HAS_ADMIN_RIGHTS)
  5434.             return AccessLevels._masterAccessLevel;
  5435.         else if (_accessLevel == null) /* This is here because inventory etc. is loaded before access level on login, so it is not null */
  5436.             setAccessLevel(AccessLevels._userAccessLevelNum);
  5437.        
  5438.         return _accessLevel;
  5439.     }
  5440.    
  5441.     /**
  5442.      * Update Stats of the L2PcInstance client side by sending Server->Client packet UserInfo/StatusUpdate to this L2PcInstance and CharInfo/StatusUpdate to all L2PcInstance in its _KnownPlayers (broadcast).
  5443.      * @param broadcastType
  5444.      */
  5445.     public void updateAndBroadcastStatus(int broadcastType)
  5446.     {
  5447.         refreshOverloaded();
  5448.         refreshExpertisePenalty();
  5449.        
  5450.         if (broadcastType == 1)
  5451.             sendPacket(new UserInfo(this));
  5452.         else if (broadcastType == 2)
  5453.             broadcastUserInfo();
  5454.     }
  5455.    
  5456.     /**
  5457.      * Send a Server->Client StatusUpdate packet with Karma to the L2PcInstance and all L2PcInstance to inform (broadcast).
  5458.      */
  5459.     public void broadcastKarma()
  5460.     {
  5461.         StatusUpdate su = new StatusUpdate(this);
  5462.         su.addAttribute(StatusUpdate.KARMA, getKarma());
  5463.         sendPacket(su);
  5464.        
  5465.         if (getPet() != null)
  5466.             sendPacket(new RelationChanged(getPet(), getRelation(this), false));
  5467.        
  5468.         broadcastRelationsChanges();
  5469.     }
  5470.    
  5471.     /**
  5472.      * Set the online Flag to True or False and update the characters table of the database with online status and lastAccess (called when login and logout).
  5473.      * @param isOnline
  5474.      * @param updateInDb
  5475.      */
  5476.     public void setOnlineStatus(boolean isOnline, boolean updateInDb)
  5477.     {
  5478.         if (_isOnline != isOnline)
  5479.             _isOnline = isOnline;
  5480.        
  5481.         // Update the characters table of the database with online status and lastAccess (called when login and logout)
  5482.         if (updateInDb)
  5483.             updateOnlineStatus();
  5484.     }
  5485.    
  5486.     public void setIsIn7sDungeon(boolean isIn7sDungeon)
  5487.     {
  5488.         _isIn7sDungeon = isIn7sDungeon;
  5489.     }
  5490.    
  5491.     /**
  5492.      * Update the characters table of the database with online status and lastAccess of this L2PcInstance (called when login and logout).
  5493.      */
  5494.     public void updateOnlineStatus()
  5495.     {
  5496.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5497.         {
  5498.             PreparedStatement statement = con.prepareStatement("UPDATE characters SET online=?, lastAccess=? WHERE obj_id=?");
  5499.             statement.setInt(1, isOnlineInt());
  5500.             statement.setLong(2, System.currentTimeMillis());
  5501.             statement.setInt(3, getObjectId());
  5502.             statement.execute();
  5503.             statement.close();
  5504.         }
  5505.         catch (Exception e)
  5506.         {
  5507.             _log.warning("could not set char online status:" + e);
  5508.         }
  5509.     }
  5510.    
  5511.     /**
  5512.      * Create a new player in the characters table of the database.
  5513.      * @return true if successful.
  5514.      */
  5515.     private boolean createDb()
  5516.     {
  5517.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5518.         {
  5519.             PreparedStatement statement = con.prepareStatement(INSERT_CHARACTER);
  5520.             statement.setString(1, _accountName);
  5521.             statement.setInt(2, getObjectId());
  5522.             statement.setString(3, getName());
  5523.             statement.setInt(4, getLevel());
  5524.             statement.setInt(5, getMaxHp());
  5525.             statement.setDouble(6, getCurrentHp());
  5526.             statement.setInt(7, getMaxCp());
  5527.             statement.setDouble(8, getCurrentCp());
  5528.             statement.setInt(9, getMaxMp());
  5529.             statement.setDouble(10, getCurrentMp());
  5530.             statement.setInt(11, getAppearance().getFace());
  5531.             statement.setInt(12, getAppearance().getHairStyle());
  5532.             statement.setInt(13, getAppearance().getHairColor());
  5533.             statement.setInt(14, getAppearance().getSex() ? 1 : 0);
  5534.             statement.setLong(15, getExp());
  5535.             statement.setInt(16, getSp());
  5536.             statement.setInt(17, getKarma());
  5537.             statement.setInt(18, getPvpKills());
  5538.             statement.setInt(19, getPkKills());
  5539.             statement.setInt(20, getClanId());
  5540.             statement.setInt(21, getRace().ordinal());
  5541.             statement.setInt(22, getClassId().getId());
  5542.             statement.setLong(23, getDeleteTimer());
  5543.             statement.setInt(24, hasDwarvenCraft() ? 1 : 0);
  5544.             statement.setString(25, getTitle());
  5545.             statement.setInt(26, getAccessLevel().getLevel());
  5546.             statement.setInt(27, isOnlineInt());
  5547.             statement.setInt(28, isIn7sDungeon() ? 1 : 0);
  5548.             statement.setInt(29, getClanPrivileges());
  5549.             statement.setInt(30, wantsPeace() ? 1 : 0);
  5550.             statement.setInt(31, getBaseClass());
  5551.             statement.setInt(32, isNoble() ? 1 : 0);
  5552.             statement.setLong(33, 0);
  5553.             statement.setLong(34, System.currentTimeMillis());
  5554.             statement.executeUpdate();
  5555.             statement.close();
  5556.         }
  5557.         catch (Exception e)
  5558.         {
  5559.             _log.severe("Could not insert char data: " + e);
  5560.             return false;
  5561.         }
  5562.         return true;
  5563.     }
  5564.    
  5565.     /**
  5566.      * Retrieve a L2PcInstance from the characters table of the database and add it in _allObjects of the L2world.<BR>
  5567.      * <BR>
  5568.      * <B><U> Actions</U> :</B><BR>
  5569.      * <BR>
  5570.      * <li>Retrieve the L2PcInstance from the characters table of the database</li> <li>Add the L2PcInstance object in _allObjects</li> <li>Set the x,y,z position of the L2PcInstance and make it invisible</li> <li>Update the overloaded status of the L2PcInstance</li><BR>
  5571.      * <BR>
  5572.      * @param objectId Identifier of the object to initialized
  5573.      * @return The L2PcInstance loaded from the database
  5574.      */
  5575.     public static L2PcInstance restore(int objectId)
  5576.     {
  5577.         L2PcInstance player = null;
  5578.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5579.         {
  5580.             PreparedStatement statement = con.prepareStatement(RESTORE_CHARACTER);
  5581.             statement.setInt(1, objectId);
  5582.             ResultSet rset = statement.executeQuery();
  5583.            
  5584.             while (rset.next())
  5585.             {
  5586.                 final int activeClassId = rset.getInt("classid");
  5587.                 final L2PcTemplate template = CharTemplateTable.getInstance().getTemplate(activeClassId);
  5588.                 final PcAppearance app = new PcAppearance(rset.getByte("face"), rset.getByte("hairColor"), rset.getByte("hairStyle"), rset.getInt("sex") != 0);
  5589.                
  5590.                 player = new L2PcInstance(objectId, template, rset.getString("account_name"), app);
  5591.                 player.setName(rset.getString("char_name"));
  5592.                 player._lastAccess = rset.getLong("lastAccess");
  5593.                
  5594.                 player.getStat().setExp(rset.getLong("exp"));
  5595.                 player.setExpBeforeDeath(rset.getLong("expBeforeDeath"));
  5596.                 player.getStat().setLevel(rset.getByte("level"));
  5597.                 player.getStat().setSp(rset.getInt("sp"));
  5598.                
  5599.                 player.setWantsPeace(rset.getInt("wantspeace") == 1);
  5600.                
  5601.                 player.setHeading(rset.getInt("heading"));
  5602.                
  5603.                 player.setKarma(rset.getInt("karma"));
  5604.                 player.setPvpKills(rset.getInt("pvpkills"));
  5605.                 player.setPkKills(rset.getInt("pkkills"));
  5606.                 player.setOnlineTime(rset.getLong("onlinetime"));
  5607.                 player.setNoble(rset.getInt("nobless") == 1, false);
  5608.                
  5609.                 player.setClanJoinExpiryTime(rset.getLong("clan_join_expiry_time"));
  5610.                 if (player.getClanJoinExpiryTime() < System.currentTimeMillis())
  5611.                     player.setClanJoinExpiryTime(0);
  5612.                
  5613.                 player.setClanCreateExpiryTime(rset.getLong("clan_create_expiry_time"));
  5614.                 if (player.getClanCreateExpiryTime() < System.currentTimeMillis())
  5615.                     player.setClanCreateExpiryTime(0);
  5616.                
  5617.                 player.setPowerGrade((int) rset.getLong("power_grade"));
  5618.                 player.setPledgeType(rset.getInt("subpledge"));
  5619.                 player.setLastRecomUpdate(rset.getLong("last_recom_date"));
  5620.                
  5621.                 int clanId = rset.getInt("clanid");
  5622.                 if (clanId > 0)
  5623.                     player.setClan(ClanTable.getInstance().getClan(clanId));
  5624.                
  5625.                 if (player.getClan() != null)
  5626.                 {
  5627.                     if (player.getClan().getLeaderId() != player.getObjectId())
  5628.                     {
  5629.                         if (player.getPowerGrade() == 0)
  5630.                             player.setPowerGrade(5);
  5631.                        
  5632.                         player.setClanPrivileges(player.getClan().getRankPrivs(player.getPowerGrade()));
  5633.                     }
  5634.                     else
  5635.                     {
  5636.                         player.setClanPrivileges(L2Clan.CP_ALL);
  5637.                         player.setPowerGrade(1);
  5638.                     }
  5639.                 }
  5640.                 else
  5641.                     player.setClanPrivileges(L2Clan.CP_NOTHING);
  5642.                
  5643.                 player.setPledgeClass(L2ClanMember.calculatePledgeClass(player));
  5644.                 player.setDeleteTimer(rset.getLong("deletetime"));
  5645.                
  5646.                 player.setTitle(rset.getString("title"));
  5647.                 player.setAccessLevel(rset.getInt("accesslevel"));
  5648.                 player.setFistsWeaponItem(findFistsWeaponItem(activeClassId));
  5649.                 player.setUptime(System.currentTimeMillis());
  5650.                
  5651.                 // Check recs
  5652.                 player.checkRecom(rset.getInt("rec_have"), rset.getInt("rec_left"));
  5653.                
  5654.                 player._classIndex = 0;
  5655.                 try
  5656.                 {
  5657.                     player.setBaseClass(rset.getInt("base_class"));
  5658.                 }
  5659.                 catch (Exception e)
  5660.                 {
  5661.                     player.setBaseClass(activeClassId);
  5662.                 }
  5663.                
  5664.                 // Restore Subclass Data (cannot be done earlier in function)
  5665.                 if (restoreSubClassData(player))
  5666.                 {
  5667.                     if (activeClassId != player.getBaseClass())
  5668.                     {
  5669.                         for (SubClass subClass : player.getSubClasses().values())
  5670.                             if (subClass.getClassId() == activeClassId)
  5671.                                 player._classIndex = subClass.getClassIndex();
  5672.                     }
  5673.                 }
  5674.                
  5675.                 player.setApprentice(rset.getInt("apprentice"));
  5676.                 player.setSponsor(rset.getInt("sponsor"));
  5677.                 player.setLvlJoinedAcademy(rset.getInt("lvl_joined_academy"));
  5678.                 player.setIsIn7sDungeon(rset.getInt("isin7sdungeon") == 1);
  5679.                 player.setPunishLevel(rset.getInt("punish_level"));
  5680.                 if (player.getPunishLevel() != PunishLevel.NONE)
  5681.                     player.setPunishTimer(rset.getLong("punish_timer"));
  5682.                 else
  5683.                     player.setPunishTimer(0);
  5684.                
  5685.                 CursedWeaponsManager.getInstance().checkPlayer(player);
  5686.                
  5687.                 player.setAllianceWithVarkaKetra(rset.getInt("varka_ketra_ally"));
  5688.                
  5689.                 player.setVoteBuff(rset.getInt("votebuff") == 1 ? true : false);
  5690.                 player.setVoteBuffEndTime(rset.getLong("vote_end_buff"));
  5691.  
  5692.                 player.setDeathPenaltyBuffLevel(rset.getInt("death_penalty_level"));
  5693.                
  5694.                 // Set the x,y,z position of the L2PcInstance and make it invisible
  5695.                 player.setXYZInvisible(rset.getInt("x"), rset.getInt("y"), rset.getInt("z"));
  5696.                
  5697.                 // Set Hero status if it applies
  5698.                 if (Hero.getInstance().isActiveHero(objectId))
  5699.                     player.setHero(true);
  5700.                
  5701.                 // Retrieve from the database all secondary data of this L2PcInstance and reward expertise/lucky skills if necessary.
  5702.                 // Note that Clan, Noblesse and Hero skills are given separately and not here.
  5703.                 player.restoreCharData();
  5704.                 player.rewardSkills();
  5705.                
  5706.                 // buff and status icons
  5707.                 if (Config.STORE_SKILL_COOLTIME)
  5708.                     player.restoreEffects();
  5709.                
  5710.                 // Restore current CP, HP and MP values
  5711.                 final double currentHp = rset.getDouble("curHp");
  5712.                
  5713.                 player.setCurrentCp(rset.getDouble("curCp"));
  5714.                 player.setCurrentHp(currentHp);
  5715.                 player.setCurrentMp(rset.getDouble("curMp"));
  5716.                
  5717.                 if (currentHp < 0.5)
  5718.                 {
  5719.                     player.setIsDead(true);
  5720.                     player.stopHpMpRegeneration();
  5721.                 }
  5722.                
  5723.                 // Restore pet if exists in the world
  5724.                 player.setPet(L2World.getInstance().getPet(player.getObjectId()));
  5725.                 if (player.getPet() != null)
  5726.                     player.getPet().setOwner(player);
  5727.                
  5728.                 player.refreshOverloaded();
  5729.                 player.refreshExpertisePenalty();
  5730.                
  5731.                 player.restoreFriendList();
  5732.                
  5733.                 // Retrieve the name and ID of the other characters assigned to this account.
  5734.                 PreparedStatement stmt = con.prepareStatement("SELECT obj_Id, char_name FROM characters WHERE account_name=? AND obj_Id<>?");
  5735.                 stmt.setString(1, player._accountName);
  5736.                 stmt.setInt(2, objectId);
  5737.                 ResultSet chars = stmt.executeQuery();
  5738.                
  5739.                 while (chars.next())
  5740.                     player._chars.put(chars.getInt("obj_Id"), chars.getString("char_name"));
  5741.                
  5742.                 chars.close();
  5743.                 stmt.close();
  5744.                 break;
  5745.             }
  5746.            
  5747.             rset.close();
  5748.             statement.close();
  5749.         }
  5750.         catch (Exception e)
  5751.         {
  5752.             _log.severe("Could not restore char data: " + e);
  5753.         }
  5754.        
  5755.         return player;
  5756.     }
  5757.    
  5758.     /**
  5759.      * @return
  5760.      */
  5761.     public Forum getMail()
  5762.     {
  5763.         if (_forumMail == null)
  5764.         {
  5765.             setMail(ForumsBBSManager.getInstance().getForumByName("MailRoot").getChildByName(getName()));
  5766.            
  5767.             if (_forumMail == null)
  5768.             {
  5769.                 ForumsBBSManager.getInstance().createNewForum(getName(), ForumsBBSManager.getInstance().getForumByName("MailRoot"), Forum.MAIL, Forum.OWNERONLY, getObjectId());
  5770.                 setMail(ForumsBBSManager.getInstance().getForumByName("MailRoot").getChildByName(getName()));
  5771.             }
  5772.         }
  5773.        
  5774.         return _forumMail;
  5775.     }
  5776.    
  5777.     /**
  5778.      * @param forum
  5779.      */
  5780.     public void setMail(Forum forum)
  5781.     {
  5782.         _forumMail = forum;
  5783.     }
  5784.    
  5785.     /**
  5786.      * @return
  5787.      */
  5788.     public Forum getMemo()
  5789.     {
  5790.         if (_forumMemo == null)
  5791.         {
  5792.             setMemo(ForumsBBSManager.getInstance().getForumByName("MemoRoot").getChildByName(_accountName));
  5793.            
  5794.             if (_forumMemo == null)
  5795.             {
  5796.                 ForumsBBSManager.getInstance().createNewForum(_accountName, ForumsBBSManager.getInstance().getForumByName("MemoRoot"), Forum.MEMO, Forum.OWNERONLY, getObjectId());
  5797.                 setMemo(ForumsBBSManager.getInstance().getForumByName("MemoRoot").getChildByName(_accountName));
  5798.             }
  5799.         }
  5800.        
  5801.         return _forumMemo;
  5802.     }
  5803.    
  5804.     /**
  5805.      * @param forum
  5806.      */
  5807.     public void setMemo(Forum forum)
  5808.     {
  5809.         _forumMemo = forum;
  5810.     }
  5811.    
  5812.     /**
  5813.      * Restores sub-class data for the L2PcInstance, used to check the current class index for the character.
  5814.      * @param player The player to make checks on.
  5815.      * @return true if successful.
  5816.      */
  5817.     private static boolean restoreSubClassData(L2PcInstance player)
  5818.     {
  5819.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5820.         {
  5821.             PreparedStatement statement = con.prepareStatement(RESTORE_CHAR_SUBCLASSES);
  5822.             statement.setInt(1, player.getObjectId());
  5823.            
  5824.             ResultSet rset = statement.executeQuery();
  5825.            
  5826.             while (rset.next())
  5827.             {
  5828.                 SubClass subClass = new SubClass();
  5829.                 subClass.setClassId(rset.getInt("class_id"));
  5830.                 subClass.setLevel(rset.getByte("level"));
  5831.                 subClass.setExp(rset.getLong("exp"));
  5832.                 subClass.setSp(rset.getInt("sp"));
  5833.                 subClass.setClassIndex(rset.getInt("class_index"));
  5834.                
  5835.                 // Enforce the correct indexing of _subClasses against their class indexes.
  5836.                 player.getSubClasses().put(subClass.getClassIndex(), subClass);
  5837.             }
  5838.            
  5839.             statement.close();
  5840.         }
  5841.         catch (Exception e)
  5842.         {
  5843.             _log.warning("Could not restore classes for " + player.getName() + ": " + e);
  5844.             e.printStackTrace();
  5845.         }
  5846.        
  5847.         return true;
  5848.     }
  5849.    
  5850.     /**
  5851.      * Restores secondary data for the L2PcInstance, based on the current class index.
  5852.      */
  5853.     private void restoreCharData()
  5854.     {
  5855.         // Retrieve from the database all skills of this L2PcInstance and add them to _skills.
  5856.         restoreSkills();
  5857.        
  5858.         // Retrieve from the database all macroses of this L2PcInstance and add them to _macroses.
  5859.         _macroses.restore();
  5860.        
  5861.         // Retrieve from the database all shortCuts of this L2PcInstance and add them to _shortCuts.
  5862.         _shortCuts.restore();
  5863.        
  5864.         // Retrieve from the database all henna of this L2PcInstance and add them to _henna.
  5865.         restoreHenna();
  5866.        
  5867.         // Retrieve from the database all recom data of this L2PcInstance and add to _recomChars.
  5868.         restoreRecom();
  5869.        
  5870.         // Retrieve from the database the recipe book of this L2PcInstance.
  5871.         if (!isSubClassActive())
  5872.             restoreRecipeBook();
  5873.     }
  5874.    
  5875.     /**
  5876.      * Store recipe book data for this L2PcInstance, if not on an active sub-class.
  5877.      */
  5878.     private void storeRecipeBook()
  5879.     {
  5880.         // If the player is on a sub-class don't even attempt to store a recipe book.
  5881.         if (isSubClassActive())
  5882.             return;
  5883.         if (getCommonRecipeBook().length == 0 && getDwarvenRecipeBook().length == 0)
  5884.             return;
  5885.        
  5886.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5887.         {
  5888.             PreparedStatement statement = con.prepareStatement("DELETE FROM character_recipebook WHERE char_id=?");
  5889.             statement.setInt(1, getObjectId());
  5890.             statement.execute();
  5891.             statement.close();
  5892.            
  5893.             L2RecipeList[] recipes = getCommonRecipeBook();
  5894.            
  5895.             for (L2RecipeList recipe : recipes)
  5896.             {
  5897.                 statement = con.prepareStatement("INSERT INTO character_recipebook (char_id, id, type) values(?,?,0)");
  5898.                 statement.setInt(1, getObjectId());
  5899.                 statement.setInt(2, recipe.getId());
  5900.                 statement.execute();
  5901.                 statement.close();
  5902.             }
  5903.            
  5904.             recipes = getDwarvenRecipeBook();
  5905.             for (L2RecipeList recipe : recipes)
  5906.             {
  5907.                 statement = con.prepareStatement("INSERT INTO character_recipebook (char_id, id, type) values(?,?,1)");
  5908.                 statement.setInt(1, getObjectId());
  5909.                 statement.setInt(2, recipe.getId());
  5910.                 statement.execute();
  5911.                 statement.close();
  5912.             }
  5913.         }
  5914.         catch (Exception e)
  5915.         {
  5916.             _log.warning("Could not store recipe book data: " + e);
  5917.         }
  5918.     }
  5919.    
  5920.     /**
  5921.      * Restore recipe book data for this L2PcInstance.
  5922.      */
  5923.     private void restoreRecipeBook()
  5924.     {
  5925.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5926.         {
  5927.             PreparedStatement statement = con.prepareStatement("SELECT id, type FROM character_recipebook WHERE char_id=?");
  5928.             statement.setInt(1, getObjectId());
  5929.             ResultSet rset = statement.executeQuery();
  5930.            
  5931.             L2RecipeList recipe;
  5932.             while (rset.next())
  5933.             {
  5934.                 recipe = RecipeController.getInstance().getRecipeList(rset.getInt("id"));
  5935.                
  5936.                 if (rset.getInt("type") == 1)
  5937.                     registerDwarvenRecipeList(recipe);
  5938.                 else
  5939.                     registerCommonRecipeList(recipe);
  5940.             }
  5941.            
  5942.             rset.close();
  5943.             statement.close();
  5944.         }
  5945.         catch (Exception e)
  5946.         {
  5947.             _log.warning("Could not restore recipe book data:" + e);
  5948.         }
  5949.     }
  5950.    
  5951.     /**
  5952.      * Update L2PcInstance stats in the characters table of the database.
  5953.      * @param storeActiveEffects
  5954.      */
  5955.     public synchronized void store(boolean storeActiveEffects)
  5956.     {
  5957.         // update client coords, if these look like true
  5958.         if (isInsideRadius(getClientX(), getClientY(), 1000, true))
  5959.             setXYZ(getClientX(), getClientY(), getClientZ());
  5960.        
  5961.         storeCharBase();
  5962.         storeCharSub();
  5963.         storeEffect(storeActiveEffects);
  5964.         storeRecipeBook();
  5965.         SevenSigns.getInstance().saveSevenSignsData(getObjectId());
  5966.     }
  5967.    
  5968.     public void store()
  5969.     {
  5970.         store(true);
  5971.     }
  5972.    
  5973.     private void storeCharBase()
  5974.     {
  5975.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  5976.         {
  5977.             // Get the exp, level, and sp of base class to store in base table
  5978.             int currentClassIndex = getClassIndex();
  5979.             _classIndex = 0;
  5980.             long exp = getStat().getExp();
  5981.             int level = getStat().getLevel();
  5982.             int sp = getStat().getSp();
  5983.             _classIndex = currentClassIndex;
  5984.            
  5985.             PreparedStatement statement = con.prepareStatement(UPDATE_CHARACTER);
  5986.            
  5987.             statement.setInt(1, level);
  5988.             statement.setInt(2, getMaxHp());
  5989.             statement.setDouble(3, getCurrentHp());
  5990.             statement.setInt(4, getMaxCp());
  5991.             statement.setDouble(5, getCurrentCp());
  5992.             statement.setInt(6, getMaxMp());
  5993.             statement.setDouble(7, getCurrentMp());
  5994.             statement.setInt(8, getAppearance().getFace());
  5995.             statement.setInt(9, getAppearance().getHairStyle());
  5996.             statement.setInt(10, getAppearance().getHairColor());
  5997.             statement.setInt(11, getAppearance().getSex() ? 1 : 0);
  5998.             statement.setInt(12, getHeading());
  5999.             statement.setInt(13, _observerMode ? _lastX : getX());
  6000.             statement.setInt(14, _observerMode ? _lastY : getY());
  6001.             statement.setInt(15, _observerMode ? _lastZ : getZ());
  6002.             statement.setLong(16, exp);
  6003.             statement.setLong(17, getExpBeforeDeath());
  6004.             statement.setInt(18, sp);
  6005.             statement.setInt(19, getKarma());
  6006.             statement.setInt(20, getPvpKills());
  6007.             statement.setInt(21, getPkKills());
  6008.             statement.setInt(22, getRecomHave());
  6009.             statement.setInt(23, getRecomLeft());
  6010.             statement.setInt(24, getClanId());
  6011.             statement.setInt(25, getRace().ordinal());
  6012.             statement.setInt(26, getClassId().getId());
  6013.             statement.setLong(27, getDeleteTimer());
  6014.             statement.setString(28, getTitle());
  6015.             statement.setInt(29, getAccessLevel().getLevel());
  6016.             statement.setInt(30, isOnlineInt());
  6017.             statement.setInt(31, isIn7sDungeon() ? 1 : 0);
  6018.             statement.setInt(32, getClanPrivileges());
  6019.             statement.setInt(33, wantsPeace() ? 1 : 0);
  6020.             statement.setInt(34, getBaseClass());
  6021.            
  6022.             long totalOnlineTime = _onlineTime;
  6023.             if (_onlineBeginTime > 0)
  6024.                 totalOnlineTime += (System.currentTimeMillis() - _onlineBeginTime) / 1000;
  6025.            
  6026.             statement.setLong(35, totalOnlineTime);
  6027.             statement.setInt(36, getPunishLevel().value());
  6028.             statement.setLong(37, getPunishTimer());
  6029.             statement.setInt(38, isNoble() ? 1 : 0);
  6030.             statement.setLong(39, getPowerGrade());
  6031.             statement.setInt(40, getPledgeType());
  6032.             statement.setLong(41, getLastRecomUpdate());
  6033.             statement.setInt(42, getLvlJoinedAcademy());
  6034.             statement.setLong(43, getApprentice());
  6035.             statement.setLong(44, getSponsor());
  6036.             statement.setInt(45, getAllianceWithVarkaKetra());
  6037.             statement.setLong(46, getClanJoinExpiryTime());
  6038.             statement.setLong(47, getClanCreateExpiryTime());
  6039.             statement.setString(48, getName());
  6040.             statement.setLong(49, getDeathPenaltyBuffLevel());
  6041.             statement.setInt(50, isVoteBuff() ? 1 : 0);
  6042.             statement.setLong(51, getVoteBuffEndTime());
  6043.             statement.setInt(52, getObjectId());
  6044.            
  6045.             statement.execute();
  6046.             statement.close();
  6047.         }
  6048.         catch (Exception e)
  6049.         {
  6050.             _log.warning("Could not store char base data: " + e);
  6051.         }
  6052.     }
  6053.    
  6054.     private void storeCharSub()
  6055.     {
  6056.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6057.         {
  6058.             PreparedStatement statement = con.prepareStatement(UPDATE_CHAR_SUBCLASS);
  6059.            
  6060.             if (getTotalSubClasses() > 0)
  6061.             {
  6062.                 for (SubClass subClass : getSubClasses().values())
  6063.                 {
  6064.                     statement.setLong(1, subClass.getExp());
  6065.                     statement.setInt(2, subClass.getSp());
  6066.                     statement.setInt(3, subClass.getLevel());
  6067.                     statement.setInt(4, subClass.getClassId());
  6068.                     statement.setInt(5, getObjectId());
  6069.                     statement.setInt(6, subClass.getClassIndex());
  6070.                    
  6071.                     statement.execute();
  6072.                 }
  6073.             }
  6074.             statement.close();
  6075.         }
  6076.         catch (Exception e)
  6077.         {
  6078.             _log.warning("Could not store sub class data for " + getName() + ": " + e);
  6079.         }
  6080.     }
  6081.    
  6082.     private void storeEffect(boolean storeEffects)
  6083.     {
  6084.         if (!Config.STORE_SKILL_COOLTIME)
  6085.             return;
  6086.        
  6087.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6088.         {
  6089.             // Delete all current stored effects for char to avoid dupe
  6090.             PreparedStatement statement = con.prepareStatement(DELETE_SKILL_SAVE);
  6091.            
  6092.             statement.setInt(1, getObjectId());
  6093.             statement.setInt(2, getClassIndex());
  6094.             statement.execute();
  6095.             statement.close();
  6096.            
  6097.             int buff_index = 0;
  6098.            
  6099.             final List<Integer> storedSkills = new ArrayList<>();
  6100.            
  6101.             // Store all effect data along with calulated remaining
  6102.             // reuse delays for matching skills. 'restore_type'= 0.
  6103.             statement = con.prepareStatement(ADD_SKILL_SAVE);
  6104.            
  6105.             if (storeEffects)
  6106.             {
  6107.                 for (L2Effect effect : getAllEffects())
  6108.                 {
  6109.                     if (effect == null)
  6110.                         continue;
  6111.                    
  6112.                     switch (effect.getEffectType())
  6113.                     {
  6114.                         case HEAL_OVER_TIME:
  6115.                         case COMBAT_POINT_HEAL_OVER_TIME:
  6116.                             continue;
  6117.                     }
  6118.                    
  6119.                     L2Skill skill = effect.getSkill();
  6120.                     if (storedSkills.contains(skill.getReuseHashCode()))
  6121.                         continue;
  6122.                    
  6123.                     storedSkills.add(skill.getReuseHashCode());
  6124.                    
  6125.                     if (!effect.isHerbEffect() && effect.getInUse() && !skill.isToggle())
  6126.                     {
  6127.                         statement.setInt(1, getObjectId());
  6128.                         statement.setInt(2, skill.getId());
  6129.                         statement.setInt(3, skill.getLevel());
  6130.                         statement.setInt(4, effect.getCount());
  6131.                         statement.setInt(5, effect.getTime());
  6132.                        
  6133.                         if (_reuseTimeStamps.containsKey(skill.getReuseHashCode()))
  6134.                         {
  6135.                             TimeStamp t = _reuseTimeStamps.get(skill.getReuseHashCode());
  6136.                             statement.setLong(6, t.hasNotPassed() ? t.getReuse() : 0);
  6137.                             statement.setDouble(7, t.hasNotPassed() ? t.getStamp() : 0);
  6138.                         }
  6139.                         else
  6140.                         {
  6141.                             statement.setLong(6, 0);
  6142.                             statement.setDouble(7, 0);
  6143.                         }
  6144.                        
  6145.                         statement.setInt(8, 0);
  6146.                         statement.setInt(9, getClassIndex());
  6147.                         statement.setInt(10, ++buff_index);
  6148.                         statement.execute();
  6149.                     }
  6150.                 }
  6151.             }
  6152.            
  6153.             // Store the reuse delays of remaining skills which
  6154.             // lost effect but still under reuse delay. 'restore_type' 1.
  6155.             for (int hash : _reuseTimeStamps.keySet())
  6156.             {
  6157.                 if (storedSkills.contains(hash))
  6158.                     continue;
  6159.                
  6160.                 TimeStamp t = _reuseTimeStamps.get(hash);
  6161.                 if (t != null && t.hasNotPassed())
  6162.                 {
  6163.                     storedSkills.add(hash);
  6164.                    
  6165.                     statement.setInt(1, getObjectId());
  6166.                     statement.setInt(2, t.getSkillId());
  6167.                     statement.setInt(3, t.getSkillLvl());
  6168.                     statement.setInt(4, -1);
  6169.                     statement.setInt(5, -1);
  6170.                     statement.setLong(6, t.getReuse());
  6171.                     statement.setDouble(7, t.getStamp());
  6172.                     statement.setInt(8, 1);
  6173.                     statement.setInt(9, getClassIndex());
  6174.                     statement.setInt(10, ++buff_index);
  6175.                     statement.execute();
  6176.                 }
  6177.             }
  6178.             statement.close();
  6179.         }
  6180.         catch (Exception e)
  6181.         {
  6182.             _log.log(Level.WARNING, "Could not store char effect data: ", e);
  6183.         }
  6184.     }
  6185.    
  6186.     /**
  6187.      * @return True if the L2PcInstance is online.
  6188.      */
  6189.     public boolean isOnline()
  6190.     {
  6191.         return _isOnline;
  6192.     }
  6193.    
  6194.     /**
  6195.      * @return an int interpretation of online status.
  6196.      */
  6197.     public int isOnlineInt()
  6198.     {
  6199.         if (_isOnline && getClient() != null)
  6200.             return getClient().isDetached() ? 2 : 1;
  6201.        
  6202.         return 0;
  6203.     }
  6204.    
  6205.     public boolean isIn7sDungeon()
  6206.     {
  6207.         return _isIn7sDungeon;
  6208.     }
  6209.    
  6210.     /**
  6211.      * Add a skill to the L2PcInstance _skills and its Func objects to the calculator set of the L2PcInstance and save update in the character_skills table of the database.<BR>
  6212.      * <BR>
  6213.      * <B><U> Concept</U> :</B><BR>
  6214.      * <BR>
  6215.      * All skills own by a L2PcInstance are identified in <B>_skills</B><BR>
  6216.      * <BR>
  6217.      * <B><U> Actions</U> :</B><BR>
  6218.      * <BR>
  6219.      * <li>Replace oldSkill by newSkill or Add the newSkill</li> <li>If an old skill has been replaced, remove all its Func objects of L2Character calculator set</li> <li>Add Func objects of newSkill to the calculator set of the L2Character</li><BR>
  6220.      * <BR>
  6221.      * @param newSkill The L2Skill to add to the L2Character
  6222.      * @param store
  6223.      * @return The L2Skill replaced or null if just added a new L2Skill
  6224.      */
  6225.     public L2Skill addSkill(L2Skill newSkill, boolean store)
  6226.     {
  6227.         // Add a skill to the L2PcInstance _skills and its Func objects to the calculator set of the L2PcInstance
  6228.         L2Skill oldSkill = super.addSkill(newSkill);
  6229.        
  6230.         // Add or update a L2PcInstance skill in the character_skills table of the database
  6231.         if (store)
  6232.             storeSkill(newSkill, oldSkill, -1);
  6233.        
  6234.         return oldSkill;
  6235.     }
  6236.    
  6237.     @Override
  6238.     public L2Skill removeSkill(L2Skill skill, boolean store)
  6239.     {
  6240.         if (store)
  6241.             return removeSkill(skill);
  6242.        
  6243.         return super.removeSkill(skill, true);
  6244.     }
  6245.    
  6246.     public L2Skill removeSkill(L2Skill skill, boolean store, boolean cancelEffect)
  6247.     {
  6248.         if (store)
  6249.             return removeSkill(skill);
  6250.        
  6251.         return super.removeSkill(skill, cancelEffect);
  6252.     }
  6253.    
  6254.     /**
  6255.      * Remove a skill from the L2Character and its Func objects from calculator set of the L2Character and save update in the character_skills table of the database.<BR>
  6256.      * <BR>
  6257.      * <B><U> Concept</U> :</B><BR>
  6258.      * <BR>
  6259.      * All skills own by a L2Character are identified in <B>_skills</B><BR>
  6260.      * <BR>
  6261.      * <B><U> Actions</U> :</B><BR>
  6262.      * <BR>
  6263.      * <li>Remove the skill from the L2Character _skills</li> <li>Remove all its Func objects from the L2Character calculator set</li><BR>
  6264.      * <BR>
  6265.      * <B><U> Overriden in </U> :</B><BR>
  6266.      * <BR>
  6267.      * <li>L2PcInstance : Save update in the character_skills table of the database</li><BR>
  6268.      * <BR>
  6269.      * @param skill The L2Skill to remove from the L2Character
  6270.      * @return The L2Skill removed
  6271.      */
  6272.     @Override
  6273.     public L2Skill removeSkill(L2Skill skill)
  6274.     {
  6275.         // Remove a skill from the L2Character and its Func objects from calculator set of the L2Character
  6276.         L2Skill oldSkill = super.removeSkill(skill);
  6277.        
  6278.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6279.         {
  6280.             PreparedStatement statement = con.prepareStatement(DELETE_SKILL_FROM_CHAR);
  6281.            
  6282.             if (oldSkill != null)
  6283.             {
  6284.                 statement.setInt(1, oldSkill.getId());
  6285.                 statement.setInt(2, getObjectId());
  6286.                 statement.setInt(3, getClassIndex());
  6287.                 statement.execute();
  6288.             }
  6289.             statement.close();
  6290.         }
  6291.         catch (Exception e)
  6292.         {
  6293.             _log.warning("Error could not delete skill: " + e);
  6294.         }
  6295.        
  6296.         // Don't busy with shortcuts if skill was a passive skill.
  6297.         if (skill != null && !skill.isPassive())
  6298.         {
  6299.             L2ShortCut[] allShortCuts = getAllShortCuts();
  6300.            
  6301.             for (L2ShortCut sc : allShortCuts)
  6302.             {
  6303.                 if (sc != null && sc.getId() == skill.getId() && sc.getType() == L2ShortCut.TYPE_SKILL)
  6304.                     deleteShortCut(sc.getSlot(), sc.getPage());
  6305.             }
  6306.         }
  6307.        
  6308.         return oldSkill;
  6309.     }
  6310.    
  6311.     /**
  6312.      * Add or update a L2PcInstance skill in the character_skills table of the database. <BR>
  6313.      * <BR>
  6314.      * If newClassIndex > -1, the skill will be stored with that class index, not the current one.
  6315.      * @param newSkill
  6316.      * @param oldSkill
  6317.      * @param newClassIndex
  6318.      */
  6319.     private void storeSkill(L2Skill newSkill, L2Skill oldSkill, int newClassIndex)
  6320.     {
  6321.         int classIndex = _classIndex;
  6322.        
  6323.         if (newClassIndex > -1)
  6324.             classIndex = newClassIndex;
  6325.        
  6326.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6327.         {
  6328.             PreparedStatement statement;
  6329.            
  6330.             if (oldSkill != null && newSkill != null)
  6331.             {
  6332.                 statement = con.prepareStatement(UPDATE_CHARACTER_SKILL_LEVEL);
  6333.                 statement.setInt(1, newSkill.getLevel());
  6334.                 statement.setInt(2, oldSkill.getId());
  6335.                 statement.setInt(3, getObjectId());
  6336.                 statement.setInt(4, classIndex);
  6337.                 statement.execute();
  6338.                 statement.close();
  6339.             }
  6340.             else if (newSkill != null)
  6341.             {
  6342.                 statement = con.prepareStatement(ADD_NEW_SKILL);
  6343.                 statement.setInt(1, getObjectId());
  6344.                 statement.setInt(2, newSkill.getId());
  6345.                 statement.setInt(3, newSkill.getLevel());
  6346.                 statement.setInt(4, classIndex);
  6347.                 statement.execute();
  6348.                 statement.close();
  6349.             }
  6350.             else
  6351.             {
  6352.                 _log.warning("storeSkill() couldn't store new skill. It's null type.");
  6353.             }
  6354.         }
  6355.         catch (Exception e)
  6356.         {
  6357.             _log.warning("Error could not store char skills: " + e);
  6358.         }
  6359.     }
  6360.    
  6361.     /**
  6362.      * Retrieve from the database all skills of this L2PcInstance and add them to _skills.
  6363.      */
  6364.     private void restoreSkills()
  6365.     {
  6366.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6367.         {
  6368.             PreparedStatement statement = con.prepareStatement(RESTORE_SKILLS_FOR_CHAR);
  6369.             statement.setInt(1, getObjectId());
  6370.             statement.setInt(2, getClassIndex());
  6371.             ResultSet rset = statement.executeQuery();
  6372.            
  6373.             // Go though the recordset of this SQL query
  6374.             while (rset.next())
  6375.             {
  6376.                 int id = rset.getInt("skill_id");
  6377.                 int level = rset.getInt("skill_level");
  6378.                
  6379.                 if (id > 9000)
  6380.                     continue; // fake skills for base stats
  6381.                    
  6382.                 // Create a L2Skill object for each record
  6383.                 L2Skill skill = SkillTable.getInstance().getInfo(id, level);
  6384.                
  6385.                 // Add the L2Skill object to the L2Character _skills and its Func objects to the calculator set of the L2Character
  6386.                 super.addSkill(skill);
  6387.             }
  6388.            
  6389.             rset.close();
  6390.             statement.close();
  6391.         }
  6392.         catch (Exception e)
  6393.         {
  6394.             _log.warning("Could not restore character skills: " + e);
  6395.         }
  6396.     }
  6397.    
  6398.     /**
  6399.      * Retrieve from the database all skill effects of this L2PcInstance and add them to the player.
  6400.      */
  6401.     public void restoreEffects()
  6402.     {
  6403.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6404.         {
  6405.             PreparedStatement statement = con.prepareStatement(RESTORE_SKILL_SAVE);
  6406.             statement.setInt(1, getObjectId());
  6407.             statement.setInt(2, getClassIndex());
  6408.             ResultSet rset = statement.executeQuery();
  6409.            
  6410.             while (rset.next())
  6411.             {
  6412.                 int effectCount = rset.getInt("effect_count");
  6413.                 int effectCurTime = rset.getInt("effect_cur_time");
  6414.                 long reuseDelay = rset.getLong("reuse_delay");
  6415.                 long systime = rset.getLong("systime");
  6416.                 int restoreType = rset.getInt("restore_type");
  6417.                
  6418.                 final L2Skill skill = SkillTable.getInstance().getInfo(rset.getInt("skill_id"), rset.getInt("skill_level"));
  6419.                 if (skill == null)
  6420.                     continue;
  6421.                
  6422.                 final long remainingTime = systime - System.currentTimeMillis();
  6423.                 if (remainingTime > 10)
  6424.                 {
  6425.                     disableSkill(skill, remainingTime);
  6426.                     addTimeStamp(skill, reuseDelay, systime);
  6427.                 }
  6428.                
  6429.                 /**
  6430.                  * Restore Type 1 The remaning skills lost effect upon logout but were still under a high reuse delay.
  6431.                  */
  6432.                 if (restoreType > 0)
  6433.                     continue;
  6434.                
  6435.                 /**
  6436.                  * Restore Type 0 These skills were still in effect on the character upon logout. Some of which were self casted and might still have a long reuse delay which also is restored.
  6437.                  */
  6438.                 if (skill.hasEffects())
  6439.                 {
  6440.                     Env env = new Env();
  6441.                     env.player = this;
  6442.                     env.target = this;
  6443.                     env.skill = skill;
  6444.                     L2Effect ef;
  6445.                     for (EffectTemplate et : skill.getEffectTemplates())
  6446.                     {
  6447.                         ef = et.getEffect(env);
  6448.                         if (ef != null)
  6449.                         {
  6450.                             ef.setCount(effectCount);
  6451.                             ef.setFirstTime(effectCurTime);
  6452.                             ef.scheduleEffect();
  6453.                         }
  6454.                     }
  6455.                 }
  6456.             }
  6457.            
  6458.             rset.close();
  6459.             statement.close();
  6460.            
  6461.             statement = con.prepareStatement(DELETE_SKILL_SAVE);
  6462.             statement.setInt(1, getObjectId());
  6463.             statement.setInt(2, getClassIndex());
  6464.             statement.executeUpdate();
  6465.             statement.close();
  6466.         }
  6467.         catch (Exception e)
  6468.         {
  6469.             _log.log(Level.WARNING, "Could not restore " + this + " active effect data: " + e.getMessage(), e);
  6470.         }
  6471.     }
  6472.    
  6473.     /**
  6474.      * Retrieve from the database all Henna of this L2PcInstance, add them to _henna and calculate stats of the L2PcInstance.
  6475.      */
  6476.     private void restoreHenna()
  6477.     {
  6478.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6479.         {
  6480.             PreparedStatement statement = con.prepareStatement(RESTORE_CHAR_HENNAS);
  6481.             statement.setInt(1, getObjectId());
  6482.             statement.setInt(2, getClassIndex());
  6483.             ResultSet rset = statement.executeQuery();
  6484.            
  6485.             for (int i = 0; i < 3; i++)
  6486.                 _henna[i] = null;
  6487.            
  6488.             while (rset.next())
  6489.             {
  6490.                 int slot = rset.getInt("slot");
  6491.                
  6492.                 if (slot < 1 || slot > 3)
  6493.                     continue;
  6494.                
  6495.                 int symbolId = rset.getInt("symbol_id");
  6496.                 if (symbolId != 0)
  6497.                 {
  6498.                     L2Henna tpl = HennaTable.getInstance().getTemplate(symbolId);
  6499.                     if (tpl != null)
  6500.                         _henna[slot - 1] = tpl;
  6501.                 }
  6502.             }
  6503.            
  6504.             rset.close();
  6505.             statement.close();
  6506.         }
  6507.         catch (Exception e)
  6508.         {
  6509.             _log.warning("could not restore henna: " + e);
  6510.         }
  6511.        
  6512.         // Calculate Henna modifiers of this L2PcInstance
  6513.         recalcHennaStats();
  6514.     }
  6515.    
  6516.     /**
  6517.      * Retrieve from the database all Recommendation data of this L2PcInstance, add to _recomChars and calculate stats of the L2PcInstance.
  6518.      */
  6519.     private void restoreRecom()
  6520.     {
  6521.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6522.         {
  6523.             PreparedStatement statement = con.prepareStatement(RESTORE_CHAR_RECOMS);
  6524.             statement.setInt(1, getObjectId());
  6525.             ResultSet rset = statement.executeQuery();
  6526.             while (rset.next())
  6527.                 _recomChars.add(rset.getInt("target_id"));
  6528.            
  6529.             rset.close();
  6530.             statement.close();
  6531.         }
  6532.         catch (Exception e)
  6533.         {
  6534.             _log.warning("could not restore recommendations: " + e);
  6535.         }
  6536.     }
  6537.    
  6538.     /**
  6539.      * @return the number of Henna empty slot of the L2PcInstance.
  6540.      */
  6541.     public int getHennaEmptySlots()
  6542.     {
  6543.         int totalSlots = 0;
  6544.         if (getClassId().level() == 1)
  6545.             totalSlots = 2;
  6546.         else
  6547.             totalSlots = 3;
  6548.        
  6549.         for (int i = 0; i < 3; i++)
  6550.         {
  6551.             if (_henna[i] != null)
  6552.                 totalSlots--;
  6553.         }
  6554.        
  6555.         if (totalSlots <= 0)
  6556.             return 0;
  6557.        
  6558.         return totalSlots;
  6559.     }
  6560.    
  6561.     /**
  6562.      * Remove a Henna of the L2PcInstance, save update in the character_hennas table of the database and send Server->Client HennaInfo/UserInfo packet to this L2PcInstance.
  6563.      * @param slot The slot number to make checks on.
  6564.      * @return true if successful.
  6565.      */
  6566.     public boolean removeHenna(int slot)
  6567.     {
  6568.         if (slot < 1 || slot > 3)
  6569.             return false;
  6570.        
  6571.         slot--;
  6572.        
  6573.         if (_henna[slot] == null)
  6574.             return false;
  6575.        
  6576.         L2Henna henna = _henna[slot];
  6577.         _henna[slot] = null;
  6578.        
  6579.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6580.         {
  6581.             PreparedStatement statement = con.prepareStatement(DELETE_CHAR_HENNA);
  6582.            
  6583.             statement.setInt(1, getObjectId());
  6584.             statement.setInt(2, slot + 1);
  6585.             statement.setInt(3, getClassIndex());
  6586.            
  6587.             statement.execute();
  6588.             statement.close();
  6589.         }
  6590.         catch (Exception e)
  6591.         {
  6592.             _log.warning("could not remove char henna: " + e);
  6593.         }
  6594.        
  6595.         // Calculate Henna modifiers of this L2PcInstance
  6596.         recalcHennaStats();
  6597.        
  6598.         // Send Server->Client HennaInfo packet to this L2PcInstance
  6599.         sendPacket(new HennaInfo(this));
  6600.        
  6601.         // Send Server->Client UserInfo packet to this L2PcInstance
  6602.         sendPacket(new UserInfo(this));
  6603.        
  6604.         reduceAdena("Henna", henna.getPrice() / 5, this, false);
  6605.        
  6606.         // Add the recovered dyes to the player's inventory and notify them.
  6607.         addItem("Henna", henna.getDyeId(), L2Henna.getAmountDyeRequire() / 2, this, true);
  6608.         sendPacket(SystemMessageId.SYMBOL_DELETED);
  6609.         return true;
  6610.     }
  6611.    
  6612.     /**
  6613.      * Add a Henna to the L2PcInstance, save update in the character_hennas table of the database and send Server->Client HennaInfo/UserInfo packet to this L2PcInstance.
  6614.      * @param henna The Henna template to add.
  6615.      */
  6616.     public void addHenna(L2Henna henna)
  6617.     {
  6618.         for (int i = 0; i < 3; i++)
  6619.         {
  6620.             if (_henna[i] == null)
  6621.             {
  6622.                 _henna[i] = henna;
  6623.                
  6624.                 // Calculate Henna modifiers of this L2PcInstance
  6625.                 recalcHennaStats();
  6626.                
  6627.                 try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  6628.                 {
  6629.                     PreparedStatement statement = con.prepareStatement(ADD_CHAR_HENNA);
  6630.                    
  6631.                     statement.setInt(1, getObjectId());
  6632.                     statement.setInt(2, henna.getSymbolId());
  6633.                     statement.setInt(3, i + 1);
  6634.                     statement.setInt(4, getClassIndex());
  6635.                    
  6636.                     statement.execute();
  6637.                     statement.close();
  6638.                 }
  6639.                 catch (Exception e)
  6640.                 {
  6641.                     _log.warning("could not save char henna: " + e);
  6642.                 }
  6643.                
  6644.                 sendPacket(new HennaInfo(this));
  6645.                 sendPacket(new UserInfo(this));
  6646.                 sendPacket(SystemMessageId.SYMBOL_ADDED);
  6647.                 return;
  6648.             }
  6649.         }
  6650.     }
  6651.    
  6652.     /**
  6653.      * Calculate Henna modifiers of this L2PcInstance.<BR>
  6654.      * <BR>
  6655.      */
  6656.     private void recalcHennaStats()
  6657.     {
  6658.         _hennaINT = 0;
  6659.         _hennaSTR = 0;
  6660.         _hennaCON = 0;
  6661.         _hennaMEN = 0;
  6662.         _hennaWIT = 0;
  6663.         _hennaDEX = 0;
  6664.        
  6665.         for (int i = 0; i < 3; i++)
  6666.         {
  6667.             if (_henna[i] == null)
  6668.                 continue;
  6669.            
  6670.             _hennaINT += _henna[i].getStatINT();
  6671.             _hennaSTR += _henna[i].getStatSTR();
  6672.             _hennaMEN += _henna[i].getStatMEN();
  6673.             _hennaCON += _henna[i].getStatCON();
  6674.             _hennaWIT += _henna[i].getStatWIT();
  6675.             _hennaDEX += _henna[i].getStatDEX();
  6676.         }
  6677.        
  6678.         if (_hennaINT > 5)
  6679.             _hennaINT = 5;
  6680.        
  6681.         if (_hennaSTR > 5)
  6682.             _hennaSTR = 5;
  6683.        
  6684.         if (_hennaMEN > 5)
  6685.             _hennaMEN = 5;
  6686.        
  6687.         if (_hennaCON > 5)
  6688.             _hennaCON = 5;
  6689.        
  6690.         if (_hennaWIT > 5)
  6691.             _hennaWIT = 5;
  6692.        
  6693.         if (_hennaDEX > 5)
  6694.             _hennaDEX = 5;
  6695.     }
  6696.    
  6697.     /**
  6698.      * @param slot A slot to check.
  6699.      * @return the Henna of this L2PcInstance corresponding to the selected slot.
  6700.      */
  6701.     public L2Henna getHenna(int slot)
  6702.     {
  6703.         if (slot < 1 || slot > 3)
  6704.             return null;
  6705.        
  6706.         return _henna[slot - 1];
  6707.     }
  6708.    
  6709.     public int getHennaStatINT()
  6710.     {
  6711.         return _hennaINT;
  6712.     }
  6713.    
  6714.     public int getHennaStatSTR()
  6715.     {
  6716.         return _hennaSTR;
  6717.     }
  6718.    
  6719.     public int getHennaStatCON()
  6720.     {
  6721.         return _hennaCON;
  6722.     }
  6723.    
  6724.     public int getHennaStatMEN()
  6725.     {
  6726.         return _hennaMEN;
  6727.     }
  6728.    
  6729.     public int getHennaStatWIT()
  6730.     {
  6731.         return _hennaWIT;
  6732.     }
  6733.    
  6734.     public int getHennaStatDEX()
  6735.     {
  6736.         return _hennaDEX;
  6737.     }
  6738.    
  6739.     /**
  6740.      * Return True if the L2PcInstance is autoAttackable.
  6741.      * <ul>
  6742.      * <li>Check if the attacker isn't the L2PcInstance Pet</li>
  6743.      * <li>Check if the attacker is L2MonsterInstance</li>
  6744.      * <li>If the attacker is a L2PcInstance, check if it is not in the same party</li>
  6745.      * <li>Check if the L2PcInstance has Karma</li>
  6746.      * <li>If the attacker is a L2PcInstance, check if it is not in the same siege clan (Attacker, Defender)</li>
  6747.      * </ul>
  6748.      */
  6749.     @Override
  6750.     public boolean isAutoAttackable(L2Character attacker)
  6751.     {
  6752.         // Check if the attacker isn't the L2PcInstance Pet
  6753.         if (attacker == this || attacker == getPet())
  6754.             return false;
  6755.        
  6756.         // Check if the attacker is a L2MonsterInstance
  6757.         if (attacker instanceof L2MonsterInstance)
  6758.             return true;
  6759.        
  6760.         // Check if the attacker is not in the same party
  6761.         if (getParty() != null && getParty().getPartyMembers().contains(attacker))
  6762.             return false;
  6763.        
  6764.         // Check if the attacker is a L2Playable
  6765.         if (attacker instanceof L2Playable)
  6766.         {
  6767.             if (isInsideZone(ZoneId.PEACE))
  6768.                 return false;
  6769.            
  6770.             // Get L2PcInstance
  6771.             final L2PcInstance cha = attacker.getActingPlayer();
  6772.            
  6773.             // Check if the attacker is in olympiad and olympiad start
  6774.             if (attacker instanceof L2PcInstance && cha.isInOlympiadMode())
  6775.             {
  6776.                 if (isInOlympiadMode() && isOlympiadStart() && cha.getOlympiadGameId() == getOlympiadGameId())
  6777.                     return true;
  6778.                
  6779.                 return false;
  6780.             }
  6781.            
  6782.             // is AutoAttackable if both players are in the same duel and the duel is still going on
  6783.             if (getDuelState() == Duel.DUELSTATE_DUELLING && getDuelId() == cha.getDuelId())
  6784.                 return true;
  6785.            
  6786.             if (getClan() != null)
  6787.             {
  6788.                 final Siege siege = SiegeManager.getSiege(getX(), getY(), getZ());
  6789.                 if (siege != null)
  6790.                 {
  6791.                     // Check if a siege is in progress and if attacker and the L2PcInstance aren't in the Defender clan
  6792.                     if (siege.checkIsDefender(cha.getClan()) && siege.checkIsDefender(getClan()))
  6793.                         return false;
  6794.                    
  6795.                     // Check if a siege is in progress and if attacker and the L2PcInstance aren't in the Attacker clan
  6796.                     if (siege.checkIsAttacker(cha.getClan()) && siege.checkIsAttacker(getClan()))
  6797.                         return false;
  6798.                 }
  6799.                
  6800.                 // Check if clan is at war
  6801.                 if (getClan().isAtWarWith(cha.getClanId()) && !wantsPeace() && !cha.wantsPeace() && !isAcademyMember())
  6802.                     return true;
  6803.             }
  6804.            
  6805.             // Check if the L2PcInstance is in an arena.
  6806.             if (isInArena() && attacker.isInArena())
  6807.                 return true;
  6808.            
  6809.             // Check if the attacker is not in the same ally.
  6810.             if (getAllyId() != 0 && getAllyId() == cha.getAllyId())
  6811.                 return false;
  6812.            
  6813.             // Check if the attacker is not in the same clan.
  6814.             if (getClan() != null && getClan().isMember(cha.getObjectId()))
  6815.                 return false;
  6816.            
  6817.             // Now check again if the L2PcInstance is in pvp zone (as arenas check was made before, it ends with sieges).
  6818.             if (isInsideZone(ZoneId.PVP) && attacker.isInsideZone(ZoneId.PVP))
  6819.                 return true;
  6820.         }
  6821.         else if (attacker instanceof L2SiegeGuardInstance)
  6822.         {
  6823.             if (getClan() != null)
  6824.             {
  6825.                 final Siege siege = SiegeManager.getSiege(this);
  6826.                 return (siege != null && siege.checkIsAttacker(getClan()));
  6827.             }
  6828.         }
  6829.        
  6830.         // Check if the L2PcInstance has Karma
  6831.         if (getKarma() > 0 || getPvpFlag() > 0)
  6832.             return true;
  6833.        
  6834.         return false;
  6835.     }
  6836.    
  6837.     /**
  6838.      * Check if the active L2Skill can be casted.<BR>
  6839.      * <BR>
  6840.      * <B><U> Actions</U> :</B><BR>
  6841.      * <BR>
  6842.      * <li>Check if the skill isn't toggle and is offensive</li> <li>Check if the target is in the skill cast range</li> <li>Check if the skill is Spoil type and if the target isn't already spoiled</li> <li>Check if the caster owns enought consummed Item, enough HP and MP to cast the skill</li> <li>
  6843.      * Check if the caster isn't sitting</li> <li>Check if all skills are enabled and this skill is enabled</li><BR>
  6844.      * <BR>
  6845.      * <li>Check if the caster own the weapon needed</li><BR>
  6846.      * <BR>
  6847.      * <li>Check if the skill is active</li><BR>
  6848.      * <BR>
  6849.      * <li>Check if all casting conditions are completed</li><BR>
  6850.      * <BR>
  6851.      * <li>Notify the AI with CAST and target</li><BR>
  6852.      * <BR>
  6853.      * @param skill The L2Skill to use
  6854.      * @param forceUse used to force ATTACK on players
  6855.      * @param dontMove used to prevent movement, if not in range
  6856.      */
  6857.     @Override
  6858.     public boolean useMagic(L2Skill skill, boolean forceUse, boolean dontMove)
  6859.     {
  6860.         // Check if the skill is active
  6861.         if (skill.isPassive())
  6862.         {
  6863.             sendPacket(ActionFailed.STATIC_PACKET);
  6864.             return false;
  6865.         }
  6866.        
  6867.         // Cancels the use of skills when player uses a cursed weapon or is flying.
  6868.         if ((isCursedWeaponEquipped() && !skill.isDemonicSkill()) // If CW, allow ONLY demonic skills.
  6869.             || (getMountType() == 1 && !skill.isStriderSkill()) // If mounted, allow ONLY Strider skills.
  6870.             || (getMountType() == 2 && !skill.isFlyingSkill())) // If flying, allow ONLY Wyvern skills.
  6871.         {
  6872.             sendPacket(ActionFailed.STATIC_PACKET);
  6873.             return false;
  6874.         }
  6875.        
  6876.         // Players wearing Formal Wear cannot use skills.
  6877.         final L2ItemInstance formal = getInventory().getPaperdollItem(Inventory.PAPERDOLL_CHEST);
  6878.         if (formal != null && formal.getItem().getBodyPart() == L2Item.SLOT_ALLDRESS)
  6879.         {
  6880.             sendPacket(SystemMessageId.CANNOT_USE_ITEMS_SKILLS_WITH_FORMALWEAR);
  6881.             sendPacket(ActionFailed.STATIC_PACKET);
  6882.             return false;
  6883.         }
  6884.        
  6885.         // ************************************* Check Casting in Progress *******************************************
  6886.        
  6887.         // If a skill is currently being used, queue this one if this is not the same
  6888.         if (isCastingNow())
  6889.         {
  6890.             SkillDat currentSkill = getCurrentSkill();
  6891.             // Check if new skill different from current skill in progress
  6892.             if (currentSkill != null && skill.getId() == currentSkill.getSkillId())
  6893.             {
  6894.                 sendPacket(ActionFailed.STATIC_PACKET);
  6895.                 return false;
  6896.             }
  6897.            
  6898.             if (Config.DEBUG && getQueuedSkill() != null)
  6899.                 _log.info(getQueuedSkill().getSkill().getName() + " is already queued for " + getName() + ".");
  6900.            
  6901.             // Create a new SkillDat object and queue it in the player _queuedSkill
  6902.             setQueuedSkill(skill, forceUse, dontMove);
  6903.             sendPacket(ActionFailed.STATIC_PACKET);
  6904.             return false;
  6905.         }
  6906.         setIsCastingNow(true);
  6907.        
  6908.         // Create a new SkillDat object and set the player _currentSkill
  6909.         setCurrentSkill(skill, forceUse, dontMove);
  6910.        
  6911.         if (getQueuedSkill() != null) // wiping out previous values, after casting has been aborted
  6912.             setQueuedSkill(null, false, false);
  6913.        
  6914.         if (!checkUseMagicConditions(skill, forceUse, dontMove))
  6915.         {
  6916.             setIsCastingNow(false);
  6917.             return false;
  6918.         }
  6919.        
  6920.         // Check if the target is correct and Notify the AI with CAST and target
  6921.         L2Object target = null;
  6922.        
  6923.         switch (skill.getTargetType())
  6924.         {
  6925.             case TARGET_AURA: // AURA, SELF should be cast even if no target has been found
  6926.             case TARGET_FRONT_AURA:
  6927.             case TARGET_BEHIND_AURA:
  6928.             case TARGET_GROUND:
  6929.             case TARGET_SELF:
  6930.             case TARGET_AURA_UNDEAD:
  6931.                 target = this;
  6932.                 break;
  6933.             default:
  6934.                
  6935.                 // Get the first target of the list
  6936.                 target = skill.getFirstOfTargetList(this);
  6937.                 break;
  6938.         }
  6939.        
  6940.         // Notify the AI with CAST and target
  6941.         getAI().setIntention(CtrlIntention.CAST, skill, target);
  6942.         return true;
  6943.     }
  6944.    
  6945.     private boolean checkUseMagicConditions(L2Skill skill, boolean forceUse, boolean dontMove)
  6946.     {
  6947.         L2SkillType sklType = skill.getSkillType();
  6948.        
  6949.         // ************************************* Check Player State *******************************************
  6950.        
  6951.         // Abnormal effects(ex : Stun, Sleep...) are checked in L2Character useMagic()
  6952.        
  6953.         if (isOutOfControl() || isParalyzed() || isStunned() || isSleeping())
  6954.         {
  6955.             sendPacket(ActionFailed.STATIC_PACKET);
  6956.             return false;
  6957.         }
  6958.        
  6959.         // Check if the player is dead
  6960.         if (isDead())
  6961.         {
  6962.             // Send ActionFailed to the L2PcInstance
  6963.             sendPacket(ActionFailed.STATIC_PACKET);
  6964.             return false;
  6965.         }
  6966.        
  6967.         if (isFishing() && (sklType != L2SkillType.PUMPING && sklType != L2SkillType.REELING && sklType != L2SkillType.FISHING))
  6968.         {
  6969.             // Only fishing skills are available
  6970.             sendPacket(SystemMessageId.ONLY_FISHING_SKILLS_NOW);
  6971.             return false;
  6972.         }
  6973.        
  6974.         if (inObserverMode())
  6975.         {
  6976.             sendPacket(SystemMessageId.OBSERVERS_CANNOT_PARTICIPATE);
  6977.             abortCast();
  6978.             sendPacket(ActionFailed.STATIC_PACKET);
  6979.             return false;
  6980.         }
  6981.        
  6982.         // Check if the caster is sitted. Toggle skills can be only removed, not activated.
  6983.         if (isSitting())
  6984.         {
  6985.             if (skill.isToggle())
  6986.             {
  6987.                 // Get effects of the skill
  6988.                 L2Effect effect = getFirstEffect(skill.getId());
  6989.                 if (effect != null)
  6990.                 {
  6991.                     effect.exit();
  6992.                    
  6993.                     // Send ActionFailed to the L2PcInstance
  6994.                     sendPacket(ActionFailed.STATIC_PACKET);
  6995.                     return false;
  6996.                 }
  6997.             }
  6998.            
  6999.             // Send a System Message to the caster
  7000.             sendPacket(SystemMessageId.CANT_MOVE_SITTING);
  7001.            
  7002.             // Send ActionFailed to the L2PcInstance
  7003.             sendPacket(ActionFailed.STATIC_PACKET);
  7004.             return false;
  7005.         }
  7006.        
  7007.         // Check if the skill type is TOGGLE
  7008.         if (skill.isToggle())
  7009.         {
  7010.             // Get effects of the skill
  7011.             L2Effect effect = getFirstEffect(skill.getId());
  7012.            
  7013.             if (effect != null)
  7014.             {
  7015.                 // If the toggle is different of FakeDeath, you can de-activate it clicking on it.
  7016.                 if (skill.getId() != 60)
  7017.                     effect.exit();
  7018.                
  7019.                 // Send ActionFailed to the L2PcInstance
  7020.                 sendPacket(ActionFailed.STATIC_PACKET);
  7021.                 return false;
  7022.             }
  7023.         }
  7024.        
  7025.         // Check if the player uses "Fake Death" skill
  7026.         if (isFakeDeath())
  7027.         {
  7028.             // Send ActionFailed to the L2PcInstance
  7029.             sendPacket(ActionFailed.STATIC_PACKET);
  7030.             return false;
  7031.         }
  7032.        
  7033.         // ************************************* Check Target *******************************************
  7034.         // Create and set a L2Object containing the target of the skill
  7035.         L2Object target = null;
  7036.         SkillTargetType sklTargetType = skill.getTargetType();
  7037.         Point3D worldPosition = getCurrentSkillWorldPosition();
  7038.        
  7039.         if (sklTargetType == SkillTargetType.TARGET_GROUND && worldPosition == null)
  7040.         {
  7041.             _log.info("WorldPosition is null for skill: " + skill.getName() + ", player: " + getName() + ".");
  7042.             sendPacket(ActionFailed.STATIC_PACKET);
  7043.             return false;
  7044.         }
  7045.        
  7046.         switch (sklTargetType)
  7047.         {
  7048.         // Target the player if skill type is AURA, PARTY, CLAN or SELF
  7049.             case TARGET_AURA:
  7050.             case TARGET_FRONT_AURA:
  7051.             case TARGET_BEHIND_AURA:
  7052.             case TARGET_AURA_UNDEAD:
  7053.             case TARGET_PARTY:
  7054.             case TARGET_ALLY:
  7055.             case TARGET_CLAN:
  7056.             case TARGET_GROUND:
  7057.             case TARGET_SELF:
  7058.             case TARGET_AREA_SUMMON:
  7059.                 target = this;
  7060.                 break;
  7061.             case TARGET_PET:
  7062.             case TARGET_SUMMON:
  7063.                 target = getPet();
  7064.                 break;
  7065.             default:
  7066.                 target = getTarget();
  7067.                 break;
  7068.         }
  7069.        
  7070.         // Check the validity of the target
  7071.         if (target == null)
  7072.         {
  7073.             sendPacket(ActionFailed.STATIC_PACKET);
  7074.             return false;
  7075.         }
  7076.        
  7077.         if (target instanceof L2DoorInstance)
  7078.         {
  7079.             if (!((L2DoorInstance) target).isAttackable(this) // Siege doors only hittable during siege
  7080.                 || (((L2DoorInstance) target).isUnlockable() && skill.getSkillType() != L2SkillType.UNLOCK)) // unlockable doors
  7081.             {
  7082.                 sendPacket(SystemMessageId.INCORRECT_TARGET);
  7083.                 sendPacket(ActionFailed.STATIC_PACKET);
  7084.                 return false;
  7085.             }
  7086.         }
  7087.        
  7088.         // Are the target and the player in the same duel?
  7089.         if (isInDuel())
  7090.         {
  7091.             if (target instanceof L2Playable)
  7092.             {
  7093.                 // Get L2PcInstance
  7094.                 L2PcInstance cha = target.getActingPlayer();
  7095.                 if (cha.getDuelId() != getDuelId())
  7096.                 {
  7097.                     sendPacket(SystemMessageId.INCORRECT_TARGET);
  7098.                     sendPacket(ActionFailed.STATIC_PACKET);
  7099.                     return false;
  7100.                 }
  7101.             }
  7102.         }
  7103.        
  7104.         // ************************************* Check skill availability *******************************************
  7105.        
  7106.         // Siege summon checks. Both checks send a message to the player if it return false.
  7107.         if (skill.isSiegeSummonSkill() && (!SiegeManager.checkIfOkToSummon(this) || !SevenSigns.getInstance().checkSummonConditions(this)))
  7108.             return false;
  7109.        
  7110.         // Check if this skill is enabled (ex : reuse time)
  7111.         if (isSkillDisabled(skill))
  7112.         {
  7113.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_PREPARED_FOR_REUSE).addSkillName(skill));
  7114.             return false;
  7115.         }
  7116.        
  7117.         // ************************************* Check casting conditions *******************************************
  7118.        
  7119.         // Check if all casting conditions are completed
  7120.         if (!skill.checkCondition(this, target, false))
  7121.         {
  7122.             // Send ActionFailed to the L2PcInstance
  7123.             sendPacket(ActionFailed.STATIC_PACKET);
  7124.             return false;
  7125.         }
  7126.        
  7127.         // ************************************* Check Skill Type *******************************************
  7128.        
  7129.         // Check if this is offensive magic skill
  7130.         if (skill.isOffensive())
  7131.         {
  7132.             if (isInsidePeaceZone(this, target))
  7133.             {
  7134.                 // If L2Character or target is in a peace zone, send a system message TARGET_IN_PEACEZONE ActionFailed
  7135.                 sendPacket(SystemMessageId.TARGET_IN_PEACEZONE);
  7136.                 sendPacket(ActionFailed.STATIC_PACKET);
  7137.                 return false;
  7138.             }
  7139.            
  7140.             if (isInOlympiadMode() && !isOlympiadStart())
  7141.             {
  7142.                 // if L2PcInstance is in Olympia and the match isn't already start, send ActionFailed
  7143.                 sendPacket(ActionFailed.STATIC_PACKET);
  7144.                 return false;
  7145.             }
  7146.            
  7147.             // Check if the target is attackable
  7148.             if (!target.isAttackable() && !getAccessLevel().allowPeaceAttack())
  7149.             {
  7150.                 // If target is not attackable, send ActionFailed
  7151.                 sendPacket(ActionFailed.STATIC_PACKET);
  7152.                 return false;
  7153.             }
  7154.            
  7155.             // Check if a Forced ATTACK is in progress on non-attackable target
  7156.             if (!target.isAutoAttackable(this) && !forceUse)
  7157.             {
  7158.                 switch (sklTargetType)
  7159.                 {
  7160.                     case TARGET_AURA:
  7161.                     case TARGET_FRONT_AURA:
  7162.                     case TARGET_BEHIND_AURA:
  7163.                     case TARGET_AURA_UNDEAD:
  7164.                     case TARGET_CLAN:
  7165.                     case TARGET_ALLY:
  7166.                     case TARGET_PARTY:
  7167.                     case TARGET_SELF:
  7168.                     case TARGET_GROUND:
  7169.                     case TARGET_AREA_SUMMON:
  7170.                         break;
  7171.                     default: // Send ActionFailed to the L2PcInstance
  7172.                         sendPacket(ActionFailed.STATIC_PACKET);
  7173.                         return false;
  7174.                 }
  7175.             }
  7176.            
  7177.             // Check if the target is in the skill cast range
  7178.             if (dontMove)
  7179.             {
  7180.                 // Calculate the distance between the L2PcInstance and the target
  7181.                 if (sklTargetType == SkillTargetType.TARGET_GROUND)
  7182.                 {
  7183.                     if (!isInsideRadius(worldPosition.getX(), worldPosition.getY(), worldPosition.getZ(), skill.getCastRange() + getTemplate().getCollisionRadius(), false, false))
  7184.                     {
  7185.                         // Send a System Message to the caster
  7186.                         sendPacket(SystemMessageId.TARGET_TOO_FAR);
  7187.                        
  7188.                         // Send ActionFailed to the L2PcInstance
  7189.                         sendPacket(ActionFailed.STATIC_PACKET);
  7190.                         return false;
  7191.                     }
  7192.                 }
  7193.                 else if (skill.getCastRange() > 0 && !isInsideRadius(target, skill.getCastRange() + getTemplate().getCollisionRadius(), false, false))
  7194.                 {
  7195.                     // Send a System Message to the caster
  7196.                     sendPacket(SystemMessageId.TARGET_TOO_FAR);
  7197.                    
  7198.                     // Send ActionFailed to the L2PcInstance
  7199.                     sendPacket(ActionFailed.STATIC_PACKET);
  7200.                     return false;
  7201.                 }
  7202.             }
  7203.         }
  7204.        
  7205.         // Check if the skill is defensive
  7206.         if (!skill.isOffensive() && target instanceof L2MonsterInstance && !forceUse)
  7207.         {
  7208.             // check if the target is a monster and if force attack is set.. if not then we don't want to cast.
  7209.             switch (sklTargetType)
  7210.             {
  7211.                 case TARGET_PET:
  7212.                 case TARGET_SUMMON:
  7213.                 case TARGET_AURA:
  7214.                 case TARGET_FRONT_AURA:
  7215.                 case TARGET_BEHIND_AURA:
  7216.                 case TARGET_AURA_UNDEAD:
  7217.                 case TARGET_CLAN:
  7218.                 case TARGET_SELF:
  7219.                 case TARGET_PARTY:
  7220.                 case TARGET_ALLY:
  7221.                 case TARGET_CORPSE_MOB:
  7222.                 case TARGET_AREA_CORPSE_MOB:
  7223.                 case TARGET_GROUND:
  7224.                     break;
  7225.                 default:
  7226.                 {
  7227.                     switch (sklType)
  7228.                     {
  7229.                         case BEAST_FEED:
  7230.                         case DELUXE_KEY_UNLOCK:
  7231.                         case UNLOCK:
  7232.                             break;
  7233.                         default:
  7234.                             sendPacket(ActionFailed.STATIC_PACKET);
  7235.                             return false;
  7236.                     }
  7237.                     break;
  7238.                 }
  7239.             }
  7240.         }
  7241.        
  7242.         // Check if the skill is Spoil type and if the target isn't already spoiled
  7243.         if (sklType == L2SkillType.SPOIL)
  7244.         {
  7245.             if (!(target instanceof L2MonsterInstance))
  7246.             {
  7247.                 // Send a System Message to the L2PcInstance
  7248.                 sendPacket(SystemMessageId.INCORRECT_TARGET);
  7249.                
  7250.                 // Send ActionFailed to the L2PcInstance
  7251.                 sendPacket(ActionFailed.STATIC_PACKET);
  7252.                 return false;
  7253.             }
  7254.         }
  7255.        
  7256.         // Check if the skill is Sweep type and if conditions not apply
  7257.         if (sklType == L2SkillType.SWEEP && target instanceof L2Attackable)
  7258.         {
  7259.             if (((L2Attackable) target).isDead())
  7260.             {
  7261.                 final int spoilerId = ((L2Attackable) target).getIsSpoiledBy();
  7262.                 if (spoilerId == 0)
  7263.                 {
  7264.                     // Send a System Message to the L2PcInstance
  7265.                     sendPacket(SystemMessageId.SWEEPER_FAILED_TARGET_NOT_SPOILED);
  7266.                    
  7267.                     // Send ActionFailed to the L2PcInstance
  7268.                     sendPacket(ActionFailed.STATIC_PACKET);
  7269.                     return false;
  7270.                 }
  7271.                
  7272.                 if (getObjectId() != spoilerId && !isInLooterParty(spoilerId))
  7273.                 {
  7274.                     // Send a System Message to the L2PcInstance
  7275.                     sendPacket(SystemMessageId.SWEEP_NOT_ALLOWED);
  7276.                    
  7277.                     // Send ActionFailed to the L2PcInstance
  7278.                     sendPacket(ActionFailed.STATIC_PACKET);
  7279.                     return false;
  7280.                 }
  7281.             }
  7282.         }
  7283.        
  7284.         // Check if the skill is Drain Soul (Soul Crystals) and if the target is a MOB
  7285.         if (sklType == L2SkillType.DRAIN_SOUL)
  7286.         {
  7287.             if (!(target instanceof L2MonsterInstance))
  7288.             {
  7289.                 // Send a System Message to the L2PcInstance
  7290.                 sendPacket(SystemMessageId.INCORRECT_TARGET);
  7291.                
  7292.                 // Send ActionFailed to the L2PcInstance
  7293.                 sendPacket(ActionFailed.STATIC_PACKET);
  7294.                 return false;
  7295.             }
  7296.         }
  7297.        
  7298.         // Check if this is a Pvp skill and target isn't a non-flagged/non-karma player
  7299.         switch (sklTargetType)
  7300.         {
  7301.             case TARGET_PARTY:
  7302.             case TARGET_ALLY: // For such skills, checkPvpSkill() is called from L2Skill.getTargetList()
  7303.             case TARGET_CLAN: // For such skills, checkPvpSkill() is called from L2Skill.getTargetList()
  7304.             case TARGET_AURA:
  7305.             case TARGET_FRONT_AURA:
  7306.             case TARGET_BEHIND_AURA:
  7307.             case TARGET_AURA_UNDEAD:
  7308.             case TARGET_GROUND:
  7309.             case TARGET_SELF:
  7310.                 break;
  7311.             default:
  7312.                 if (!checkPvpSkill(target, skill) && !getAccessLevel().allowPeaceAttack())
  7313.                 {
  7314.                     // Send a System Message to the L2PcInstance
  7315.                     sendPacket(SystemMessageId.TARGET_IS_INCORRECT);
  7316.                    
  7317.                     // Send ActionFailed to the L2PcInstance
  7318.                     sendPacket(ActionFailed.STATIC_PACKET);
  7319.                     return false;
  7320.                 }
  7321.         }
  7322.        
  7323.         if ((sklTargetType == SkillTargetType.TARGET_HOLY && !checkIfOkToCastSealOfRule(CastleManager.getInstance().getCastle(this), false, skill, target)) || (sklType == L2SkillType.SIEGEFLAG && !L2SkillSiegeFlag.checkIfOkToPlaceFlag(this, false)) || (sklType == L2SkillType.STRSIEGEASSAULT && !checkIfOkToUseStriderSiegeAssault(skill)) || (sklType == L2SkillType.SUMMON_FRIEND && !(checkSummonerStatus(this) && checkSummonTargetStatus(target, this))))
  7324.         {
  7325.             sendPacket(ActionFailed.STATIC_PACKET);
  7326.             abortCast();
  7327.             return false;
  7328.         }
  7329.        
  7330.         // GeoData Los Check here
  7331.         if (skill.getCastRange() > 0)
  7332.         {
  7333.             if (sklTargetType == SkillTargetType.TARGET_GROUND)
  7334.             {
  7335.                 if (!GeoData.getInstance().canSeeTarget(this, worldPosition))
  7336.                 {
  7337.                     sendPacket(SystemMessageId.CANT_SEE_TARGET);
  7338.                     sendPacket(ActionFailed.STATIC_PACKET);
  7339.                     return false;
  7340.                 }
  7341.             }
  7342.             else if (!GeoData.getInstance().canSeeTarget(this, target))
  7343.             {
  7344.                 sendPacket(SystemMessageId.CANT_SEE_TARGET);
  7345.                 sendPacket(ActionFailed.STATIC_PACKET);
  7346.                 return false;
  7347.             }
  7348.         }
  7349.         // finally, after passing all conditions
  7350.         return true;
  7351.     }
  7352.    
  7353.     public boolean checkIfOkToUseStriderSiegeAssault(L2Skill skill)
  7354.     {
  7355.         SystemMessage sm;
  7356.         Castle castle = CastleManager.getInstance().getCastle(this);
  7357.        
  7358.         if (!isRiding())
  7359.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7360.         else if (!(getTarget() instanceof L2DoorInstance))
  7361.             sm = SystemMessage.getSystemMessage(SystemMessageId.INCORRECT_TARGET);
  7362.         else if (castle == null || castle.getCastleId() <= 0)
  7363.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7364.         else if (!castle.getSiege().isInProgress() || castle.getSiege().getAttackerClan(getClan()) == null)
  7365.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7366.         else
  7367.             return true;
  7368.        
  7369.         sendPacket(sm);
  7370.         return false;
  7371.     }
  7372.    
  7373.     public boolean checkIfOkToCastSealOfRule(Castle castle, boolean isCheckOnly, L2Skill skill, L2Object target)
  7374.     {
  7375.         SystemMessage sm;
  7376.        
  7377.         if (castle == null || castle.getCastleId() <= 0)
  7378.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7379.         else if (!castle.getArtefacts().contains(target))
  7380.             sm = SystemMessage.getSystemMessage(SystemMessageId.INCORRECT_TARGET);
  7381.         else if (!castle.getSiege().isInProgress())
  7382.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7383.         else if (!Util.checkIfInRange(200, this, target, true))
  7384.             sm = SystemMessage.getSystemMessage(SystemMessageId.DIST_TOO_FAR_CASTING_STOPPED);
  7385.         else if (!isInsideZone(ZoneId.CAST_ON_ARTIFACT))
  7386.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7387.         else if (castle.getSiege().getAttackerClan(getClan()) == null)
  7388.             sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill);
  7389.         else
  7390.         {
  7391.             if (!isCheckOnly)
  7392.             {
  7393.                 sm = SystemMessage.getSystemMessage(SystemMessageId.OPPONENT_STARTED_ENGRAVING);
  7394.                 castle.getSiege().announceToPlayer(sm, false);
  7395.             }
  7396.             return true;
  7397.         }
  7398.         sendPacket(sm);
  7399.         return false;
  7400.     }
  7401.    
  7402.     public boolean isInLooterParty(int LooterId)
  7403.     {
  7404.         L2PcInstance looter = L2World.getInstance().getPlayer(LooterId);
  7405.        
  7406.         // if L2PcInstance is in a CommandChannel
  7407.         if (isInParty() && getParty().isInCommandChannel() && looter != null)
  7408.             return getParty().getCommandChannel().getMembers().contains(looter);
  7409.        
  7410.         if (isInParty() && looter != null)
  7411.             return getParty().getPartyMembers().contains(looter);
  7412.        
  7413.         return false;
  7414.     }
  7415.    
  7416.     /**
  7417.      * Check if the requested casting is a Pc->Pc skill cast and if it's a valid pvp condition
  7418.      * @param target L2Object instance containing the target
  7419.      * @param skill L2Skill instance with the skill being casted
  7420.      * @return False if the skill is a pvpSkill and target is not a valid pvp target
  7421.      */
  7422.     public boolean checkPvpSkill(L2Object target, L2Skill skill)
  7423.     {
  7424.         return checkPvpSkill(target, skill, false);
  7425.     }
  7426.    
  7427.     /**
  7428.      * Check if the requested casting is a Pc->Pc skill cast and if it's a valid pvp condition
  7429.      * @param target L2Object instance containing the target
  7430.      * @param skill L2Skill instance with the skill being casted
  7431.      * @param srcIsSummon is L2Summon - caster?
  7432.      * @return False if the skill is a pvpSkill and target is not a valid pvp target
  7433.      */
  7434.     public boolean checkPvpSkill(L2Object target, L2Skill skill, boolean srcIsSummon)
  7435.     {
  7436.         // check for PC->PC Pvp status
  7437.         if (target instanceof L2Summon)
  7438.             target = target.getActingPlayer();
  7439.        
  7440.         if (target != null && target != this && target instanceof L2PcInstance && !(isInDuel() && ((L2PcInstance) target).getDuelId() == getDuelId()) && !isInsideZone(ZoneId.PVP) && !target.isInsideZone(ZoneId.PVP))
  7441.         {
  7442.             SkillDat skilldat = getCurrentSkill();
  7443.             SkillDat skilldatpet = getCurrentPetSkill();
  7444.            
  7445.             if (skill.isPvpSkill()) // pvp skill
  7446.             {
  7447.                 // in clan war player can attack whites even with sleep etc.
  7448.                 if (getClan() != null && ((L2PcInstance) target).getClan() != null)
  7449.                 {
  7450.                     if (getClan().isAtWarWith(((L2PcInstance) target).getClan().getClanId()))
  7451.                         return true;
  7452.                 }
  7453.                
  7454.                 // target's pvp flag is not set and target has no karma
  7455.                 if (((L2PcInstance) target).getPvpFlag() == 0 && ((L2PcInstance) target).getKarma() == 0)
  7456.                     return false;
  7457.             }
  7458.             else if ((skilldat != null && !skilldat.isCtrlPressed() && skill.isOffensive() && !srcIsSummon) || (skilldatpet != null && !skilldatpet.isCtrlPressed() && skill.isOffensive() && srcIsSummon))
  7459.             {
  7460.                 // in clan war player can attack whites even with sleep etc.
  7461.                 if (getClan() != null && ((L2PcInstance) target).getClan() != null)
  7462.                 {
  7463.                     if (getClan().isAtWarWith(((L2PcInstance) target).getClan().getClanId()))
  7464.                         return true;
  7465.                 }
  7466.                
  7467.                 // target's pvp flag is not set and target has no karma
  7468.                 if (((L2PcInstance) target).getPvpFlag() == 0 && ((L2PcInstance) target).getKarma() == 0)
  7469.                     return false;
  7470.             }
  7471.         }
  7472.         return true;
  7473.     }
  7474.    
  7475.     /**
  7476.      * @return True if the L2PcInstance is a Mage (based on class templates).
  7477.      */
  7478.     public boolean isMageClass()
  7479.     {
  7480.         return getClassId().isMage();
  7481.     }
  7482.    
  7483.     public boolean isMounted()
  7484.     {
  7485.         return _mountType > 0;
  7486.     }
  7487.    
  7488.     /**
  7489.      * This method allows to :<br>
  7490.      * - change isRiding/isFlying flags;<br>
  7491.      * - gift player with Wyvern Breath skill if mount is a wyvern;;<br>
  7492.      * - send the skillList (faded icons update)
  7493.      * @param npcId the npcId of the mount
  7494.      * @param npcLevel The level of the mount
  7495.      * @param mountType 0, 1 or 2 (dismount, strider or wyvern).
  7496.      * @return always true.
  7497.      */
  7498.     public boolean setMount(int npcId, int npcLevel, int mountType)
  7499.     {
  7500.         switch (mountType)
  7501.         {
  7502.             case 0: // Dismounted
  7503.                 if (isFlying())
  7504.                     removeSkill(FrequentSkill.WYVERN_BREATH.getSkill());
  7505.                 break;
  7506.            
  7507.             case 2: // Flying Wyvern
  7508.                 addSkill(FrequentSkill.WYVERN_BREATH.getSkill(), false); // not saved to DB
  7509.                 break;
  7510.         }
  7511.        
  7512.         _mountNpcId = npcId;
  7513.         _mountType = mountType;
  7514.         _mountLevel = npcLevel;
  7515.        
  7516.         sendSkillList(); // Update faded icons && eventual added skills.
  7517.         return true;
  7518.     }
  7519.    
  7520.     @Override
  7521.     public boolean isRiding()
  7522.     {
  7523.         return _mountType == 1;
  7524.     }
  7525.    
  7526.     @Override
  7527.     public boolean isFlying()
  7528.     {
  7529.         return _mountType == 2;
  7530.     }
  7531.    
  7532.     /**
  7533.      * @return the type of Pet mounted (0 : none, 1 : Strider, 2 : Wyvern).
  7534.      */
  7535.     public int getMountType()
  7536.     {
  7537.         return _mountType;
  7538.     }
  7539.    
  7540.     @Override
  7541.     public final void stopAllEffects()
  7542.     {
  7543.         super.stopAllEffects();
  7544.         updateAndBroadcastStatus(2);
  7545.     }
  7546.    
  7547.     @Override
  7548.     public final void stopAllEffectsExceptThoseThatLastThroughDeath()
  7549.     {
  7550.         super.stopAllEffectsExceptThoseThatLastThroughDeath();
  7551.         updateAndBroadcastStatus(2);
  7552.     }
  7553.    
  7554.     /**
  7555.      * Stop all toggle-type effects
  7556.      */
  7557.     public final void stopAllToggles()
  7558.     {
  7559.         _effects.stopAllToggles();
  7560.     }
  7561.    
  7562.     public final void stopCubics()
  7563.     {
  7564.         if (getCubics() != null)
  7565.         {
  7566.             boolean removed = false;
  7567.             for (L2CubicInstance cubic : getCubics().values())
  7568.             {
  7569.                 cubic.stopAction();
  7570.                 delCubic(cubic.getId());
  7571.                 removed = true;
  7572.             }
  7573.             if (removed)
  7574.                 broadcastUserInfo();
  7575.         }
  7576.     }
  7577.    
  7578.     public final void stopCubicsByOthers()
  7579.     {
  7580.         if (getCubics() != null)
  7581.         {
  7582.             boolean removed = false;
  7583.             for (L2CubicInstance cubic : getCubics().values())
  7584.             {
  7585.                 if (cubic.givenByOther())
  7586.                 {
  7587.                     cubic.stopAction();
  7588.                     delCubic(cubic.getId());
  7589.                     removed = true;
  7590.                 }
  7591.             }
  7592.             if (removed)
  7593.                 broadcastUserInfo();
  7594.         }
  7595.     }
  7596.    
  7597.     /**
  7598.      * Send UserInfo to this L2PcInstance and CharInfo to all L2PcInstance in its _KnownPlayers.<BR>
  7599.      * <BR>
  7600.      * <B><U> Concept</U> :</B><BR>
  7601.      * <BR>
  7602.      * Others L2PcInstance in the detection area of the L2PcInstance are identified in <B>_knownPlayers</B>. In order to inform other players of this L2PcInstance state modifications, server just need to go through _knownPlayers to send Server->Client Packet<BR>
  7603.      * <BR>
  7604.      * <B><U> Actions</U> :</B><BR>
  7605.      * <BR>
  7606.      * <li>Send UserInfo to this L2PcInstance (Public and Private Data)</li> <li>Send CharInfo to all L2PcInstance in _KnownPlayers of the L2PcInstance (Public data only)</li><BR>
  7607.      * <BR>
  7608.      * <FONT COLOR=#FF0000><B> <U>Caution</U> : DON'T SEND UserInfo packet to other players instead of CharInfo packet. Indeed, UserInfo packet contains PRIVATE DATA as MaxHP, STR, DEX...</B></FONT><BR>
  7609.      * <BR>
  7610.      */
  7611.     @Override
  7612.     public void updateAbnormalEffect()
  7613.     {
  7614.         broadcastUserInfo();
  7615.     }
  7616.    
  7617.     /**
  7618.      * Disable the Inventory and create a new task to enable it after 1.5s.
  7619.      */
  7620.     public void tempInventoryDisable()
  7621.     {
  7622.         _inventoryDisable = true;
  7623.        
  7624.         ThreadPoolManager.getInstance().scheduleGeneral(new InventoryEnable(), 1500);
  7625.     }
  7626.    
  7627.     /**
  7628.      * @return True if the Inventory is disabled.
  7629.      */
  7630.     public boolean isInventoryDisabled()
  7631.     {
  7632.         return _inventoryDisable;
  7633.     }
  7634.    
  7635.     protected class InventoryEnable implements Runnable
  7636.     {
  7637.         @Override
  7638.         public void run()
  7639.         {
  7640.             _inventoryDisable = false;
  7641.         }
  7642.     }
  7643.    
  7644.     public Map<Integer, L2CubicInstance> getCubics()
  7645.     {
  7646.         return _cubics;
  7647.     }
  7648.    
  7649.     /**
  7650.      * Add a L2CubicInstance to the L2PcInstance _cubics.
  7651.      * @param id
  7652.      * @param level
  7653.      * @param matk
  7654.      * @param activationtime
  7655.      * @param activationchance
  7656.      * @param totalLifetime
  7657.      * @param givenByOther
  7658.      */
  7659.     public void addCubic(int id, int level, double matk, int activationtime, int activationchance, int totalLifetime, boolean givenByOther)
  7660.     {
  7661.         if (Config.DEBUG)
  7662.             _log.info("L2PcInstance(" + getName() + "): addCubic(" + id + "|" + level + "|" + matk + ")");
  7663.        
  7664.         L2CubicInstance cubic = new L2CubicInstance(this, id, level, (int) matk, activationtime, activationchance, totalLifetime, givenByOther);
  7665.         _cubics.put(id, cubic);
  7666.     }
  7667.    
  7668.     /**
  7669.      * Remove a L2CubicInstance from the L2PcInstance _cubics.
  7670.      * @param id
  7671.      */
  7672.     public void delCubic(int id)
  7673.     {
  7674.         _cubics.remove(id);
  7675.     }
  7676.    
  7677.     /**
  7678.      * @param id
  7679.      * @return the L2CubicInstance corresponding to the Identifier of the L2PcInstance _cubics.
  7680.      */
  7681.     public L2CubicInstance getCubic(int id)
  7682.     {
  7683.         return _cubics.get(id);
  7684.     }
  7685.    
  7686.     @Override
  7687.     public String toString()
  7688.     {
  7689.         return "player " + getName();
  7690.     }
  7691.    
  7692.     /**
  7693.      * @return the modifier corresponding to the Enchant Effect of the Active Weapon (Min : 127).
  7694.      */
  7695.     public int getEnchantEffect()
  7696.     {
  7697.         L2ItemInstance wpn = getActiveWeaponInstance();
  7698.        
  7699.         if (wpn == null)
  7700.             return 0;
  7701.        
  7702.         return Math.min(127, wpn.getEnchantLevel());
  7703.     }
  7704.    
  7705.     /**
  7706.      * Set the _currentFolkNpc of the player.
  7707.      * @param npc
  7708.      */
  7709.     public void setCurrentFolkNPC(L2Npc npc)
  7710.     {
  7711.         _currentFolkNpc = npc;
  7712.     }
  7713.    
  7714.     /**
  7715.      * @return the _currentFolkNpc of the player.
  7716.      */
  7717.     public L2Npc getCurrentFolkNPC()
  7718.     {
  7719.         return _currentFolkNpc;
  7720.     }
  7721.    
  7722.     /**
  7723.      * @return True if L2PcInstance is a participant in the Festival of Darkness.
  7724.      */
  7725.     public boolean isFestivalParticipant()
  7726.     {
  7727.         return SevenSignsFestival.getInstance().isParticipant(this);
  7728.     }
  7729.    
  7730.     public void addAutoSoulShot(int itemId)
  7731.     {
  7732.         _activeSoulShots.add(itemId);
  7733.     }
  7734.    
  7735.     public boolean removeAutoSoulShot(int itemId)
  7736.     {
  7737.         return _activeSoulShots.remove(itemId);
  7738.     }
  7739.    
  7740.     public Set<Integer> getAutoSoulShot()
  7741.     {
  7742.         return _activeSoulShots;
  7743.     }
  7744.    
  7745.     @Override
  7746.     public boolean isChargedShot(ShotType type)
  7747.     {
  7748.         L2ItemInstance weapon = getActiveWeaponInstance();
  7749.         return weapon != null && weapon.isChargedShot(type);
  7750.     }
  7751.    
  7752.     @Override
  7753.     public void setChargedShot(ShotType type, boolean charged)
  7754.     {
  7755.         L2ItemInstance weapon = getActiveWeaponInstance();
  7756.         if (weapon != null)
  7757.             weapon.setChargedShot(type, charged);
  7758.     }
  7759.    
  7760.     @Override
  7761.     public void rechargeShots(boolean physical, boolean magic)
  7762.     {
  7763.         if (_activeSoulShots == null || _activeSoulShots.isEmpty())
  7764.             return;
  7765.        
  7766.         for (int itemId : _activeSoulShots)
  7767.         {
  7768.             L2ItemInstance item = getInventory().getItemByItemId(itemId);
  7769.             if (item != null)
  7770.             {
  7771.                 if (magic && item.getItem().getDefaultAction() == L2ActionType.spiritshot)
  7772.                 {
  7773.                     IItemHandler handler = ItemHandler.getInstance().getItemHandler(item.getEtcItem());
  7774.                     if (handler != null)
  7775.                         handler.useItem(this, item, false);
  7776.                 }
  7777.                
  7778.                 if (physical && item.getItem().getDefaultAction() == L2ActionType.soulshot)
  7779.                 {
  7780.                     IItemHandler handler = ItemHandler.getInstance().getItemHandler(item.getEtcItem());
  7781.                     if (handler != null)
  7782.                         handler.useItem(this, item, false);
  7783.                 }
  7784.             }
  7785.             else
  7786.                 removeAutoSoulShot(itemId);
  7787.         }
  7788.     }
  7789.    
  7790.     /**
  7791.      * Cancel autoshot use for shot itemId
  7792.      * @param itemId int id to disable
  7793.      * @return true if canceled.
  7794.      */
  7795.     public boolean disableAutoShot(int itemId)
  7796.     {
  7797.         if (_activeSoulShots.contains(itemId))
  7798.         {
  7799.             removeAutoSoulShot(itemId);
  7800.             sendPacket(new ExAutoSoulShot(itemId, 0));
  7801.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.AUTO_USE_OF_S1_CANCELLED).addItemName(itemId));
  7802.             return true;
  7803.         }
  7804.        
  7805.         return false;
  7806.     }
  7807.    
  7808.     /**
  7809.      * Cancel all autoshots for player
  7810.      */
  7811.     public void disableAutoShotsAll()
  7812.     {
  7813.         for (int itemId : _activeSoulShots)
  7814.         {
  7815.             sendPacket(new ExAutoSoulShot(itemId, 0));
  7816.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.AUTO_USE_OF_S1_CANCELLED).addItemName(itemId));
  7817.         }
  7818.         _activeSoulShots.clear();
  7819.     }
  7820.    
  7821.     class LookingForFishTask implements Runnable
  7822.     {
  7823.         boolean _isNoob, _isUpperGrade;
  7824.         int _fishType, _fishGutsCheck;
  7825.         long _endTaskTime;
  7826.        
  7827.         protected LookingForFishTask(int fishWaitTime, int fishGutsCheck, int fishType, boolean isNoob, boolean isUpperGrade)
  7828.         {
  7829.             _fishGutsCheck = fishGutsCheck;
  7830.             _endTaskTime = System.currentTimeMillis() + fishWaitTime + 10000;
  7831.             _fishType = fishType;
  7832.             _isNoob = isNoob;
  7833.             _isUpperGrade = isUpperGrade;
  7834.         }
  7835.        
  7836.         @Override
  7837.         public void run()
  7838.         {
  7839.             if (System.currentTimeMillis() >= _endTaskTime)
  7840.             {
  7841.                 endFishing(false);
  7842.                 return;
  7843.             }
  7844.            
  7845.             if (_fishType == -1)
  7846.                 return;
  7847.            
  7848.             int check = Rnd.get(1000);
  7849.             if (_fishGutsCheck > check)
  7850.             {
  7851.                 stopLookingForFishTask();
  7852.                 startFishCombat(_isNoob, _isUpperGrade);
  7853.             }
  7854.         }
  7855.     }
  7856.    
  7857.     public int getClanPrivileges()
  7858.     {
  7859.         return _clanPrivileges;
  7860.     }
  7861.    
  7862.     public void setClanPrivileges(int n)
  7863.     {
  7864.         _clanPrivileges = n;
  7865.     }
  7866.    
  7867.     // baron etc
  7868.     public void setPledgeClass(int classId)
  7869.     {
  7870.         _pledgeClass = classId;
  7871.     }
  7872.    
  7873.     public int getPledgeClass()
  7874.     {
  7875.         return _pledgeClass;
  7876.     }
  7877.    
  7878.     public void setPledgeType(int typeId)
  7879.     {
  7880.         _pledgeType = typeId;
  7881.     }
  7882.    
  7883.     public int getPledgeType()
  7884.     {
  7885.         return _pledgeType;
  7886.     }
  7887.    
  7888.     public int getApprentice()
  7889.     {
  7890.         return _apprentice;
  7891.     }
  7892.    
  7893.     public void setApprentice(int apprentice_id)
  7894.     {
  7895.         _apprentice = apprentice_id;
  7896.     }
  7897.    
  7898.     public int getSponsor()
  7899.     {
  7900.         return _sponsor;
  7901.     }
  7902.    
  7903.     public void setSponsor(int sponsor_id)
  7904.     {
  7905.         _sponsor = sponsor_id;
  7906.     }
  7907.    
  7908.     @Override
  7909.     public void sendMessage(String message)
  7910.     {
  7911.         sendPacket(SystemMessage.sendString(message));
  7912.     }
  7913.    
  7914.     /**
  7915.      * Unsummon all types of summons : pets, cubics, normal summons and trained beasts.
  7916.      */
  7917.     public void dropAllSummons()
  7918.     {
  7919.         // Delete summons and pets
  7920.         if (getPet() != null)
  7921.             getPet().unSummon(this);
  7922.        
  7923.         // Delete trained beasts
  7924.         if (getTrainedBeast() != null)
  7925.             getTrainedBeast().deleteMe();
  7926.        
  7927.         // Delete any form of cubics
  7928.         stopCubics();
  7929.     }
  7930.    
  7931.     public void enterObserverMode(int x, int y, int z)
  7932.     {
  7933.         _lastX = getX();
  7934.         _lastY = getY();
  7935.         _lastZ = getZ();
  7936.        
  7937.         _observerMode = true;
  7938.        
  7939.         if (isSitting())
  7940.             standUp();
  7941.        
  7942.         dropAllSummons();
  7943.         setTarget(null);
  7944.         setIsParalyzed(true);
  7945.         startParalyze();
  7946.         setIsInvul(true);
  7947.         getAppearance().setInvisible();
  7948.        
  7949.         sendPacket(new ObservationMode(x, y, z));
  7950.         getKnownList().removeAllKnownObjects(); // reinit knownlist
  7951.         setXYZ(x, y, z);
  7952.        
  7953.         broadcastUserInfo();
  7954.     }
  7955.    
  7956.     public void setLastCords(int x, int y, int z)
  7957.     {
  7958.         _lastX = getX();
  7959.         _lastY = getY();
  7960.         _lastZ = getZ();
  7961.     }
  7962.    
  7963.     public void enterOlympiadObserverMode(int id)
  7964.     {
  7965.         final OlympiadGameTask task = OlympiadGameManager.getInstance().getOlympiadTask(id);
  7966.         if (task == null)
  7967.             return;
  7968.        
  7969.         dropAllSummons();
  7970.        
  7971.         if (getParty() != null)
  7972.             getParty().removePartyMember(this, true);
  7973.        
  7974.         _olympiadGameId = id;
  7975.        
  7976.         if (isSitting())
  7977.             standUp();
  7978.        
  7979.         if (!_observerMode)
  7980.         {
  7981.             _lastX = getX();
  7982.             _lastY = getY();
  7983.             _lastZ = getZ();
  7984.         }
  7985.        
  7986.         _observerMode = true;
  7987.         setTarget(null);
  7988.         setIsInvul(true);
  7989.         getAppearance().setInvisible();
  7990.         teleToLocation(task.getZone().getSpawns().get(2), 0);
  7991.         sendPacket(new ExOlympiadMode(3));
  7992.         broadcastUserInfo();
  7993.     }
  7994.    
  7995.     public void leaveObserverMode()
  7996.     {
  7997.         setTarget(null);
  7998.         getKnownList().removeAllKnownObjects(); // reinit knownlist
  7999.         setXYZ(_lastX, _lastY, _lastZ);
  8000.         setIsParalyzed(false);
  8001.         stopParalyze(false);
  8002.         getAppearance().setVisible();
  8003.         setIsInvul(false);
  8004.        
  8005.         if (hasAI())
  8006.             getAI().setIntention(CtrlIntention.IDLE);
  8007.        
  8008.         // prevent receive falling damage
  8009.         setFalling();
  8010.        
  8011.         _observerMode = false;
  8012.         setLastCords(0, 0, 0);
  8013.         sendPacket(new ObservationReturn(this));
  8014.         broadcastUserInfo();
  8015.     }
  8016.    
  8017.     public void leaveOlympiadObserverMode()
  8018.     {
  8019.         if (_olympiadGameId == -1)
  8020.             return;
  8021.        
  8022.         _olympiadGameId = -1;
  8023.         _observerMode = false;
  8024.        
  8025.         setTarget(null);
  8026.         sendPacket(new ExOlympiadMode(0));
  8027.         teleToLocation(_lastX, _lastY, _lastZ, 20);
  8028.         getAppearance().setVisible();
  8029.         setIsInvul(false);
  8030.        
  8031.         if (hasAI())
  8032.             getAI().setIntention(CtrlIntention.IDLE);
  8033.        
  8034.         setLastCords(0, 0, 0);
  8035.         broadcastUserInfo();
  8036.     }
  8037.    
  8038.     public void setOlympiadSide(int i)
  8039.     {
  8040.         _olympiadSide = i;
  8041.     }
  8042.    
  8043.     public int getOlympiadSide()
  8044.     {
  8045.         return _olympiadSide;
  8046.     }
  8047.    
  8048.     public void setOlympiadGameId(int id)
  8049.     {
  8050.         _olympiadGameId = id;
  8051.     }
  8052.    
  8053.     public int getOlympiadGameId()
  8054.     {
  8055.         return _olympiadGameId;
  8056.     }
  8057.    
  8058.     public int getLastX()
  8059.     {
  8060.         return _lastX;
  8061.     }
  8062.    
  8063.     public int getLastY()
  8064.     {
  8065.         return _lastY;
  8066.     }
  8067.    
  8068.     public int getLastZ()
  8069.     {
  8070.         return _lastZ;
  8071.     }
  8072.    
  8073.     public boolean inObserverMode()
  8074.     {
  8075.         return _observerMode;
  8076.     }
  8077.    
  8078.     public int getTeleMode()
  8079.     {
  8080.         return _telemode;
  8081.     }
  8082.    
  8083.     public void setTeleMode(int mode)
  8084.     {
  8085.         _telemode = mode;
  8086.     }
  8087.    
  8088.     public void setLoto(int i, int val)
  8089.     {
  8090.         _loto[i] = val;
  8091.     }
  8092.    
  8093.     public int getLoto(int i)
  8094.     {
  8095.         return _loto[i];
  8096.     }
  8097.    
  8098.     public void setRace(int i, int val)
  8099.     {
  8100.         _race[i] = val;
  8101.     }
  8102.    
  8103.     public int getRace(int i)
  8104.     {
  8105.         return _race[i];
  8106.     }
  8107.    
  8108.     public boolean isInRefusalMode()
  8109.     {
  8110.         return _messageRefusal;
  8111.     }
  8112.    
  8113.     public void setInRefusalMode(boolean mode)
  8114.     {
  8115.         _messageRefusal = mode;
  8116.         sendPacket(new EtcStatusUpdate(this));
  8117.     }
  8118.    
  8119.     public void setTradeRefusal(boolean mode)
  8120.     {
  8121.         _tradeRefusal = mode;
  8122.     }
  8123.    
  8124.     public boolean getTradeRefusal()
  8125.     {
  8126.         return _tradeRefusal;
  8127.     }
  8128.    
  8129.     public void setExchangeRefusal(boolean mode)
  8130.     {
  8131.         _exchangeRefusal = mode;
  8132.     }
  8133.    
  8134.     public boolean getExchangeRefusal()
  8135.     {
  8136.         return _exchangeRefusal;
  8137.     }
  8138.    
  8139.     public BlockList getBlockList()
  8140.     {
  8141.         return _blockList;
  8142.     }
  8143.    
  8144.     public void setHero(boolean hero)
  8145.     {
  8146.         if (hero)
  8147.         {
  8148.             for (L2Skill s : SkillTable.getHeroSkills())
  8149.                 addSkill(s, false); // Dont Save Hero skills to database
  8150.         }
  8151.         else
  8152.         {
  8153.             for (L2Skill s : SkillTable.getHeroSkills())
  8154.                 super.removeSkill(s); // Just Remove skills from nonHero characters
  8155.         }
  8156.         _hero = hero;
  8157.        
  8158.         sendSkillList();
  8159.     }
  8160.    
  8161.     public void setIsInOlympiadMode(boolean b)
  8162.     {
  8163.         _inOlympiadMode = b;
  8164.     }
  8165.    
  8166.     public void setIsOlympiadStart(boolean b)
  8167.     {
  8168.         _OlympiadStart = b;
  8169.     }
  8170.    
  8171.     public boolean isOlympiadStart()
  8172.     {
  8173.         return _OlympiadStart;
  8174.     }
  8175.    
  8176.     public boolean isHero()
  8177.     {
  8178.         return _hero;
  8179.     }
  8180.    
  8181.     public boolean isInOlympiadMode()
  8182.     {
  8183.         return _inOlympiadMode;
  8184.     }
  8185.    
  8186.     public boolean isInDuel()
  8187.     {
  8188.         return _isInDuel;
  8189.     }
  8190.    
  8191.     public int getDuelId()
  8192.     {
  8193.         return _duelId;
  8194.     }
  8195.    
  8196.     public void setDuelState(int mode)
  8197.     {
  8198.         _duelState = mode;
  8199.     }
  8200.    
  8201.     public int getDuelState()
  8202.     {
  8203.         return _duelState;
  8204.     }
  8205.    
  8206.     /**
  8207.      * Sets up the duel state using a non 0 duelId.
  8208.      * @param duelId 0=not in a duel
  8209.      */
  8210.     public void setIsInDuel(int duelId)
  8211.     {
  8212.         if (duelId > 0)
  8213.         {
  8214.             _isInDuel = true;
  8215.             _duelState = Duel.DUELSTATE_DUELLING;
  8216.             _duelId = duelId;
  8217.         }
  8218.         else
  8219.         {
  8220.             if (_duelState == Duel.DUELSTATE_DEAD)
  8221.             {
  8222.                 enableAllSkills();
  8223.                 getStatus().startHpMpRegeneration();
  8224.             }
  8225.             _isInDuel = false;
  8226.             _duelState = Duel.DUELSTATE_NODUEL;
  8227.             _duelId = 0;
  8228.         }
  8229.     }
  8230.    
  8231.     /**
  8232.      * This returns a SystemMessage stating why the player is not available for duelling.
  8233.      * @return S1_CANNOT_DUEL... message
  8234.      */
  8235.     public SystemMessage getNoDuelReason()
  8236.     {
  8237.         SystemMessage sm = SystemMessage.getSystemMessage(_noDuelReason);
  8238.         sm.addPcName(this);
  8239.         _noDuelReason = SystemMessageId.THERE_IS_NO_OPPONENT_TO_RECEIVE_YOUR_CHALLENGE_FOR_A_DUEL;
  8240.         return sm;
  8241.     }
  8242.    
  8243.     /**
  8244.      * Checks if this player might join / start a duel. To get the reason use getNoDuelReason() after calling this function.
  8245.      * @return true if the player might join/start a duel.
  8246.      */
  8247.     public boolean canDuel()
  8248.     {
  8249.         if (isInCombat() || getPunishLevel() == PunishLevel.JAIL)
  8250.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_CURRENTLY_ENGAGED_IN_BATTLE;
  8251.         else if (isDead() || isAlikeDead() || (getCurrentHp() < getMaxHp() / 2 || getCurrentMp() < getMaxMp() / 2))
  8252.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_HP_OR_MP_IS_BELOW_50_PERCENT;
  8253.         else if (isInDuel())
  8254.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_ALREADY_ENGAGED_IN_A_DUEL;
  8255.         else if (isInOlympiadMode())
  8256.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_PARTICIPATING_IN_THE_OLYMPIAD;
  8257.         else if (isCursedWeaponEquipped())
  8258.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_IN_A_CHAOTIC_STATE;
  8259.         else if (isInStoreMode())
  8260.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_CURRENTLY_ENGAGED_IN_A_PRIVATE_STORE_OR_MANUFACTURE;
  8261.         else if (isMounted() || isInBoat())
  8262.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_CURRENTLY_RIDING_A_BOAT_WYVERN_OR_STRIDER;
  8263.         else if (isFishing())
  8264.             _noDuelReason = SystemMessageId.S1_CANNOT_DUEL_BECAUSE_S1_IS_CURRENTLY_FISHING;
  8265.         else if (isInsideZone(ZoneId.PVP) || isInsideZone(ZoneId.PEACE) || isInsideZone(ZoneId.SIEGE))
  8266.             _noDuelReason = SystemMessageId.S1_CANNOT_MAKE_A_CHALLANGE_TO_A_DUEL_BECAUSE_S1_IS_CURRENTLY_IN_A_DUEL_PROHIBITED_AREA;
  8267.         else
  8268.             return true;
  8269.        
  8270.         return false;
  8271.     }
  8272.    
  8273.     public boolean isNoble()
  8274.     {
  8275.         return _noble;
  8276.     }
  8277.    
  8278.     /**
  8279.      * Set Noblesse Status, and reward with nobles' skills.
  8280.      * @param val Add skills if setted to true, else remove skills.
  8281.      * @param store Store the status directly in the db if setted to true.
  8282.      */
  8283.     public void setNoble(boolean val, boolean store)
  8284.     {
  8285.         if (val)
  8286.             for (L2Skill s : SkillTable.getNobleSkills())
  8287.                 addSkill(s, false); // Dont Save Noble skills to Sql
  8288.         else
  8289.             for (L2Skill s : SkillTable.getNobleSkills())
  8290.                 super.removeSkill(s); // Just Remove skills without deleting from Sql
  8291.            
  8292.         _noble = val;
  8293.        
  8294.         sendSkillList();
  8295.        
  8296.         if (store)
  8297.         {
  8298.             try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  8299.             {
  8300.                 PreparedStatement statement = con.prepareStatement(UPDATE_NOBLESS);
  8301.                 statement.setBoolean(1, val);
  8302.                 statement.setInt(2, getObjectId());
  8303.                 statement.executeUpdate();
  8304.                 statement.close();
  8305.             }
  8306.             catch (Exception e)
  8307.             {
  8308.                 _log.log(Level.WARNING, "Could not update " + getName() + " nobless status: " + e.getMessage(), e);
  8309.             }
  8310.         }
  8311.     }
  8312.    
  8313.     public void setLvlJoinedAcademy(int lvl)
  8314.     {
  8315.         _lvlJoinedAcademy = lvl;
  8316.     }
  8317.    
  8318.     public int getLvlJoinedAcademy()
  8319.     {
  8320.         return _lvlJoinedAcademy;
  8321.     }
  8322.    
  8323.     public boolean isAcademyMember()
  8324.     {
  8325.         return _lvlJoinedAcademy > 0;
  8326.     }
  8327.    
  8328.     public void setTeam(int team)
  8329.     {
  8330.         _team = team;
  8331.     }
  8332.    
  8333.     public int getTeam()
  8334.     {
  8335.         return _team;
  8336.     }
  8337.    
  8338.     public void setWantsPeace(boolean wantsPeace)
  8339.     {
  8340.         _wantsPeace = wantsPeace;
  8341.     }
  8342.    
  8343.     public boolean wantsPeace()
  8344.     {
  8345.         return _wantsPeace;
  8346.     }
  8347.    
  8348.     public boolean isFishing()
  8349.     {
  8350.         return _fishingLoc != null;
  8351.     }
  8352.    
  8353.     public void setAllianceWithVarkaKetra(int sideAndLvlOfAlliance)
  8354.     {
  8355.         _alliedVarkaKetra = sideAndLvlOfAlliance;
  8356.     }
  8357.    
  8358.     /**
  8359.      * [-5,-1] varka, 0 neutral, [1,5] ketra
  8360.      * @return the side faction.
  8361.      */
  8362.     public int getAllianceWithVarkaKetra()
  8363.     {
  8364.         return _alliedVarkaKetra;
  8365.     }
  8366.    
  8367.     public boolean isAlliedWithVarka()
  8368.     {
  8369.         return (_alliedVarkaKetra < 0);
  8370.     }
  8371.    
  8372.     public boolean isAlliedWithKetra()
  8373.     {
  8374.         return (_alliedVarkaKetra > 0);
  8375.     }
  8376.    
  8377.     public void sendSkillList()
  8378.     {
  8379.         final L2ItemInstance formal = getInventory().getPaperdollItem(Inventory.PAPERDOLL_CHEST);
  8380.         final boolean isWearingFormalWear = formal != null && formal.getItem().getBodyPart() == L2Item.SLOT_ALLDRESS;
  8381.        
  8382.         boolean isDisabled = false;
  8383.         SkillList sl = new SkillList();
  8384.         for (L2Skill s : getAllSkills())
  8385.         {
  8386.             if (s == null)
  8387.                 continue;
  8388.            
  8389.             if (s.getId() > 9000 && s.getId() < 9007)
  8390.                 continue; // Fake skills to change base stats
  8391.                
  8392.             if (getClan() != null)
  8393.                 isDisabled = s.isClanSkill() && getClan().getReputationScore() < 0;
  8394.            
  8395.             if (isCursedWeaponEquipped()) // Only Demonic skills are available
  8396.                 isDisabled = !s.isDemonicSkill();
  8397.             else if (isMounted()) // else if, because only ONE state is possible
  8398.             {
  8399.                 if (getMountType() == 1) // Only Strider skills are available
  8400.                     isDisabled = !s.isStriderSkill();
  8401.                 else if (getMountType() == 2) // Only Wyvern skills are available
  8402.                     isDisabled = !s.isFlyingSkill();
  8403.             }
  8404.            
  8405.             if (isWearingFormalWear)
  8406.                 isDisabled = true;
  8407.            
  8408.             sl.addSkill(s.getId(), s.getLevel(), s.isPassive(), isDisabled);
  8409.         }
  8410.         sendPacket(sl);
  8411.     }
  8412.    
  8413.     /**
  8414.      * 1. Add the specified class ID as a subclass (up to the maximum number of <b>three</b>) for this character.<BR>
  8415.      * 2. This method no longer changes the active _classIndex of the player. This is only done by the calling of setActiveClass() method as that should be the only way to do so.
  8416.      * @param classId
  8417.      * @param classIndex
  8418.      * @return boolean subclassAdded
  8419.      */
  8420.     public boolean addSubClass(int classId, int classIndex)
  8421.     {
  8422.         if (!_subclassLock.tryLock())
  8423.             return false;
  8424.        
  8425.         try
  8426.         {
  8427.             if (getTotalSubClasses() == 3 || classIndex == 0)
  8428.                 return false;
  8429.            
  8430.             if (getSubClasses().containsKey(classIndex))
  8431.                 return false;
  8432.            
  8433.             // Note: Never change _classIndex in any method other than setActiveClass().
  8434.            
  8435.             SubClass newClass = new SubClass();
  8436.             newClass.setClassId(classId);
  8437.             newClass.setClassIndex(classIndex);
  8438.            
  8439.             try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  8440.             {
  8441.                 PreparedStatement statement = con.prepareStatement(ADD_CHAR_SUBCLASS);
  8442.                 statement.setInt(1, getObjectId());
  8443.                 statement.setInt(2, newClass.getClassId());
  8444.                 statement.setLong(3, newClass.getExp());
  8445.                 statement.setInt(4, newClass.getSp());
  8446.                 statement.setInt(5, newClass.getLevel());
  8447.                 statement.setInt(6, newClass.getClassIndex()); // <-- Added
  8448.                
  8449.                 statement.execute();
  8450.                 statement.close();
  8451.             }
  8452.             catch (Exception e)
  8453.             {
  8454.                 _log.warning("WARNING: Could not add character sub class for " + getName() + ": " + e);
  8455.                 return false;
  8456.             }
  8457.            
  8458.             // Commit after database INSERT incase exception is thrown.
  8459.             getSubClasses().put(newClass.getClassIndex(), newClass);
  8460.            
  8461.             if (Config.DEBUG)
  8462.                 _log.info(getName() + " added class ID " + classId + " as a sub class at index " + classIndex + ".");
  8463.            
  8464.             ClassId subTemplate = ClassId.values()[classId];
  8465.             Collection<L2SkillLearn> skillTree = SkillTreeTable.getInstance().getAllowedSkills(subTemplate);
  8466.            
  8467.             if (skillTree == null)
  8468.                 return true;
  8469.            
  8470.             final Map<Integer, L2Skill> prevSkillList = new LinkedHashMap<>();
  8471.            
  8472.             for (L2SkillLearn skillInfo : skillTree)
  8473.             {
  8474.                 if (skillInfo.getMinLevel() <= 40)
  8475.                 {
  8476.                     L2Skill prevSkill = prevSkillList.get(skillInfo.getId());
  8477.                     L2Skill newSkill = SkillTable.getInstance().getInfo(skillInfo.getId(), skillInfo.getLevel());
  8478.                    
  8479.                     if (prevSkill != null && (prevSkill.getLevel() > newSkill.getLevel()))
  8480.                         continue;
  8481.                    
  8482.                     prevSkillList.put(newSkill.getId(), newSkill);
  8483.                     storeSkill(newSkill, prevSkill, classIndex);
  8484.                 }
  8485.             }
  8486.            
  8487.             if (Config.DEBUG)
  8488.                 _log.info(getName() + " was given " + getAllSkills().length + " skills for their new sub class.");
  8489.            
  8490.             return true;
  8491.         }
  8492.         finally
  8493.         {
  8494.             _subclassLock.unlock();
  8495.         }
  8496.     }
  8497.    
  8498.     /**
  8499.      * 1. Completely erase all existance of the subClass linked to the classIndex.<BR>
  8500.      * 2. Send over the newClassId to addSubClass()to create a new instance on this classIndex.<BR>
  8501.      * 3. Upon Exception, revert the player to their BaseClass to avoid further problems.<BR>
  8502.      * @param classIndex
  8503.      * @param newClassId
  8504.      * @return boolean subclassAdded
  8505.      */
  8506.     public boolean modifySubClass(int classIndex, int newClassId)
  8507.     {
  8508.         if (!_subclassLock.tryLock())
  8509.             return false;
  8510.        
  8511.         try
  8512.         {
  8513.             int oldClassId = getSubClasses().get(classIndex).getClassId();
  8514.            
  8515.             if (Config.DEBUG)
  8516.                 _log.info(getName() + " has requested to modify sub class index " + classIndex + " from class ID " + oldClassId + " to " + newClassId + ".");
  8517.            
  8518.             try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  8519.             {
  8520.                 // Remove all henna info stored for this sub-class.
  8521.                 PreparedStatement statement = con.prepareStatement(DELETE_CHAR_HENNAS);
  8522.                 statement.setInt(1, getObjectId());
  8523.                 statement.setInt(2, classIndex);
  8524.                 statement.execute();
  8525.                 statement.close();
  8526.                
  8527.                 // Remove all shortcuts info stored for this sub-class.
  8528.                 statement = con.prepareStatement(DELETE_CHAR_SHORTCUTS);
  8529.                 statement.setInt(1, getObjectId());
  8530.                 statement.setInt(2, classIndex);
  8531.                 statement.execute();
  8532.                 statement.close();
  8533.                
  8534.                 // Remove all effects info stored for this sub-class.
  8535.                 statement = con.prepareStatement(DELETE_SKILL_SAVE);
  8536.                 statement.setInt(1, getObjectId());
  8537.                 statement.setInt(2, classIndex);
  8538.                 statement.execute();
  8539.                 statement.close();
  8540.                
  8541.                 // Remove all skill info stored for this sub-class.
  8542.                 statement = con.prepareStatement(DELETE_CHAR_SKILLS);
  8543.                 statement.setInt(1, getObjectId());
  8544.                 statement.setInt(2, classIndex);
  8545.                 statement.execute();
  8546.                 statement.close();
  8547.                
  8548.                 // Remove all basic info stored about this sub-class.
  8549.                 statement = con.prepareStatement(DELETE_CHAR_SUBCLASS);
  8550.                 statement.setInt(1, getObjectId());
  8551.                 statement.setInt(2, classIndex);
  8552.                 statement.execute();
  8553.                 statement.close();
  8554.             }
  8555.             catch (Exception e)
  8556.             {
  8557.                 _log.warning("Could not modify subclass for " + getName() + " to class index " + classIndex + ": " + e);
  8558.                
  8559.                 // This must be done in order to maintain data consistency.
  8560.                 getSubClasses().remove(classIndex);
  8561.                 return false;
  8562.             }
  8563.            
  8564.             getSubClasses().remove(classIndex);
  8565.         }
  8566.         finally
  8567.         {
  8568.             _subclassLock.unlock();
  8569.         }
  8570.        
  8571.         return addSubClass(newClassId, classIndex);
  8572.     }
  8573.    
  8574.     public boolean isSubClassActive()
  8575.     {
  8576.         return _classIndex > 0;
  8577.     }
  8578.    
  8579.     public Map<Integer, SubClass> getSubClasses()
  8580.     {
  8581.         return _subClasses;
  8582.     }
  8583.    
  8584.     public int getTotalSubClasses()
  8585.     {
  8586.         return getSubClasses().size();
  8587.     }
  8588.    
  8589.     public int getBaseClass()
  8590.     {
  8591.         return _baseClass;
  8592.     }
  8593.    
  8594.     public int getActiveClass()
  8595.     {
  8596.         return _activeClass;
  8597.     }
  8598.    
  8599.     public int getClassIndex()
  8600.     {
  8601.         return _classIndex;
  8602.     }
  8603.    
  8604.     private void setClassTemplate(int classId)
  8605.     {
  8606.         _activeClass = classId;
  8607.        
  8608.         L2PcTemplate t = CharTemplateTable.getInstance().getTemplate(classId);
  8609.        
  8610.         if (t == null)
  8611.         {
  8612.             _log.severe("Missing template for classId: " + classId);
  8613.             throw new Error();
  8614.         }
  8615.        
  8616.         // Set the template of the L2PcInstance
  8617.         setTemplate(t);
  8618.     }
  8619.    
  8620.     /**
  8621.      * Changes the character's class based on the given class index. <BR>
  8622.      * <BR>
  8623.      * An index of zero specifies the character's original (base) class, while indexes 1-3 specifies the character's sub-classes respectively.
  8624.      * @param classIndex
  8625.      * @return true if successful.
  8626.      */
  8627.     public boolean setActiveClass(int classIndex)
  8628.     {
  8629.         if (!_subclassLock.tryLock())
  8630.             return false;
  8631.        
  8632.         try
  8633.         {
  8634.             // Remove active item skills before saving char to database because next time when choosing this class, worn items can be different
  8635.             for (L2ItemInstance item : getInventory().getAugmentedItems())
  8636.             {
  8637.                 if (item != null && item.isEquipped())
  8638.                     item.getAugmentation().removeBonus(this);
  8639.             }
  8640.            
  8641.             // abort any kind of cast.
  8642.             abortCast();
  8643.            
  8644.             // Stop casting for any player that may be casting a force buff on this l2pcinstance.
  8645.             for (L2Character character : getKnownList().getKnownType(L2Character.class))
  8646.                 if (character.getFusionSkill() != null && character.getFusionSkill().getTarget() == this)
  8647.                     character.abortCast();
  8648.            
  8649.             /*
  8650.              * 1. Call store() before modifying _classIndex to avoid skill effects rollover. 2. Register the correct _classId against applied 'classIndex'.
  8651.              */
  8652.             store();
  8653.             _reuseTimeStamps.clear();
  8654.            
  8655.             // clear charges
  8656.             _charges.set(0);
  8657.             stopChargeTask();
  8658.            
  8659.             if (classIndex == 0)
  8660.                 setClassTemplate(getBaseClass());
  8661.             else
  8662.             {
  8663.                 try
  8664.                 {
  8665.                     setClassTemplate(getSubClasses().get(classIndex).getClassId());
  8666.                 }
  8667.                 catch (Exception e)
  8668.                 {
  8669.                     _log.info("Could not switch " + getName() + "'s sub class to class index " + classIndex + ": " + e);
  8670.                     return false;
  8671.                 }
  8672.             }
  8673.             _classIndex = classIndex;
  8674.            
  8675.             if (isInParty())
  8676.                 getParty().recalculatePartyLevel();
  8677.            
  8678.             /*
  8679.              * Update the character's change in class status. 1. Remove any active cubics from the player. 2. Renovate the characters table in the database with the new class info, storing also buff/effect data. 3. Remove all existing skills. 4. Restore all the learned skills for the current class
  8680.              * from the database. 5. Restore effect/buff data for the new class. 6. Restore henna data for the class, applying the new stat modifiers while removing existing ones. 7. Reset HP/MP/CP stats and send Server->Client character status packet to reflect changes. 8. Restore shortcut data
  8681.              * related to this class. 9. Resend a class change animation effect to broadcast to all nearby players. 10.Unsummon any active servitor from the player.
  8682.              */
  8683.            
  8684.             if (getPet() instanceof L2SummonInstance)
  8685.                 getPet().unSummon(this);
  8686.            
  8687.             for (L2Skill oldSkill : getAllSkills())
  8688.                 super.removeSkill(oldSkill);
  8689.            
  8690.             stopAllEffectsExceptThoseThatLastThroughDeath();
  8691.             stopCubics();
  8692.            
  8693.             if (isSubClassActive())
  8694.             {
  8695.                 _dwarvenRecipeBook.clear();
  8696.                 _commonRecipeBook.clear();
  8697.             }
  8698.             else
  8699.             {
  8700.                 restoreRecipeBook();
  8701.             }
  8702.            
  8703.             // Restore any Death Penalty Buff
  8704.             restoreDeathPenaltyBuffLevel();
  8705.            
  8706.             restoreSkills();
  8707.             rewardSkills();
  8708.             regiveTemporarySkills();
  8709.            
  8710.             // Prevents some issues when changing between subclases that shares skills
  8711.             if (_disabledSkills != null && !_disabledSkills.isEmpty())
  8712.                 _disabledSkills.clear();
  8713.            
  8714.             restoreEffects();
  8715.             updateEffectIcons();
  8716.             sendPacket(new EtcStatusUpdate(this));
  8717.            
  8718.             // If player has quest "Repent Your Sins", remove it
  8719.             QuestState st = getQuestState("Q422_RepentYourSins");
  8720.             if (st != null)
  8721.                 st.exitQuest(true);
  8722.            
  8723.             for (int i = 0; i < 3; i++)
  8724.                 _henna[i] = null;
  8725.            
  8726.             restoreHenna();
  8727.             sendPacket(new HennaInfo(this));
  8728.            
  8729.             if (getCurrentHp() > getMaxHp())
  8730.                 setCurrentHp(getMaxHp());
  8731.             if (getCurrentMp() > getMaxMp())
  8732.                 setCurrentMp(getMaxMp());
  8733.             if (getCurrentCp() > getMaxCp())
  8734.                 setCurrentCp(getMaxCp());
  8735.            
  8736.             refreshOverloaded();
  8737.             refreshExpertisePenalty();
  8738.             broadcastUserInfo();
  8739.            
  8740.             // Clear resurrect xp calculation
  8741.             setExpBeforeDeath(0);
  8742.            
  8743.             _shortCuts.restore();
  8744.             sendPacket(new ShortCutInit(this));
  8745.            
  8746.             broadcastPacket(new SocialAction(this, 15));
  8747.             sendPacket(new SkillCoolTime(this));
  8748.            
  8749.             if(isVoteBuff())
  8750.             {
  8751.                 final L2Skill skill = SkillTable.getInstance().getInfo(7083, 1);
  8752.                 if(skill != null)
  8753.                 {
  8754.                   addSkill(skill,false);
  8755.                   sendSkillList();
  8756.                 }
  8757.             }
  8758.             else
  8759.             {
  8760.                 removeSkill(SkillTable.getInstance().getInfo(7083, 1),true);
  8761.             }
  8762.            
  8763.             return true;
  8764.         }
  8765.         finally
  8766.         {
  8767.             _subclassLock.unlock();
  8768.         }
  8769.     }
  8770.    
  8771.     public boolean isLocked()
  8772.     {
  8773.         return _subclassLock.isLocked();
  8774.     }
  8775.    
  8776.     public boolean isVoteBuff()
  8777.     {
  8778.         return _isVoteBuff;
  8779.     }
  8780.    
  8781.     public void setVoteBuff(boolean val)
  8782.     {
  8783.         _isVoteBuff = val;
  8784.     }
  8785.     public long getVoteBuffEndTime()
  8786.     {
  8787.         return _votebuff_endTime;
  8788.     }
  8789.    
  8790.     public long getvotetime()
  8791.     {
  8792.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  8793.         {
  8794.             PreparedStatement statement = con.prepareStatement("SELECT vote_end_buff FROM characters WHERE obj_Id=?");
  8795.             statement.setInt(1, getObjectId());
  8796.             ResultSet rset = statement.executeQuery();
  8797.             while(rset.next())
  8798.             {
  8799.                 _votebuff_endTime = rset.getLong("vote_end_buff");
  8800.             }
  8801.             rset.close();
  8802.             statement.close();
  8803.         }
  8804.         catch (Exception e)
  8805.         {
  8806.             _log.log(Level.WARNING, "Error found in " + getName() + "'s Vote Buff: " + e.getMessage(), e);
  8807.         }
  8808.        
  8809.         return _votebuff_endTime - System.currentTimeMillis();
  8810.     }
  8811.    
  8812.     public void setVoteBuffEndTime(long val)
  8813.     {
  8814.         _votebuff_endTime = val;
  8815.     }
  8816.    
  8817.     private boolean _isVoting = false;
  8818.    
  8819.     public final boolean isVoting()
  8820.     {
  8821.         return _isVoting;
  8822.     }
  8823.    
  8824.     public final void setIsVoting(boolean value)
  8825.     {
  8826.         _isVoting = value;
  8827.     }  
  8828.    
  8829.     public void setEndVoteBuff(int val)
  8830.     {
  8831.          Calendar calendar = Calendar.getInstance();
  8832.           calendar.add(Calendar.HOUR, val);
  8833.          long end_hours = calendar.getTimeInMillis();    
  8834.          _votebuff_endTime = end_hours;
  8835.    }
  8836.    
  8837.     public void stopWaterTask()
  8838.     {
  8839.         if (_isInWater)
  8840.         {
  8841.             _isInWater = false;
  8842.             sendPacket(new SetupGauge(2, 0));
  8843.             WaterTaskManager.getInstance().removeWaterTask(this);
  8844.         }
  8845.     }
  8846.    
  8847.     public void startWaterTask()
  8848.     {
  8849.         if (!isDead() && !_isInWater)
  8850.         {
  8851.             _isInWater = true;
  8852.             int time = (int) calcStat(Stats.BREATH, 60000, this, null);
  8853.            
  8854.             sendPacket(new SetupGauge(2, time));
  8855.             WaterTaskManager.getInstance().addWaterTask(this, System.currentTimeMillis() + time);
  8856.         }
  8857.     }
  8858.    
  8859.     public void checkWaterState()
  8860.     {
  8861.         if (isInsideZone(ZoneId.WATER))
  8862.             startWaterTask();
  8863.         else
  8864.             stopWaterTask();
  8865.     }
  8866.    
  8867.     public void onPlayerEnter()
  8868.     {
  8869.         if (isCursedWeaponEquipped())
  8870.             CursedWeaponsManager.getInstance().getCursedWeapon(getCursedWeaponEquippedId()).cursedOnLogin();
  8871.        
  8872.         // Add a task for the "Take Break" message.
  8873.         TakeBreakTaskManager.getInstance().addTakeBreakTask(this);
  8874.        
  8875.         // Teleport player if the Seven Signs period isn't the good one, or if the player isn't in a cabal.
  8876.         if (isIn7sDungeon() && !isGM())
  8877.         {
  8878.             if (SevenSigns.getInstance().isSealValidationPeriod() || SevenSigns.getInstance().isCompResultsPeriod())
  8879.             {
  8880.                 if (SevenSigns.getInstance().getPlayerCabal(getObjectId()) != SevenSigns.getInstance().getCabalHighestScore())
  8881.                 {
  8882.                     teleToLocation(MapRegionTable.TeleportWhereType.Town);
  8883.                     setIsIn7sDungeon(false);
  8884.                 }
  8885.             }
  8886.             else if (SevenSigns.getInstance().getPlayerCabal(getObjectId()) == SevenSigns.CABAL_NULL)
  8887.             {
  8888.                 teleToLocation(MapRegionTable.TeleportWhereType.Town);
  8889.                 setIsIn7sDungeon(false);
  8890.             }
  8891.         }
  8892.        
  8893.         // Jail task
  8894.         updatePunishState();
  8895.        
  8896.         if (isGM())
  8897.         {
  8898.             if (isInvul())
  8899.                 sendMessage("Entering world in Invulnerable mode.");
  8900.             if (getAppearance().getInvisible())
  8901.                 sendMessage("Entering world in Invisible mode.");
  8902.             if (isInRefusalMode())
  8903.                 sendMessage("Entering world in Message Refusal mode.");
  8904.         }
  8905.        
  8906.         revalidateZone(true);
  8907.         notifyFriends(true);
  8908.     }
  8909.    
  8910.     public long getLastAccess()
  8911.     {
  8912.         return _lastAccess;
  8913.     }
  8914.    
  8915.     private void checkRecom(int recsHave, int recsLeft)
  8916.     {
  8917.         Calendar check = Calendar.getInstance();
  8918.         check.setTimeInMillis(_lastRecomUpdate);
  8919.         check.add(Calendar.DAY_OF_MONTH, 1);
  8920.        
  8921.         Calendar min = Calendar.getInstance();
  8922.        
  8923.         _recomHave = recsHave;
  8924.         _recomLeft = recsLeft;
  8925.        
  8926.         if (getStat().getLevel() < 10 || check.after(min))
  8927.             return;
  8928.        
  8929.         restartRecom();
  8930.     }
  8931.    
  8932.     public void restartRecom()
  8933.     {
  8934.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  8935.         {
  8936.             PreparedStatement statement = con.prepareStatement(DELETE_CHAR_RECOMS);
  8937.             statement.setInt(1, getObjectId());
  8938.             statement.execute();
  8939.             statement.close();
  8940.            
  8941.             _recomChars.clear();
  8942.         }
  8943.         catch (Exception e)
  8944.         {
  8945.             _log.warning("could not clear char recommendations: " + e);
  8946.         }
  8947.        
  8948.         if (getStat().getLevel() < 20)
  8949.         {
  8950.             _recomLeft = 3;
  8951.             _recomHave--;
  8952.         }
  8953.         else if (getStat().getLevel() < 40)
  8954.         {
  8955.             _recomLeft = 6;
  8956.             _recomHave -= 2;
  8957.         }
  8958.         else
  8959.         {
  8960.             _recomLeft = 9;
  8961.             _recomHave -= 3;
  8962.         }
  8963.        
  8964.         if (_recomHave < 0)
  8965.             _recomHave = 0;
  8966.        
  8967.         // If we have to update last update time, but it's now before 13, we should set it to yesterday
  8968.         Calendar update = Calendar.getInstance();
  8969.         if (update.get(Calendar.HOUR_OF_DAY) < 13)
  8970.             update.add(Calendar.DAY_OF_MONTH, -1);
  8971.        
  8972.         update.set(Calendar.HOUR_OF_DAY, 13);
  8973.         _lastRecomUpdate = update.getTimeInMillis();
  8974.     }
  8975.    
  8976.     @Override
  8977.     public void doRevive()
  8978.     {
  8979.         super.doRevive();
  8980.         stopEffects(L2EffectType.CHARMOFCOURAGE);
  8981.         sendPacket(new EtcStatusUpdate(this));
  8982.         _reviveRequested = 0;
  8983.         _revivePower = 0;
  8984.        
  8985.         if (isMounted())
  8986.             startFeed(_mountNpcId);
  8987.        
  8988.         if (isInParty() && getParty().isInDimensionalRift())
  8989.         {
  8990.             if (!DimensionalRiftManager.getInstance().checkIfInPeaceZone(getX(), getY(), getZ()))
  8991.                 getParty().getDimensionalRift().memberRessurected(this);
  8992.         }
  8993.     }
  8994.    
  8995.     @Override
  8996.     public void doRevive(double revivePower)
  8997.     {
  8998.         // Restore the player's lost experience,
  8999.         // depending on the % return of the skill used (based on its power).
  9000.         restoreExp(revivePower);
  9001.         doRevive();
  9002.     }
  9003.    
  9004.     public void reviveRequest(L2PcInstance Reviver, L2Skill skill, boolean Pet)
  9005.     {
  9006.         if (_reviveRequested == 1)
  9007.         {
  9008.             // Resurrection has already been proposed.
  9009.             if (_revivePet == Pet)
  9010.                 Reviver.sendPacket(SystemMessageId.RES_HAS_ALREADY_BEEN_PROPOSED);
  9011.             else
  9012.             {
  9013.                 if (Pet)
  9014.                     // A pet cannot be resurrected while it's owner is in the process of resurrecting.
  9015.                     Reviver.sendPacket(SystemMessageId.CANNOT_RES_PET2);
  9016.                 else
  9017.                     // While a pet is attempting to resurrect, it cannot help in resurrecting its master.
  9018.                     Reviver.sendPacket(SystemMessageId.MASTER_CANNOT_RES);
  9019.             }
  9020.             return;
  9021.         }
  9022.        
  9023.         if ((Pet && getPet() != null && getPet().isDead()) || (!Pet && isDead()))
  9024.         {
  9025.             _reviveRequested = 1;
  9026.            
  9027.             if (isPhoenixBlessed())
  9028.                 _revivePower = 100;
  9029.             else if (isAffected(L2EffectFlag.CHARM_OF_COURAGE))
  9030.                 _revivePower = 0;
  9031.             else
  9032.                 _revivePower = Formulas.calculateSkillResurrectRestorePercent(skill.getPower(), Reviver);
  9033.            
  9034.             _revivePet = Pet;
  9035.            
  9036.             if (isAffected(L2EffectFlag.CHARM_OF_COURAGE))
  9037.             {
  9038.                 sendPacket(new ConfirmDlg(SystemMessageId.DO_YOU_WANT_TO_BE_RESTORED).addTime(60000));
  9039.                 return;
  9040.             }
  9041.            
  9042.             sendPacket(new ConfirmDlg(SystemMessageId.RESSURECTION_REQUEST_BY_S1).addPcName(Reviver));
  9043.         }
  9044.     }
  9045.    
  9046.     public void reviveAnswer(int answer)
  9047.     {
  9048.         if (_reviveRequested != 1 || (!isDead() && !_revivePet) || (_revivePet && getPet() != null && !getPet().isDead()))
  9049.             return;
  9050.        
  9051.         if (answer == 0 && isPhoenixBlessed())
  9052.             stopPhoenixBlessing(null);
  9053.         else if (answer == 1)
  9054.         {
  9055.             if (!_revivePet)
  9056.             {
  9057.                 if (_revivePower != 0)
  9058.                     doRevive(_revivePower);
  9059.                 else
  9060.                     doRevive();
  9061.             }
  9062.             else if (getPet() != null)
  9063.             {
  9064.                 if (_revivePower != 0)
  9065.                     getPet().doRevive(_revivePower);
  9066.                 else
  9067.                     getPet().doRevive();
  9068.             }
  9069.         }
  9070.         _reviveRequested = 0;
  9071.         _revivePower = 0;
  9072.     }
  9073.    
  9074.     public boolean isReviveRequested()
  9075.     {
  9076.         return (_reviveRequested == 1);
  9077.     }
  9078.    
  9079.     public boolean isRevivingPet()
  9080.     {
  9081.         return _revivePet;
  9082.     }
  9083.    
  9084.     public void removeReviving()
  9085.     {
  9086.         _reviveRequested = 0;
  9087.         _revivePower = 0;
  9088.     }
  9089.    
  9090.     public void onActionRequest()
  9091.     {
  9092.         setProtection(false);
  9093.     }
  9094.    
  9095.     /**
  9096.      * @param expertiseIndex The expertiseIndex to set.
  9097.      */
  9098.     public void setExpertiseIndex(int expertiseIndex)
  9099.     {
  9100.         _expertiseIndex = expertiseIndex;
  9101.     }
  9102.    
  9103.     /**
  9104.      * @return Returns the expertiseIndex.
  9105.      */
  9106.     public int getExpertiseIndex()
  9107.     {
  9108.         return _expertiseIndex;
  9109.     }
  9110.    
  9111.     @Override
  9112.     public final void onTeleported()
  9113.     {
  9114.         super.onTeleported();
  9115.        
  9116.         // Force a revalidation
  9117.         revalidateZone(true);
  9118.        
  9119.         if (Config.PLAYER_SPAWN_PROTECTION > 0)
  9120.             setProtection(true);
  9121.        
  9122.         // Stop toggles upon teleport.
  9123.         if (!isGM())
  9124.             stopAllToggles();
  9125.        
  9126.         // Modify the position of the tamed beast if necessary
  9127.         if (getTrainedBeast() != null)
  9128.         {
  9129.             getTrainedBeast().getAI().stopFollow();
  9130.             getTrainedBeast().teleToLocation(getPosition().getX(), getPosition().getY(), getPosition().getZ(), 0);
  9131.             getTrainedBeast().getAI().startFollow(this);
  9132.         }
  9133.        
  9134.         // Modify the position of the pet if necessary
  9135.         L2Summon pet = getPet();
  9136.         if (pet != null)
  9137.         {
  9138.             pet.setFollowStatus(false);
  9139.             pet.teleToLocation(getPosition().getX(), getPosition().getY(), getPosition().getZ(), 0);
  9140.             ((L2SummonAI) pet.getAI()).setStartFollowController(true);
  9141.             pet.setFollowStatus(true);
  9142.         }
  9143.     }
  9144.    
  9145.     public void setLastServerPosition(int x, int y, int z)
  9146.     {
  9147.         _lastServerPosition.setXYZ(x, y, z);
  9148.     }
  9149.    
  9150.     public boolean checkLastServerPosition(int x, int y, int z)
  9151.     {
  9152.         return _lastServerPosition.equals(x, y, z);
  9153.     }
  9154.    
  9155.     public int getLastServerDistance(int x, int y, int z)
  9156.     {
  9157.         double dx = (x - _lastServerPosition.getX());
  9158.         double dy = (y - _lastServerPosition.getY());
  9159.         double dz = (z - _lastServerPosition.getZ());
  9160.        
  9161.         return (int) Math.sqrt(dx * dx + dy * dy + dz * dz);
  9162.     }
  9163.    
  9164.     @Override
  9165.     public void addExpAndSp(long addToExp, int addToSp)
  9166.     {
  9167.         getStat().addExpAndSp(addToExp, addToSp);
  9168.     }
  9169.    
  9170.     public void removeExpAndSp(long removeExp, int removeSp)
  9171.     {
  9172.         getStat().removeExpAndSp(removeExp, removeSp);
  9173.     }
  9174.    
  9175.     @Override
  9176.     public void reduceCurrentHp(double value, L2Character attacker, boolean awake, boolean isDOT, L2Skill skill)
  9177.     {
  9178.         if (skill != null)
  9179.             getStatus().reduceHp(value, attacker, awake, isDOT, skill.isToggle(), skill.getDmgDirectlyToHP());
  9180.         else
  9181.             getStatus().reduceHp(value, attacker, awake, isDOT, false, false);
  9182.        
  9183.         // notify the tamed beast of attacks
  9184.         if (getTrainedBeast() != null)
  9185.             getTrainedBeast().onOwnerGotAttacked(attacker);
  9186.     }
  9187.    
  9188.     public void broadcastSnoop(int type, String name, String _text)
  9189.     {
  9190.         if (_snoopListener.size() > 0)
  9191.         {
  9192.             Snoop sn = new Snoop(getObjectId(), getName(), type, name, _text);
  9193.            
  9194.             for (L2PcInstance pci : _snoopListener)
  9195.                 if (pci != null)
  9196.                     pci.sendPacket(sn);
  9197.         }
  9198.     }
  9199.    
  9200.     public void addSnooper(L2PcInstance pci)
  9201.     {
  9202.         if (!_snoopListener.contains(pci))
  9203.             _snoopListener.add(pci);
  9204.     }
  9205.    
  9206.     public void removeSnooper(L2PcInstance pci)
  9207.     {
  9208.         _snoopListener.remove(pci);
  9209.     }
  9210.    
  9211.     public void addSnooped(L2PcInstance pci)
  9212.     {
  9213.         if (!_snoopedPlayer.contains(pci))
  9214.             _snoopedPlayer.add(pci);
  9215.     }
  9216.    
  9217.     public void removeSnooped(L2PcInstance pci)
  9218.     {
  9219.         _snoopedPlayer.remove(pci);
  9220.     }
  9221.    
  9222.     public synchronized void addBypass(String bypass)
  9223.     {
  9224.         if (bypass == null)
  9225.             return;
  9226.        
  9227.         _validBypass.add(bypass);
  9228.     }
  9229.    
  9230.     public synchronized void addBypass2(String bypass)
  9231.     {
  9232.         if (bypass == null)
  9233.             return;
  9234.        
  9235.         _validBypass2.add(bypass);
  9236.     }
  9237.    
  9238.     public synchronized boolean validateBypass(String cmd)
  9239.     {
  9240.         for (String bp : _validBypass)
  9241.         {
  9242.             if (bp == null)
  9243.                 continue;
  9244.            
  9245.             if (bp.equals(cmd))
  9246.                 return true;
  9247.         }
  9248.        
  9249.         for (String bp : _validBypass2)
  9250.         {
  9251.             if (bp == null)
  9252.                 continue;
  9253.            
  9254.             if (cmd.startsWith(bp))
  9255.                 return true;
  9256.         }
  9257.        
  9258.         if (Config.DEBUG)
  9259.             _log.warning(getName() + " sent an invalid bypass: '" + cmd + "'.");
  9260.        
  9261.         return false;
  9262.     }
  9263.    
  9264.     public boolean validateItemManipulation(int objectId, String action)
  9265.     {
  9266.         L2ItemInstance item = getInventory().getItemByObjectId(objectId);
  9267.        
  9268.         if (item == null || item.getOwnerId() != getObjectId())
  9269.         {
  9270.             _log.finest(getObjectId() + ": player tried to " + action + " item he is not owner of");
  9271.             return false;
  9272.         }
  9273.        
  9274.         // Pet is summoned and not the item that summoned the pet AND not the buggle from strider you're mounting
  9275.         if (getPet() != null && getPet().getControlItemId() == objectId || getMountObjectID() == objectId)
  9276.         {
  9277.             if (Config.DEBUG)
  9278.                 _log.finest(getObjectId() + ": player tried to " + action + " item controling pet");
  9279.            
  9280.             return false;
  9281.         }
  9282.        
  9283.         if (getActiveEnchantItem() != null && getActiveEnchantItem().getObjectId() == objectId)
  9284.         {
  9285.             if (Config.DEBUG)
  9286.                 _log.finest(getObjectId() + ":player tried to " + action + " an enchant scroll he was using");
  9287.            
  9288.             return false;
  9289.         }
  9290.        
  9291.         if (CursedWeaponsManager.getInstance().isCursed(item.getItemId()))
  9292.         {
  9293.             // can not trade a cursed weapon
  9294.             return false;
  9295.         }
  9296.        
  9297.         return true;
  9298.     }
  9299.    
  9300.     public synchronized void clearBypass()
  9301.     {
  9302.         _validBypass.clear();
  9303.         _validBypass2.clear();
  9304.     }
  9305.    
  9306.     /**
  9307.      * @return Returns the inBoat.
  9308.      */
  9309.     public boolean isInBoat()
  9310.     {
  9311.         return _vehicle != null && _vehicle.isBoat();
  9312.     }
  9313.    
  9314.     /**
  9315.      * @return
  9316.      */
  9317.     public L2BoatInstance getBoat()
  9318.     {
  9319.         return (L2BoatInstance) _vehicle;
  9320.     }
  9321.    
  9322.     public L2Vehicle getVehicle()
  9323.     {
  9324.         return _vehicle;
  9325.     }
  9326.    
  9327.     public void setVehicle(L2Vehicle v)
  9328.     {
  9329.         if (v == null && _vehicle != null)
  9330.             _vehicle.removePassenger(this);
  9331.        
  9332.         _vehicle = v;
  9333.     }
  9334.    
  9335.     public void setInCrystallize(boolean inCrystallize)
  9336.     {
  9337.         _inCrystallize = inCrystallize;
  9338.     }
  9339.    
  9340.     public boolean isInCrystallize()
  9341.     {
  9342.         return _inCrystallize;
  9343.     }
  9344.    
  9345.     /**
  9346.      * @return
  9347.      */
  9348.     public Point3D getInVehiclePosition()
  9349.     {
  9350.         return _inVehiclePosition;
  9351.     }
  9352.    
  9353.     public void setInVehiclePosition(Point3D pt)
  9354.     {
  9355.         _inVehiclePosition = pt;
  9356.     }
  9357.    
  9358.     /**
  9359.      * Manage the delete task of a L2PcInstance (Leave Party, Unsummon pet, Save its inventory in the database, Remove it from the world...).<BR>
  9360.      * <BR>
  9361.      * <B><U> Actions</U> :</B><BR>
  9362.      * <BR>
  9363.      * <li>If the L2PcInstance is in observer mode, set its position to its position before entering in observer mode</li> <li>Set the online Flag to True or False and update the characters table of the database with online status and lastAccess</li> <li>Stop the HP/MP/CP Regeneration task</li> <li>
  9364.      * Cancel Crafting, Attak or Cast</li> <li>Remove the L2PcInstance from the world</li> <li>Stop Party and Unsummon Pet</li> <li>Update database with items in its inventory and remove them from the world</li> <li>Remove all L2Object from _knownObjects and _knownPlayer of the L2Character then
  9365.      * cancel Attak or Cast and notify AI</li> <li>Close the connection with the client</li><BR>
  9366.      * <BR>
  9367.      */
  9368.     @Override
  9369.     public void deleteMe()
  9370.     {
  9371.         cleanup();
  9372.         store();
  9373.         super.deleteMe();
  9374.     }
  9375.    
  9376.     private synchronized void cleanup()
  9377.     {
  9378.         try
  9379.         {
  9380.             if (!isOnline())
  9381.                 _log.log(Level.SEVERE, "deleteMe() called on offline character " + this, new RuntimeException());
  9382.            
  9383.             // Put the online status to false
  9384.             setOnlineStatus(false, true);
  9385.            
  9386.             // abort cast & attack and remove the target. Cancels movement aswell.
  9387.             abortAttack();
  9388.             abortCast();
  9389.             stopMove(null);
  9390.             setTarget(null);
  9391.            
  9392.             PartyMatchWaitingList.getInstance().removePlayer(this);
  9393.             if (_partyroom != 0)
  9394.             {
  9395.                 PartyMatchRoom room = PartyMatchRoomList.getInstance().getRoom(_partyroom);
  9396.                 if (room != null)
  9397.                     room.deleteMember(this);
  9398.             }
  9399.            
  9400.             if (isFlying())
  9401.                 removeSkill(SkillTable.getInstance().getInfo(4289, 1));
  9402.            
  9403.             // Stop all scheduled tasks
  9404.             stopAllTimers();
  9405.            
  9406.             // Cancel the cast of eventual fusion skill users on this target.
  9407.             for (L2Character character : getKnownList().getKnownType(L2Character.class))
  9408.                 if (character.getFusionSkill() != null && character.getFusionSkill().getTarget() == this)
  9409.                     character.abortCast();
  9410.            
  9411.             // Stop signets & toggles effects.
  9412.             for (L2Effect effect : getAllEffects())
  9413.             {
  9414.                 if (effect.getSkill().isToggle())
  9415.                 {
  9416.                     effect.exit();
  9417.                     continue;
  9418.                 }
  9419.                
  9420.                 switch (effect.getEffectType())
  9421.                 {
  9422.                     case SIGNET_GROUND:
  9423.                     case SIGNET_EFFECT:
  9424.                         effect.exit();
  9425.                         break;
  9426.                 }
  9427.             }
  9428.            
  9429.             // Remove the L2PcInstance from the world
  9430.             decayMe();
  9431.            
  9432.             // Remove from world regions zones
  9433.             L2WorldRegion oldRegion = getWorldRegion();
  9434.             if (oldRegion != null)
  9435.                 oldRegion.removeFromZones(this);
  9436.            
  9437.             // If a party is in progress, leave it
  9438.             if (isInParty())
  9439.                 leaveParty();
  9440.            
  9441.             // If the L2PcInstance has Pet, unsummon it
  9442.             if (getPet() != null)
  9443.                 getPet().unSummon(this);
  9444.            
  9445.             // Handle removal from olympiad game
  9446.             if (OlympiadManager.getInstance().isRegistered(this) || getOlympiadGameId() != -1)
  9447.                 OlympiadManager.getInstance().removeDisconnectedCompetitor(this);
  9448.            
  9449.             // set the status for pledge member list to OFFLINE
  9450.             if (getClan() != null)
  9451.             {
  9452.                 L2ClanMember clanMember = getClan().getClanMember(getObjectId());
  9453.                 if (clanMember != null)
  9454.                     clanMember.setPlayerInstance(null);
  9455.             }
  9456.            
  9457.             // deals with sudden exit in the middle of transaction
  9458.             if (getActiveRequester() != null)
  9459.             {
  9460.                 setActiveRequester(null);
  9461.                 cancelActiveTrade();
  9462.             }
  9463.            
  9464.             // If the L2PcInstance is a GM, remove it from the GM List
  9465.             if (isGM())
  9466.                 GmListTable.getInstance().deleteGm(this);
  9467.            
  9468.             // Check if the L2PcInstance is in observer mode to set its position to its position
  9469.             // before entering in observer mode
  9470.             if (inObserverMode())
  9471.                 setXYZInvisible(_lastX, _lastY, _lastZ);
  9472.            
  9473.             // Oust player from boat
  9474.             if (getVehicle() != null)
  9475.                 getVehicle().oustPlayer(this);
  9476.            
  9477.             // Update inventory and remove them from the world
  9478.             getInventory().deleteMe();
  9479.            
  9480.             // Update warehouse and remove them from the world
  9481.             clearWarehouse();
  9482.            
  9483.             // Update freight and remove them from the world
  9484.             clearFreight();
  9485.             clearDepositedFreight();
  9486.            
  9487.             if (isCursedWeaponEquipped())
  9488.                 CursedWeaponsManager.getInstance().getCursedWeapon(_cursedWeaponEquippedId).setPlayer(null);
  9489.            
  9490.             // Remove all L2Object from _knownObjects and _knownPlayer of the L2Character then cancel Attak or Cast and notify AI
  9491.             getKnownList().removeAllKnownObjects();
  9492.            
  9493.             if (getClanId() > 0)
  9494.                 getClan().broadcastToOtherOnlineMembers(new PledgeShowMemberListUpdate(this), this);
  9495.            
  9496.             for (L2PcInstance player : _snoopedPlayer)
  9497.                 player.removeSnooper(this);
  9498.            
  9499.             for (L2PcInstance player : _snoopListener)
  9500.                 player.removeSnooped(this);
  9501.            
  9502.             // Remove L2Object object from _allObjects of L2World
  9503.             L2World.getInstance().removeObject(this);
  9504.             L2World.getInstance().removeFromAllPlayers(this); // force remove in case of crash during teleport
  9505.            
  9506.             // friends & blocklist update
  9507.             notifyFriends(false);
  9508.             getBlockList().playerLogout();
  9509.         }
  9510.         catch (Exception e)
  9511.         {
  9512.             _log.log(Level.WARNING, "Exception on deleteMe()" + e.getMessage(), e);
  9513.         }
  9514.     }
  9515.    
  9516.     public void startFishing(Location loc)
  9517.     {
  9518.         stopMove(null);
  9519.         setIsImmobilized(true);
  9520.        
  9521.         _fishingLoc = loc;
  9522.        
  9523.         // Starts fishing
  9524.         int group = getRandomGroup();
  9525.        
  9526.         _fish = FishTable.getFish(getRandomFishLvl(), getRandomFishType(group), group);
  9527.         if (_fish == null)
  9528.         {
  9529.             endFishing(false);
  9530.             return;
  9531.         }
  9532.        
  9533.         sendPacket(SystemMessageId.CAST_LINE_AND_START_FISHING);
  9534.        
  9535.         broadcastPacket(new ExFishingStart(this, _fish.getType(_lure.isNightLure()), loc, _lure.isNightLure()));
  9536.         sendPacket(new PlaySound(1, "SF_P_01", 0, 0, 0, 0, 0));
  9537.         startLookingForFishTask();
  9538.     }
  9539.    
  9540.     public void stopLookingForFishTask()
  9541.     {
  9542.         if (_taskforfish != null)
  9543.         {
  9544.             _taskforfish.cancel(false);
  9545.             _taskforfish = null;
  9546.         }
  9547.     }
  9548.    
  9549.     public void startLookingForFishTask()
  9550.     {
  9551.         if (!isDead() && _taskforfish == null)
  9552.         {
  9553.             int checkDelay = 0;
  9554.             boolean isNoob = false;
  9555.             boolean isUpperGrade = false;
  9556.            
  9557.             if (_lure != null)
  9558.             {
  9559.                 int lureid = _lure.getItemId();
  9560.                 isNoob = _fish.getGroup() == 0;
  9561.                 isUpperGrade = _fish.getGroup() == 2;
  9562.                 if (lureid == 6519 || lureid == 6522 || lureid == 6525 || lureid == 8505 || lureid == 8508 || lureid == 8511) // low grade
  9563.                     checkDelay = Math.round((float) (_fish.getGutsCheckTime() * (1.33)));
  9564.                 else if (lureid == 6520 || lureid == 6523 || lureid == 6526 || (lureid >= 8505 && lureid <= 8513) || (lureid >= 7610 && lureid <= 7613) || (lureid >= 7807 && lureid <= 7809) || (lureid >= 8484 && lureid <= 8486)) // medium grade, beginner, prize-winning & quest special bait
  9565.                     checkDelay = Math.round((float) (_fish.getGutsCheckTime() * (1.00)));
  9566.                 else if (lureid == 6521 || lureid == 6524 || lureid == 6527 || lureid == 8507 || lureid == 8510 || lureid == 8513) // high grade
  9567.                     checkDelay = Math.round((float) (_fish.getGutsCheckTime() * (0.66)));
  9568.             }
  9569.             _taskforfish = ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(new LookingForFishTask(_fish.getWaitTime(), _fish.getFishGuts(), _fish.getType(_lure.isNightLure()), isNoob, isUpperGrade), 10000, checkDelay);
  9570.         }
  9571.     }
  9572.    
  9573.     private int getRandomGroup()
  9574.     {
  9575.         switch (_lure.getItemId())
  9576.         {
  9577.             case 7807: // green for beginners
  9578.             case 7808: // purple for beginners
  9579.             case 7809: // yellow for beginners
  9580.             case 8486: // prize-winning for beginners
  9581.                 return 0;
  9582.                
  9583.             case 8485: // prize-winning luminous
  9584.             case 8506: // green luminous
  9585.             case 8509: // purple luminous
  9586.             case 8512: // yellow luminous
  9587.                 return 2;
  9588.                
  9589.             default:
  9590.                 return 1;
  9591.         }
  9592.     }
  9593.    
  9594.     private int getRandomFishType(int group)
  9595.     {
  9596.         int check = Rnd.get(100);
  9597.         int type = 1;
  9598.         switch (group)
  9599.         {
  9600.             case 0: // fish for novices
  9601.                 switch (_lure.getItemId())
  9602.                 {
  9603.                     case 7807: // green lure, preferred by fast-moving (nimble) fish (type 5)
  9604.                         if (check <= 54)
  9605.                             type = 5;
  9606.                         else if (check <= 77)
  9607.                             type = 4;
  9608.                         else
  9609.                             type = 6;
  9610.                         break;
  9611.                    
  9612.                     case 7808: // purple lure, preferred by fat fish (type 4)
  9613.                         if (check <= 54)
  9614.                             type = 4;
  9615.                         else if (check <= 77)
  9616.                             type = 6;
  9617.                         else
  9618.                             type = 5;
  9619.                         break;
  9620.                    
  9621.                     case 7809: // yellow lure, preferred by ugly fish (type 6)
  9622.                         if (check <= 54)
  9623.                             type = 6;
  9624.                         else if (check <= 77)
  9625.                             type = 5;
  9626.                         else
  9627.                             type = 4;
  9628.                         break;
  9629.                    
  9630.                     case 8486: // prize-winning fishing lure for beginners
  9631.                         if (check <= 33)
  9632.                             type = 4;
  9633.                         else if (check <= 66)
  9634.                             type = 5;
  9635.                         else
  9636.                             type = 6;
  9637.                         break;
  9638.                 }
  9639.                 break;
  9640.            
  9641.             case 1: // normal fish
  9642.                 switch (_lure.getItemId())
  9643.                 {
  9644.                     case 7610:
  9645.                     case 7611:
  9646.                     case 7612:
  9647.                     case 7613:
  9648.                         type = 3;
  9649.                         break;
  9650.                    
  9651.                     case 6519: // all theese lures (green) are prefered by fast-moving (nimble) fish (type 1)
  9652.                     case 8505:
  9653.                     case 6520:
  9654.                     case 6521:
  9655.                     case 8507:
  9656.                         if (check <= 54)
  9657.                             type = 1;
  9658.                         else if (check <= 74)
  9659.                             type = 0;
  9660.                         else if (check <= 94)
  9661.                             type = 2;
  9662.                         else
  9663.                             type = 3;
  9664.                         break;
  9665.                    
  9666.                     case 6522: // all theese lures (purple) are prefered by fat fish (type 0)
  9667.                     case 8508:
  9668.                     case 6523:
  9669.                     case 6524:
  9670.                     case 8510:
  9671.                         if (check <= 54)
  9672.                             type = 0;
  9673.                         else if (check <= 74)
  9674.                             type = 1;
  9675.                         else if (check <= 94)
  9676.                             type = 2;
  9677.                         else
  9678.                             type = 3;
  9679.                         break;
  9680.                    
  9681.                     case 6525: // all theese lures (yellow) are prefered by ugly fish (type 2)
  9682.                     case 8511:
  9683.                     case 6526:
  9684.                     case 6527:
  9685.                     case 8513:
  9686.                         if (check <= 55)
  9687.                             type = 2;
  9688.                         else if (check <= 74)
  9689.                             type = 1;
  9690.                         else if (check <= 94)
  9691.                             type = 0;
  9692.                         else
  9693.                             type = 3;
  9694.                         break;
  9695.                     case 8484: // prize-winning fishing lure
  9696.                         if (check <= 33)
  9697.                             type = 0;
  9698.                         else if (check <= 66)
  9699.                             type = 1;
  9700.                         else
  9701.                             type = 2;
  9702.                         break;
  9703.                 }
  9704.                 break;
  9705.            
  9706.             case 2: // upper grade fish, luminous lure
  9707.                 switch (_lure.getItemId())
  9708.                 {
  9709.                     case 8506: // green lure, preferred by fast-moving (nimble) fish (type 8)
  9710.                         if (check <= 54)
  9711.                             type = 8;
  9712.                         else if (check <= 77)
  9713.                             type = 7;
  9714.                         else
  9715.                             type = 9;
  9716.                         break;
  9717.                    
  9718.                     case 8509: // purple lure, preferred by fat fish (type 7)
  9719.                         if (check <= 54)
  9720.                             type = 7;
  9721.                         else if (check <= 77)
  9722.                             type = 9;
  9723.                         else
  9724.                             type = 8;
  9725.                         break;
  9726.                    
  9727.                     case 8512: // yellow lure, preferred by ugly fish (type 9)
  9728.                         if (check <= 54)
  9729.                             type = 9;
  9730.                         else if (check <= 77)
  9731.                             type = 8;
  9732.                         else
  9733.                             type = 7;
  9734.                         break;
  9735.                    
  9736.                     case 8485: // prize-winning fishing lure
  9737.                         if (check <= 33)
  9738.                             type = 7;
  9739.                         else if (check <= 66)
  9740.                             type = 8;
  9741.                         else
  9742.                             type = 9;
  9743.                         break;
  9744.                 }
  9745.         }
  9746.         return type;
  9747.     }
  9748.    
  9749.     private int getRandomFishLvl()
  9750.     {
  9751.         int skilllvl = getSkillLevel(1315);
  9752.        
  9753.         final L2Effect e = getFirstEffect(2274);
  9754.         if (e != null)
  9755.             skilllvl = (int) e.getSkill().getPower();
  9756.        
  9757.         if (skilllvl <= 0)
  9758.             return 1;
  9759.        
  9760.         int randomlvl;
  9761.        
  9762.         final int check = Rnd.get(100);
  9763.         if (check <= 50)
  9764.             randomlvl = skilllvl;
  9765.         else if (check <= 85)
  9766.         {
  9767.             randomlvl = skilllvl - 1;
  9768.             if (randomlvl <= 0)
  9769.                 randomlvl = 1;
  9770.         }
  9771.         else
  9772.         {
  9773.             randomlvl = skilllvl + 1;
  9774.             if (randomlvl > 27)
  9775.                 randomlvl = 27;
  9776.         }
  9777.         return randomlvl;
  9778.     }
  9779.    
  9780.     public void startFishCombat(boolean isNoob, boolean isUpperGrade)
  9781.     {
  9782.         _fishCombat = new L2Fishing(this, _fish, isNoob, isUpperGrade, _lure.getItemId());
  9783.     }
  9784.    
  9785.     public void endFishing(boolean win)
  9786.     {
  9787.         if (_fishCombat == null)
  9788.             sendPacket(SystemMessageId.BAIT_LOST_FISH_GOT_AWAY);
  9789.         else
  9790.             _fishCombat = null;
  9791.        
  9792.         _lure = null;
  9793.         _fishingLoc = null;
  9794.        
  9795.         // Ends fishing
  9796.         broadcastPacket(new ExFishingEnd(win, this));
  9797.         sendPacket(SystemMessageId.REEL_LINE_AND_STOP_FISHING);
  9798.         setIsImmobilized(false);
  9799.         stopLookingForFishTask();
  9800.     }
  9801.    
  9802.     public L2Fishing getFishCombat()
  9803.     {
  9804.         return _fishCombat;
  9805.     }
  9806.    
  9807.     public Location getFishingLoc()
  9808.     {
  9809.         return _fishingLoc;
  9810.     }
  9811.    
  9812.     public void setLure(L2ItemInstance lure)
  9813.     {
  9814.         _lure = lure;
  9815.     }
  9816.    
  9817.     public L2ItemInstance getLure()
  9818.     {
  9819.         return _lure;
  9820.     }
  9821.    
  9822.     public int getInventoryLimit()
  9823.     {
  9824.         int ivlim;
  9825.         if (getRace() == Race.Dwarf)
  9826.             ivlim = Config.INVENTORY_MAXIMUM_DWARF;
  9827.         else
  9828.             ivlim = Config.INVENTORY_MAXIMUM_NO_DWARF;
  9829.        
  9830.         ivlim += (int) getStat().calcStat(Stats.INV_LIM, 0, null, null);
  9831.        
  9832.         return ivlim;
  9833.     }
  9834.    
  9835.     /**
  9836.      * @return
  9837.      */
  9838.     public static int getQuestInventoryLimit()
  9839.     {
  9840.         return Config.INVENTORY_MAXIMUM_QUEST_ITEMS;
  9841.     }
  9842.    
  9843.     public int getWareHouseLimit()
  9844.     {
  9845.         int whlim;
  9846.         if (getRace() == Race.Dwarf)
  9847.             whlim = Config.WAREHOUSE_SLOTS_DWARF;
  9848.         else
  9849.             whlim = Config.WAREHOUSE_SLOTS_NO_DWARF;
  9850.         whlim += (int) getStat().calcStat(Stats.WH_LIM, 0, null, null);
  9851.        
  9852.         return whlim;
  9853.     }
  9854.    
  9855.     public int getPrivateSellStoreLimit()
  9856.     {
  9857.         int pslim;
  9858.         if (getRace() == Race.Dwarf)
  9859.             pslim = Config.MAX_PVTSTORE_SLOTS_DWARF;
  9860.         else
  9861.             pslim = Config.MAX_PVTSTORE_SLOTS_OTHER;
  9862.        
  9863.         pslim += (int) getStat().calcStat(Stats.P_SELL_LIM, 0, null, null);
  9864.        
  9865.         return pslim;
  9866.     }
  9867.    
  9868.     public int getPrivateBuyStoreLimit()
  9869.     {
  9870.         int pblim;
  9871.         if (getRace() == Race.Dwarf)
  9872.             pblim = Config.MAX_PVTSTORE_SLOTS_DWARF;
  9873.         else
  9874.             pblim = Config.MAX_PVTSTORE_SLOTS_OTHER;
  9875.        
  9876.         pblim += (int) getStat().calcStat(Stats.P_BUY_LIM, 0, null, null);
  9877.        
  9878.         return pblim;
  9879.     }
  9880.    
  9881.     public int getFreightLimit()
  9882.     {
  9883.         return Config.FREIGHT_SLOTS + (int) getStat().calcStat(Stats.FREIGHT_LIM, 0, null, null);
  9884.     }
  9885.    
  9886.     public int getDwarfRecipeLimit()
  9887.     {
  9888.         int recdlim = Config.DWARF_RECIPE_LIMIT;
  9889.         recdlim += (int) getStat().calcStat(Stats.REC_D_LIM, 0, null, null);
  9890.         return recdlim;
  9891.     }
  9892.    
  9893.     public int getCommonRecipeLimit()
  9894.     {
  9895.         int recclim = Config.COMMON_RECIPE_LIMIT;
  9896.         recclim += (int) getStat().calcStat(Stats.REC_C_LIM, 0, null, null);
  9897.         return recclim;
  9898.     }
  9899.    
  9900.     public int getMountNpcId()
  9901.     {
  9902.         return _mountNpcId;
  9903.     }
  9904.    
  9905.     public int getMountLevel()
  9906.     {
  9907.         return _mountLevel;
  9908.     }
  9909.    
  9910.     public void setMountObjectID(int newID)
  9911.     {
  9912.         _mountObjectID = newID;
  9913.     }
  9914.    
  9915.     public int getMountObjectID()
  9916.     {
  9917.         return _mountObjectID;
  9918.     }
  9919.    
  9920.     /**
  9921.      * @return the current skill in use or return null.
  9922.      */
  9923.     public SkillDat getCurrentSkill()
  9924.     {
  9925.         return _currentSkill;
  9926.     }
  9927.    
  9928.     /**
  9929.      * Create a new SkillDat object and set the player _currentSkill.
  9930.      * @param currentSkill
  9931.      * @param ctrlPressed
  9932.      * @param shiftPressed
  9933.      */
  9934.     public void setCurrentSkill(L2Skill currentSkill, boolean ctrlPressed, boolean shiftPressed)
  9935.     {
  9936.         if (currentSkill == null)
  9937.         {
  9938.             if (Config.DEBUG)
  9939.                 _log.info("Setting current skill: NULL for " + getName() + ".");
  9940.            
  9941.             _currentSkill = null;
  9942.             return;
  9943.         }
  9944.        
  9945.         if (Config.DEBUG)
  9946.             _log.info("Setting current skill: " + currentSkill.getName() + " (ID: " + currentSkill.getId() + ") for " + getName() + ".");
  9947.        
  9948.         _currentSkill = new SkillDat(currentSkill, ctrlPressed, shiftPressed);
  9949.     }
  9950.    
  9951.     /**
  9952.      * @return the current pet skill in use or return null.
  9953.      */
  9954.     public SkillDat getCurrentPetSkill()
  9955.     {
  9956.         return _currentPetSkill;
  9957.     }
  9958.    
  9959.     /**
  9960.      * Create a new SkillDat object and set the player _currentPetSkill.
  9961.      * @param currentSkill
  9962.      * @param ctrlPressed
  9963.      * @param shiftPressed
  9964.      */
  9965.     public void setCurrentPetSkill(L2Skill currentSkill, boolean ctrlPressed, boolean shiftPressed)
  9966.     {
  9967.         if (currentSkill == null)
  9968.         {
  9969.             if (Config.DEBUG)
  9970.                 _log.info("Setting current pet skill: NULL for " + getName() + ".");
  9971.            
  9972.             _currentPetSkill = null;
  9973.             return;
  9974.         }
  9975.        
  9976.         if (Config.DEBUG)
  9977.             _log.info("Setting current Pet skill: " + currentSkill.getName() + " (ID: " + currentSkill.getId() + ") for " + getName() + ".");
  9978.        
  9979.         _currentPetSkill = new SkillDat(currentSkill, ctrlPressed, shiftPressed);
  9980.     }
  9981.    
  9982.     public SkillDat getQueuedSkill()
  9983.     {
  9984.         return _queuedSkill;
  9985.     }
  9986.    
  9987.     /**
  9988.      * Create a new SkillDat object and queue it in the player _queuedSkill.
  9989.      * @param queuedSkill
  9990.      * @param ctrlPressed
  9991.      * @param shiftPressed
  9992.      */
  9993.     public void setQueuedSkill(L2Skill queuedSkill, boolean ctrlPressed, boolean shiftPressed)
  9994.     {
  9995.         if (queuedSkill == null)
  9996.         {
  9997.             if (Config.DEBUG)
  9998.                 _log.info("Setting queued skill: NULL for " + getName() + ".");
  9999.            
  10000.             _queuedSkill = null;
  10001.             return;
  10002.         }
  10003.        
  10004.         if (Config.DEBUG)
  10005.             _log.info("Setting queued skill: " + queuedSkill.getName() + " (ID: " + queuedSkill.getId() + ") for " + getName() + ".");
  10006.        
  10007.         _queuedSkill = new SkillDat(queuedSkill, ctrlPressed, shiftPressed);
  10008.     }
  10009.    
  10010.     /**
  10011.      * @return the timer to delay animation tasks, based on run speed.
  10012.      */
  10013.     public int getAnimationTimer()
  10014.     {
  10015.         int timer = 5000 - getRunSpeed() * 20;
  10016.         if (timer < 1000)
  10017.             timer = 1000;
  10018.        
  10019.         return timer;
  10020.     }
  10021.    
  10022.     /**
  10023.      * @return punishment level of player
  10024.      */
  10025.     public PunishLevel getPunishLevel()
  10026.     {
  10027.         return _punishLevel;
  10028.     }
  10029.    
  10030.     /**
  10031.      * @return True if player is jailed
  10032.      */
  10033.     public boolean isInJail()
  10034.     {
  10035.         return _punishLevel == PunishLevel.JAIL;
  10036.     }
  10037.    
  10038.     /**
  10039.      * @return True if player is chat banned
  10040.      */
  10041.     public boolean isChatBanned()
  10042.     {
  10043.         return _punishLevel == PunishLevel.CHAT;
  10044.     }
  10045.    
  10046.     public void setPunishLevel(int state)
  10047.     {
  10048.         switch (state)
  10049.         {
  10050.             case 0:
  10051.                 _punishLevel = PunishLevel.NONE;
  10052.                 break;
  10053.             case 1:
  10054.                 _punishLevel = PunishLevel.CHAT;
  10055.                 break;
  10056.             case 2:
  10057.                 _punishLevel = PunishLevel.JAIL;
  10058.                 break;
  10059.             case 3:
  10060.                 _punishLevel = PunishLevel.CHAR;
  10061.                 break;
  10062.             case 4:
  10063.                 _punishLevel = PunishLevel.ACC;
  10064.                 break;
  10065.         }
  10066.     }
  10067.    
  10068.     /**
  10069.      * Sets punish level for player based on delay
  10070.      * @param state
  10071.      * @param delayInMinutes -- 0 for infinite
  10072.      */
  10073.     public void setPunishLevel(PunishLevel state, int delayInMinutes)
  10074.     {
  10075.         long delayInMilliseconds = delayInMinutes * 60000L;
  10076.         switch (state)
  10077.         {
  10078.             case NONE: // Remove Punishments
  10079.             {
  10080.                 switch (_punishLevel)
  10081.                 {
  10082.                     case CHAT:
  10083.                     {
  10084.                         _punishLevel = state;
  10085.                         stopPunishTask(true);
  10086.                         sendPacket(new EtcStatusUpdate(this));
  10087.                         sendMessage("Chatting is now available.");
  10088.                         sendPacket(new PlaySound("systemmsg_e.345"));
  10089.                         break;
  10090.                     }
  10091.                     case JAIL:
  10092.                     {
  10093.                         _punishLevel = state;
  10094.                        
  10095.                         // Open a Html message to inform the player
  10096.                         NpcHtmlMessage htmlMsg = new NpcHtmlMessage(0);
  10097.                         htmlMsg.setFile("data/html/jail_out.htm");
  10098.                         sendPacket(htmlMsg);
  10099.                         stopPunishTask(true);
  10100.                         teleToLocation(17836, 170178, -3507, 20); // Floran village
  10101.                         break;
  10102.                     }
  10103.                 }
  10104.                 break;
  10105.             }
  10106.             case CHAT: // Chat ban
  10107.             {
  10108.                 // not allow player to escape jail using chat ban
  10109.                 if (_punishLevel == PunishLevel.JAIL)
  10110.                     break;
  10111.                
  10112.                 _punishLevel = state;
  10113.                 _punishTimer = 0;
  10114.                 sendPacket(new EtcStatusUpdate(this));
  10115.                
  10116.                 // Remove the task if any
  10117.                 stopPunishTask(false);
  10118.                
  10119.                 if (delayInMinutes > 0)
  10120.                 {
  10121.                     _punishTimer = delayInMilliseconds;
  10122.                    
  10123.                     // start the countdown
  10124.                     _punishTask = ThreadPoolManager.getInstance().scheduleGeneral(new PunishTask(), _punishTimer);
  10125.                     sendMessage("Chatting has been suspended for " + delayInMinutes + " minute(s).");
  10126.                 }
  10127.                 else
  10128.                     sendMessage("Chatting has been suspended.");
  10129.                
  10130.                 // Send same sound packet in both "delay" cases.
  10131.                 sendPacket(new PlaySound("systemmsg_e.346"));
  10132.                 break;
  10133.                
  10134.             }
  10135.             case JAIL: // Jail Player
  10136.             {
  10137.                 _punishLevel = state;
  10138.                 _punishTimer = 0;
  10139.                
  10140.                 // Remove the task if any
  10141.                 stopPunishTask(false);
  10142.                
  10143.                 if (delayInMinutes > 0)
  10144.                 {
  10145.                     _punishTimer = delayInMilliseconds;
  10146.                    
  10147.                     // start the countdown
  10148.                     _punishTask = ThreadPoolManager.getInstance().scheduleGeneral(new PunishTask(), _punishTimer);
  10149.                     sendMessage("You are jailed for " + delayInMinutes + " minutes.");
  10150.                 }
  10151.                
  10152.                 if (OlympiadManager.getInstance().isRegisteredInComp(this))
  10153.                     OlympiadManager.getInstance().removeDisconnectedCompetitor(this);
  10154.                
  10155.                 // Open a Html message to inform the player
  10156.                 NpcHtmlMessage htmlMsg = new NpcHtmlMessage(0);
  10157.                 htmlMsg.setFile("data/html/jail_in.htm");
  10158.                 sendPacket(htmlMsg);
  10159.                 setIsIn7sDungeon(false);
  10160.                
  10161.                 teleToLocation(-114356, -249645, -2984, 0); // Jail
  10162.                 break;
  10163.             }
  10164.             case CHAR: // Ban Character
  10165.             {
  10166.                 setAccessLevel(-100);
  10167.                 logout();
  10168.                 break;
  10169.             }
  10170.             case ACC: // Ban Account
  10171.             {
  10172.                 setAccountAccesslevel(-100);
  10173.                 logout();
  10174.                 break;
  10175.             }
  10176.             default:
  10177.             {
  10178.                 _punishLevel = state;
  10179.                 break;
  10180.             }
  10181.         }
  10182.        
  10183.         // store in database
  10184.         storeCharBase();
  10185.     }
  10186.    
  10187.     public long getPunishTimer()
  10188.     {
  10189.         return _punishTimer;
  10190.     }
  10191.    
  10192.     public void setPunishTimer(long time)
  10193.     {
  10194.         _punishTimer = time;
  10195.     }
  10196.    
  10197.     private void updatePunishState()
  10198.     {
  10199.         if (getPunishLevel() != PunishLevel.NONE)
  10200.         {
  10201.             // If punish timer exists, restart punishtask.
  10202.             if (_punishTimer > 0)
  10203.             {
  10204.                 _punishTask = ThreadPoolManager.getInstance().scheduleGeneral(new PunishTask(), _punishTimer);
  10205.                 sendMessage("You are still " + getPunishLevel().string() + " for " + Math.round(_punishTimer / 60000f) + " minutes.");
  10206.             }
  10207.             if (getPunishLevel() == PunishLevel.JAIL)
  10208.             {
  10209.                 // If player escaped, put him back in jail
  10210.                 if (!isInsideZone(ZoneId.JAIL))
  10211.                     teleToLocation(-114356, -249645, -2984, 20);
  10212.             }
  10213.         }
  10214.     }
  10215.    
  10216.     public void stopPunishTask(boolean save)
  10217.     {
  10218.         if (_punishTask != null)
  10219.         {
  10220.             if (save)
  10221.             {
  10222.                 long delay = _punishTask.getDelay(TimeUnit.MILLISECONDS);
  10223.                 if (delay < 0)
  10224.                     delay = 0;
  10225.                 setPunishTimer(delay);
  10226.             }
  10227.             _punishTask.cancel(false);
  10228.             _punishTask = null;
  10229.         }
  10230.     }
  10231.    
  10232.     protected class PunishTask implements Runnable
  10233.     {
  10234.         @Override
  10235.         public void run()
  10236.         {
  10237.             setPunishLevel(PunishLevel.NONE, 0);
  10238.         }
  10239.     }
  10240.    
  10241.     public int getPowerGrade()
  10242.     {
  10243.         return _powerGrade;
  10244.     }
  10245.    
  10246.     public void setPowerGrade(int power)
  10247.     {
  10248.         _powerGrade = power;
  10249.     }
  10250.    
  10251.     public boolean isCursedWeaponEquipped()
  10252.     {
  10253.         return _cursedWeaponEquippedId != 0;
  10254.     }
  10255.    
  10256.     public void setCursedWeaponEquippedId(int value)
  10257.     {
  10258.         _cursedWeaponEquippedId = value;
  10259.     }
  10260.    
  10261.     public int getCursedWeaponEquippedId()
  10262.     {
  10263.         return _cursedWeaponEquippedId;
  10264.     }
  10265.    
  10266.     public void shortBuffStatusUpdate(int magicId, int level, int time)
  10267.     {
  10268.         if (_shortBuffTask != null)
  10269.         {
  10270.             _shortBuffTask.cancel(false);
  10271.             _shortBuffTask = null;
  10272.         }
  10273.         _shortBuffTask = ThreadPoolManager.getInstance().scheduleGeneral(new ShortBuffTask(), time * 1000);
  10274.         setShortBuffTaskSkillId(magicId);
  10275.        
  10276.         sendPacket(new ShortBuffStatusUpdate(magicId, level, time));
  10277.     }
  10278.    
  10279.     public int getShortBuffTaskSkillId()
  10280.     {
  10281.         return _shortBuffTaskSkillId;
  10282.     }
  10283.    
  10284.     public void setShortBuffTaskSkillId(int id)
  10285.     {
  10286.         _shortBuffTaskSkillId = id;
  10287.     }
  10288.    
  10289.     public int getDeathPenaltyBuffLevel()
  10290.     {
  10291.         return _deathPenaltyBuffLevel;
  10292.     }
  10293.    
  10294.     public void setDeathPenaltyBuffLevel(int level)
  10295.     {
  10296.         _deathPenaltyBuffLevel = level;
  10297.     }
  10298.    
  10299.     public void calculateDeathPenaltyBuffLevel(L2Character killer)
  10300.     {
  10301.         if ((getKarma() > 0 || Rnd.get(1, 100) <= Config.DEATH_PENALTY_CHANCE) && !(killer instanceof L2PcInstance) && !isGM() && !(getCharmOfLuck() && killer.isRaid()) && !isPhoenixBlessed() && !(isInsideZone(ZoneId.PVP) || isInsideZone(ZoneId.SIEGE)))
  10302.             increaseDeathPenaltyBuffLevel();
  10303.     }
  10304.    
  10305.     public void increaseDeathPenaltyBuffLevel()
  10306.     {
  10307.         if (getDeathPenaltyBuffLevel() >= 15) // maximum level reached
  10308.             return;
  10309.        
  10310.         if (getDeathPenaltyBuffLevel() != 0)
  10311.         {
  10312.             L2Skill skill = SkillTable.getInstance().getInfo(5076, getDeathPenaltyBuffLevel());
  10313.            
  10314.             if (skill != null)
  10315.                 removeSkill(skill, true);
  10316.         }
  10317.        
  10318.         _deathPenaltyBuffLevel++;
  10319.        
  10320.         addSkill(SkillTable.getInstance().getInfo(5076, getDeathPenaltyBuffLevel()), false);
  10321.         sendPacket(new EtcStatusUpdate(this));
  10322.         sendPacket(SystemMessage.getSystemMessage(SystemMessageId.DEATH_PENALTY_LEVEL_S1_ADDED).addNumber(getDeathPenaltyBuffLevel()));
  10323.     }
  10324.    
  10325.     public void reduceDeathPenaltyBuffLevel()
  10326.     {
  10327.         if (getDeathPenaltyBuffLevel() <= 0)
  10328.             return;
  10329.        
  10330.         L2Skill skill = SkillTable.getInstance().getInfo(5076, getDeathPenaltyBuffLevel());
  10331.        
  10332.         if (skill != null)
  10333.             removeSkill(skill, true);
  10334.        
  10335.         _deathPenaltyBuffLevel--;
  10336.        
  10337.         if (getDeathPenaltyBuffLevel() > 0)
  10338.         {
  10339.             addSkill(SkillTable.getInstance().getInfo(5076, getDeathPenaltyBuffLevel()), false);
  10340.             sendPacket(new EtcStatusUpdate(this));
  10341.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.DEATH_PENALTY_LEVEL_S1_ADDED).addNumber(getDeathPenaltyBuffLevel()));
  10342.         }
  10343.         else
  10344.         {
  10345.             sendPacket(new EtcStatusUpdate(this));
  10346.             sendPacket(SystemMessageId.DEATH_PENALTY_LIFTED);
  10347.         }
  10348.     }
  10349.    
  10350.     public void restoreDeathPenaltyBuffLevel()
  10351.     {
  10352.         if (getDeathPenaltyBuffLevel() > 0)
  10353.             addSkill(SkillTable.getInstance().getInfo(5076, getDeathPenaltyBuffLevel()), false);
  10354.     }
  10355.    
  10356.     private final Map<Integer, TimeStamp> _reuseTimeStamps = new ConcurrentHashMap<>();
  10357.    
  10358.     public Collection<TimeStamp> getReuseTimeStamps()
  10359.     {
  10360.         return _reuseTimeStamps.values();
  10361.     }
  10362.    
  10363.     public Map<Integer, TimeStamp> getReuseTimeStamp()
  10364.     {
  10365.         return _reuseTimeStamps;
  10366.     }
  10367.    
  10368.     /**
  10369.      * Simple class containing all neccessary information to maintain valid timestamps and reuse for skills upon relog. Filter this carefully as it becomes redundant to store reuse for small delays.
  10370.      * @author Yesod
  10371.      */
  10372.     public static class TimeStamp
  10373.     {
  10374.         private final int _skillId;
  10375.         private final int _skillLvl;
  10376.         private final long _reuse;
  10377.         private final long _stamp;
  10378.        
  10379.         public TimeStamp(L2Skill skill, long reuse)
  10380.         {
  10381.             _skillId = skill.getId();
  10382.             _skillLvl = skill.getLevel();
  10383.             _reuse = reuse;
  10384.             _stamp = System.currentTimeMillis() + reuse;
  10385.         }
  10386.        
  10387.         public TimeStamp(L2Skill skill, long reuse, long systime)
  10388.         {
  10389.             _skillId = skill.getId();
  10390.             _skillLvl = skill.getLevel();
  10391.             _reuse = reuse;
  10392.             _stamp = systime;
  10393.         }
  10394.        
  10395.         public long getStamp()
  10396.         {
  10397.             return _stamp;
  10398.         }
  10399.        
  10400.         public int getSkillId()
  10401.         {
  10402.             return _skillId;
  10403.         }
  10404.        
  10405.         public int getSkillLvl()
  10406.         {
  10407.             return _skillLvl;
  10408.         }
  10409.        
  10410.         public long getReuse()
  10411.         {
  10412.             return _reuse;
  10413.         }
  10414.        
  10415.         public long getRemaining()
  10416.         {
  10417.             return Math.max(_stamp - System.currentTimeMillis(), 0);
  10418.         }
  10419.        
  10420.         /*
  10421.          * Check if the reuse delay has passed and if it has not then update the stored reuse time according to what is currently remaining on the delay.
  10422.          */
  10423.         public boolean hasNotPassed()
  10424.         {
  10425.             return System.currentTimeMillis() < _stamp;
  10426.         }
  10427.     }
  10428.    
  10429.     /**
  10430.      * Index according to skill id the current timestamp of use.
  10431.      * @param skill
  10432.      * @param reuse delay
  10433.      */
  10434.     @Override
  10435.     public void addTimeStamp(L2Skill skill, long reuse)
  10436.     {
  10437.         _reuseTimeStamps.put(skill.getReuseHashCode(), new TimeStamp(skill, reuse));
  10438.     }
  10439.    
  10440.     /**
  10441.      * Index according to skill this TimeStamp instance for restoration purposes only.
  10442.      * @param skill
  10443.      * @param reuse
  10444.      * @param systime
  10445.      */
  10446.     public void addTimeStamp(L2Skill skill, long reuse, long systime)
  10447.     {
  10448.         _reuseTimeStamps.put(skill.getReuseHashCode(), new TimeStamp(skill, reuse, systime));
  10449.     }
  10450.    
  10451.     @Override
  10452.     public L2PcInstance getActingPlayer()
  10453.     {
  10454.         return this;
  10455.     }
  10456.    
  10457.     @Override
  10458.     public final void sendDamageMessage(L2Character target, int damage, boolean mcrit, boolean pcrit, boolean miss)
  10459.     {
  10460.         // Check if hit is missed
  10461.         if (miss)
  10462.         {
  10463.             sendPacket(SystemMessageId.MISSED_TARGET);
  10464.             return;
  10465.         }
  10466.        
  10467.         // Check if hit is critical
  10468.         if (pcrit)
  10469.             sendPacket(SystemMessageId.CRITICAL_HIT);
  10470.         if (mcrit)
  10471.             sendPacket(SystemMessageId.CRITICAL_HIT_MAGIC);
  10472.        
  10473.         if (target.isInvul())
  10474.         {
  10475.             if (target.isParalyzed())
  10476.                 sendPacket(SystemMessageId.OPPONENT_PETRIFIED);
  10477.             else
  10478.                 sendPacket(SystemMessageId.ATTACK_WAS_BLOCKED);
  10479.         }
  10480.         else
  10481.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_DID_S1_DMG).addNumber(damage));
  10482.        
  10483.         if (isInOlympiadMode() && target instanceof L2PcInstance && ((L2PcInstance) target).isInOlympiadMode() && ((L2PcInstance) target).getOlympiadGameId() == getOlympiadGameId())
  10484.             OlympiadGameManager.getInstance().notifyCompetitorDamage(this, damage);
  10485.     }
  10486.    
  10487.     public void checkItemRestriction()
  10488.     {
  10489.         for (int i = 0; i < Inventory.PAPERDOLL_TOTALSLOTS; i++)
  10490.         {
  10491.             L2ItemInstance equippedItem = getInventory().getPaperdollItem(i);
  10492.             if (equippedItem != null && !equippedItem.getItem().checkCondition(this, this, false))
  10493.             {
  10494.                 getInventory().unEquipItemInSlot(i);
  10495.                
  10496.                 InventoryUpdate iu = new InventoryUpdate();
  10497.                 iu.addModifiedItem(equippedItem);
  10498.                 sendPacket(iu);
  10499.                
  10500.                 SystemMessage sm = null;
  10501.                 if (equippedItem.getEnchantLevel() > 0)
  10502.                 {
  10503.                     sm = SystemMessage.getSystemMessage(SystemMessageId.EQUIPMENT_S1_S2_REMOVED);
  10504.                     sm.addNumber(equippedItem.getEnchantLevel());
  10505.                     sm.addItemName(equippedItem);
  10506.                 }
  10507.                 else
  10508.                 {
  10509.                     sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISARMED);
  10510.                     sm.addItemName(equippedItem);
  10511.                 }
  10512.                 sendPacket(sm);
  10513.             }
  10514.         }
  10515.     }
  10516.    
  10517.     protected class Dismount implements Runnable
  10518.     {
  10519.         @Override
  10520.         public void run()
  10521.         {
  10522.             try
  10523.             {
  10524.                 dismount();
  10525.             }
  10526.             catch (Exception e)
  10527.             {
  10528.                 _log.log(Level.WARNING, "Exception on dismount(): " + e.getMessage(), e);
  10529.             }
  10530.         }
  10531.     }
  10532.    
  10533.     public void enteredNoLanding(int delay)
  10534.     {
  10535.         _dismountTask = ThreadPoolManager.getInstance().scheduleGeneral(new Dismount(), delay * 1000);
  10536.     }
  10537.    
  10538.     public void exitedNoLanding()
  10539.     {
  10540.         if (_dismountTask != null)
  10541.         {
  10542.             _dismountTask.cancel(true);
  10543.             _dismountTask = null;
  10544.         }
  10545.     }
  10546.    
  10547.     public void setIsInSiege(boolean b)
  10548.     {
  10549.         _isInSiege = b;
  10550.     }
  10551.    
  10552.     public boolean isInSiege()
  10553.     {
  10554.         return _isInSiege;
  10555.     }
  10556.    
  10557.     public FloodProtectors getFloodProtectors()
  10558.     {
  10559.         return getClient().getFloodProtectors();
  10560.     }
  10561.    
  10562.     /**
  10563.      * Remove player from BossZones (used on char logout/exit)
  10564.      */
  10565.     public void removeFromBossZone()
  10566.     {
  10567.         try
  10568.         {
  10569.             for (L2BossZone _zone : GrandBossManager.getZones())
  10570.                 _zone.removePlayer(this);
  10571.         }
  10572.         catch (Exception e)
  10573.         {
  10574.             _log.log(Level.WARNING, "Exception on removeFromBossZone(): " + e.getMessage(), e);
  10575.         }
  10576.     }
  10577.    
  10578.     /**
  10579.      * Returns the Number of Charges this L2PcInstance got.
  10580.      * @return
  10581.      */
  10582.     public int getCharges()
  10583.     {
  10584.         return _charges.get();
  10585.     }
  10586.    
  10587.     public synchronized void increaseCharges(int count, int max)
  10588.     {
  10589.         if (_charges.get() >= max)
  10590.         {
  10591.             sendPacket(SystemMessageId.FORCE_MAXLEVEL_REACHED);
  10592.             return;
  10593.         }
  10594.        
  10595.         // if no charges - start clear task
  10596.         if (_charges.get() == 0)
  10597.             restartChargeTask();
  10598.        
  10599.         if (_charges.addAndGet(count) >= max)
  10600.         {
  10601.             _charges.set(max);
  10602.             sendPacket(SystemMessageId.FORCE_MAXLEVEL_REACHED);
  10603.         }
  10604.         else
  10605.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FORCE_INCREASED_TO_S1).addNumber(_charges.get()));
  10606.        
  10607.         sendPacket(new EtcStatusUpdate(this));
  10608.     }
  10609.    
  10610.     public synchronized boolean decreaseCharges(int count)
  10611.     {
  10612.         if (_charges.get() < count)
  10613.             return false;
  10614.        
  10615.         if (_charges.addAndGet(-count) == 0)
  10616.             stopChargeTask();
  10617.        
  10618.         sendPacket(new EtcStatusUpdate(this));
  10619.         return true;
  10620.     }
  10621.    
  10622.     public void clearCharges()
  10623.     {
  10624.         _charges.set(0);
  10625.         sendPacket(new EtcStatusUpdate(this));
  10626.     }
  10627.    
  10628.     /**
  10629.      * Starts/Restarts the ChargeTask to Clear Charges after 10 Mins.
  10630.      */
  10631.     private void restartChargeTask()
  10632.     {
  10633.         if (_chargeTask != null)
  10634.         {
  10635.             _chargeTask.cancel(false);
  10636.             _chargeTask = null;
  10637.         }
  10638.         _chargeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ChargeTask(), 600000);
  10639.     }
  10640.    
  10641.     /**
  10642.      * Stops the Charges Clearing Task.
  10643.      */
  10644.     public void stopChargeTask()
  10645.     {
  10646.         if (_chargeTask != null)
  10647.         {
  10648.             _chargeTask.cancel(false);
  10649.             _chargeTask = null;
  10650.         }
  10651.     }
  10652.    
  10653.     protected class ChargeTask implements Runnable
  10654.     {
  10655.         @Override
  10656.         public void run()
  10657.         {
  10658.             clearCharges();
  10659.         }
  10660.     }
  10661.    
  10662.     /**
  10663.      * Signets check used to valid who is affected when he entered in the aoe effect.
  10664.      * @param cha The target to make checks on.
  10665.      * @return true if player can attack the target.
  10666.      */
  10667.     public boolean canAttackCharacter(L2Character cha)
  10668.     {
  10669.         if (cha instanceof L2Attackable)
  10670.             return true;
  10671.        
  10672.         if (cha instanceof L2Playable)
  10673.         {
  10674.             if (cha.isInArena())
  10675.                 return true;
  10676.            
  10677.             final L2PcInstance target = cha.getActingPlayer();
  10678.            
  10679.             if (isInDuel() && target.isInDuel() && target.getDuelId() == getDuelId())
  10680.                 return true;
  10681.            
  10682.             if (isInParty() && target.isInParty())
  10683.             {
  10684.                 if (getParty() == target.getParty())
  10685.                     return false;
  10686.                
  10687.                 if ((getParty().getCommandChannel() != null || target.getParty().getCommandChannel() != null) && (getParty().getCommandChannel() == target.getParty().getCommandChannel()))
  10688.                     return false;
  10689.             }
  10690.            
  10691.             if (getClan() != null && target.getClan() != null)
  10692.             {
  10693.                 if (getClanId() == target.getClanId())
  10694.                     return false;
  10695.                
  10696.                 if ((getAllyId() > 0 || target.getAllyId() > 0) && getAllyId() == target.getAllyId())
  10697.                     return false;
  10698.                
  10699.                 if (getClan().isAtWarWith(target.getClanId()))
  10700.                     return true;
  10701.             }
  10702.             else
  10703.             {
  10704.                 if (target.getPvpFlag() == 0 && target.getKarma() == 0)
  10705.                     return false;
  10706.             }
  10707.         }
  10708.         return true;
  10709.     }
  10710.    
  10711.     /**
  10712.      * Request Teleport
  10713.      * @param requester The player who requested the teleport.
  10714.      * @param skill The used skill.
  10715.      * @return true if successful.
  10716.      **/
  10717.     public boolean teleportRequest(L2PcInstance requester, L2Skill skill)
  10718.     {
  10719.         if (_summonRequest.getTarget() != null && requester != null)
  10720.             return false;
  10721.        
  10722.         _summonRequest.setTarget(requester, skill);
  10723.         return true;
  10724.     }
  10725.    
  10726.     /**
  10727.      * Action teleport
  10728.      * @param answer
  10729.      * @param requesterId
  10730.      **/
  10731.     public void teleportAnswer(int answer, int requesterId)
  10732.     {
  10733.         if (_summonRequest.getTarget() == null)
  10734.             return;
  10735.        
  10736.         if (answer == 1 && _summonRequest.getTarget().getObjectId() == requesterId)
  10737.             teleToTarget(this, _summonRequest.getTarget(), _summonRequest.getSkill());
  10738.        
  10739.         _summonRequest.setTarget(null, null);
  10740.     }
  10741.    
  10742.     public static void teleToTarget(L2PcInstance targetChar, L2PcInstance summonerChar, L2Skill summonSkill)
  10743.     {
  10744.         if (targetChar == null || summonerChar == null || summonSkill == null)
  10745.             return;
  10746.        
  10747.         if (!checkSummonerStatus(summonerChar))
  10748.             return;
  10749.         if (!checkSummonTargetStatus(targetChar, summonerChar))
  10750.             return;
  10751.        
  10752.         int itemConsumeId = summonSkill.getTargetConsumeId();
  10753.         int itemConsumeCount = summonSkill.getTargetConsume();
  10754.         if (itemConsumeId != 0 && itemConsumeCount != 0)
  10755.         {
  10756.             // Delete by rocknow
  10757.             if (targetChar.getInventory().getInventoryItemCount(itemConsumeId, 0) < itemConsumeCount)
  10758.             {
  10759.                 targetChar.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_REQUIRED_FOR_SUMMONING).addItemName(summonSkill.getTargetConsumeId()));
  10760.                 return;
  10761.             }
  10762.             targetChar.getInventory().destroyItemByItemId("Consume", itemConsumeId, itemConsumeCount, summonerChar, targetChar);
  10763.             targetChar.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED).addItemName(summonSkill.getTargetConsumeId()));
  10764.         }
  10765.         targetChar.teleToLocation(summonerChar.getX(), summonerChar.getY(), summonerChar.getZ(), 20);
  10766.     }
  10767.    
  10768.     public static boolean checkSummonerStatus(L2PcInstance summonerChar)
  10769.     {
  10770.         if (summonerChar == null)
  10771.             return false;
  10772.        
  10773.         if (summonerChar.isInOlympiadMode() || summonerChar.inObserverMode() || summonerChar.isInsideZone(ZoneId.NO_SUMMON_FRIEND) || summonerChar.isMounted())
  10774.             return false;
  10775.        
  10776.         return true;
  10777.     }
  10778.    
  10779.     public static boolean checkSummonTargetStatus(L2Object target, L2PcInstance summonerChar)
  10780.     {
  10781.         if (target == null || !(target instanceof L2PcInstance))
  10782.             return false;
  10783.        
  10784.         L2PcInstance targetChar = (L2PcInstance) target;
  10785.        
  10786.         if (targetChar.isAlikeDead())
  10787.         {
  10788.             summonerChar.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_IS_DEAD_AT_THE_MOMENT_AND_CANNOT_BE_SUMMONED).addPcName(targetChar));
  10789.             return false;
  10790.         }
  10791.        
  10792.         if (targetChar.isInStoreMode())
  10793.         {
  10794.             summonerChar.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_CURRENTLY_TRADING_OR_OPERATING_PRIVATE_STORE_AND_CANNOT_BE_SUMMONED).addPcName(targetChar));
  10795.             return false;
  10796.         }
  10797.        
  10798.         if (targetChar.isRooted() || targetChar.isInCombat())
  10799.         {
  10800.             summonerChar.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_IS_ENGAGED_IN_COMBAT_AND_CANNOT_BE_SUMMONED).addPcName(targetChar));
  10801.             return false;
  10802.         }
  10803.        
  10804.         if (targetChar.isInOlympiadMode())
  10805.         {
  10806.             summonerChar.sendPacket(SystemMessageId.YOU_CANNOT_SUMMON_PLAYERS_WHO_ARE_IN_OLYMPIAD);
  10807.             return false;
  10808.         }
  10809.        
  10810.         if (targetChar.isFestivalParticipant() || targetChar.isMounted())
  10811.         {
  10812.             summonerChar.sendPacket(SystemMessageId.YOUR_TARGET_IS_IN_AN_AREA_WHICH_BLOCKS_SUMMONING);
  10813.             return false;
  10814.         }
  10815.        
  10816.         if (targetChar.inObserverMode() || targetChar.isInsideZone(ZoneId.NO_SUMMON_FRIEND))
  10817.         {
  10818.             summonerChar.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_IN_SUMMON_BLOCKING_AREA).addCharName(targetChar));
  10819.             return false;
  10820.         }
  10821.        
  10822.         return true;
  10823.     }
  10824.    
  10825.     public final int getClientX()
  10826.     {
  10827.         return _clientX;
  10828.     }
  10829.    
  10830.     public final int getClientY()
  10831.     {
  10832.         return _clientY;
  10833.     }
  10834.    
  10835.     public final int getClientZ()
  10836.     {
  10837.         return _clientZ;
  10838.     }
  10839.    
  10840.     public final int getClientHeading()
  10841.     {
  10842.         return _clientHeading;
  10843.     }
  10844.    
  10845.     public final void setClientX(int val)
  10846.     {
  10847.         _clientX = val;
  10848.     }
  10849.    
  10850.     public final void setClientY(int val)
  10851.     {
  10852.         _clientY = val;
  10853.     }
  10854.    
  10855.     public final void setClientZ(int val)
  10856.     {
  10857.         _clientZ = val;
  10858.     }
  10859.    
  10860.     public final void setClientHeading(int val)
  10861.     {
  10862.         _clientHeading = val;
  10863.     }
  10864.    
  10865.     /**
  10866.      * @return the mailPosition.
  10867.      */
  10868.     public int getMailPosition()
  10869.     {
  10870.         return _mailPosition;
  10871.     }
  10872.    
  10873.     /**
  10874.      * @param mailPosition The mailPosition to set.
  10875.      */
  10876.     public void setMailPosition(int mailPosition)
  10877.     {
  10878.         _mailPosition = mailPosition;
  10879.     }
  10880.    
  10881.     /**
  10882.      * @param z
  10883.      * @return true if character falling now On the start of fall return false for correct coord sync !
  10884.      */
  10885.     public final boolean isFalling(int z)
  10886.     {
  10887.         if (isDead() || isFlying() || isInsideZone(ZoneId.WATER))
  10888.             return false;
  10889.        
  10890.         if (System.currentTimeMillis() < _fallingTimestamp)
  10891.             return true;
  10892.        
  10893.         final int deltaZ = getZ() - z;
  10894.         if (deltaZ <= getBaseTemplate().getFallHeight())
  10895.             return false;
  10896.        
  10897.         final int damage = (int) Formulas.calcFallDam(this, deltaZ);
  10898.         if (damage > 0)
  10899.         {
  10900.             reduceCurrentHp(Math.min(damage, getCurrentHp() - 1), null, false, true, null);
  10901.             sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FALL_DAMAGE_S1).addNumber(damage));
  10902.         }
  10903.        
  10904.         setFalling();
  10905.        
  10906.         return false;
  10907.     }
  10908.    
  10909.     /**
  10910.      * Set falling timestamp
  10911.      */
  10912.     public final void setFalling()
  10913.     {
  10914.         _fallingTimestamp = System.currentTimeMillis() + FALLING_VALIDATION_DELAY;
  10915.     }
  10916.    
  10917.     public boolean isAllowedToEnchantSkills()
  10918.     {
  10919.         if (isLocked())
  10920.             return false;
  10921.        
  10922.         if (AttackStanceTaskManager.getInstance().getAttackStanceTask(this))
  10923.             return false;
  10924.        
  10925.         if (isCastingNow() || isCastingSimultaneouslyNow())
  10926.             return false;
  10927.        
  10928.         if (isInBoat())
  10929.             return false;
  10930.        
  10931.         return true;
  10932.     }
  10933.    
  10934.     /**
  10935.      * Friendlist / selected Friendlist (for community board)
  10936.      */
  10937.     private final List<Integer> _friendList = new ArrayList<>();
  10938.     private final List<Integer> _selectedFriendList = new ArrayList<>();
  10939.    
  10940.     public List<Integer> getFriendList()
  10941.     {
  10942.         return _friendList;
  10943.     }
  10944.    
  10945.     public void selectFriend(Integer friendId)
  10946.     {
  10947.         if (!_selectedFriendList.contains(friendId))
  10948.             _selectedFriendList.add(friendId);
  10949.     }
  10950.    
  10951.     public void deselectFriend(Integer friendId)
  10952.     {
  10953.         if (_selectedFriendList.contains(friendId))
  10954.             _selectedFriendList.remove(friendId);
  10955.     }
  10956.    
  10957.     public long getOfflineStartTime()
  10958.     {
  10959.         return _offlineShopStart;
  10960.     }
  10961.    
  10962.     public void setOfflineStartTime(long time)
  10963.     {
  10964.         _offlineShopStart = time;
  10965.     }
  10966.    
  10967.     public boolean inOfflineShopMode()
  10968.     {
  10969.         return _inOfflineShopMode;
  10970.     }
  10971.    
  10972.     public void setOfflineShopMode(boolean value)
  10973.     {
  10974.         _inOfflineShopMode = value;
  10975.     }
  10976.    
  10977.     public List<Integer> getSelectedFriendList()
  10978.     {
  10979.         return _selectedFriendList;
  10980.     }
  10981.    
  10982.     private void restoreFriendList()
  10983.     {
  10984.         _friendList.clear();
  10985.        
  10986.         try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  10987.         {
  10988.             PreparedStatement statement = con.prepareStatement("SELECT friend_id FROM character_friends WHERE char_id = ? AND relation = 0");
  10989.             statement.setInt(1, getObjectId());
  10990.             ResultSet rset = statement.executeQuery();
  10991.            
  10992.             int friendId;
  10993.             while (rset.next())
  10994.             {
  10995.                 friendId = rset.getInt("friend_id");
  10996.                 if (friendId == getObjectId())
  10997.                     continue;
  10998.                
  10999.                 _friendList.add(friendId);
  11000.             }
  11001.            
  11002.             rset.close();
  11003.             statement.close();
  11004.         }
  11005.         catch (Exception e)
  11006.         {
  11007.             _log.log(Level.WARNING, "Error found in " + getName() + "'s friendlist: " + e.getMessage(), e);
  11008.         }
  11009.     }
  11010.    
  11011.     private void notifyFriends(boolean login)
  11012.     {
  11013.         for (int id : _friendList)
  11014.         {
  11015.             L2PcInstance friend = L2World.getInstance().getPlayer(id);
  11016.             if (friend != null)
  11017.             {
  11018.                 friend.sendPacket(new FriendList(friend));
  11019.                
  11020.                 if (login)
  11021.                     friend.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.FRIEND_S1_HAS_LOGGED_IN).addPcName(this));
  11022.             }
  11023.         }
  11024.     }
  11025.    
  11026.     private final List<Integer> _selectedBlocksList = new ArrayList<>();
  11027.    
  11028.     public void selectBlock(Integer friendId)
  11029.     {
  11030.         if (!_selectedBlocksList.contains(friendId))
  11031.             _selectedBlocksList.add(friendId);
  11032.     }
  11033.    
  11034.     public void deselectBlock(Integer friendId)
  11035.     {
  11036.         if (_selectedBlocksList.contains(friendId))
  11037.             _selectedBlocksList.remove(friendId);
  11038.     }
  11039.    
  11040.     public List<Integer> getSelectedBlocksList()
  11041.     {
  11042.         return _selectedBlocksList;
  11043.     }
  11044.    
  11045.     /**
  11046.      * Test if player inventory is under 80% capaity
  11047.      * @param includeQuestInv check also quest inventory
  11048.      * @return
  11049.      */
  11050.     public boolean isInventoryUnder80(boolean includeQuestInv)
  11051.     {
  11052.         if (getInventory().getSize(false) <= (getInventoryLimit() * 0.8))
  11053.         {
  11054.             if (includeQuestInv)
  11055.             {
  11056.                 if (getInventory().getSize(true) <= (getQuestInventoryLimit() * 0.8))
  11057.                     return true;
  11058.             }
  11059.             else
  11060.                 return true;
  11061.         }
  11062.         return false;
  11063.     }
  11064.    
  11065.     @Override
  11066.     public void broadcastRelationsChanges()
  11067.     {
  11068.         for (L2PcInstance player : getKnownList().getKnownType(L2PcInstance.class))
  11069.         {
  11070.             player.sendPacket(new RelationChanged(this, getRelation(player), isAutoAttackable(player)));
  11071.             if (getPet() != null)
  11072.                 player.sendPacket(new RelationChanged(getPet(), getRelation(player), isAutoAttackable(player)));
  11073.         }
  11074.     }
  11075.    
  11076.     @Override
  11077.     public void sendInfo(L2PcInstance activeChar)
  11078.     {
  11079.         if (isInBoat())
  11080.             getPosition().setWorldPosition(getBoat().getPosition().getWorldPosition());
  11081.        
  11082.         if (getPoly().isMorphed())
  11083.             activeChar.sendPacket(new AbstractNpcInfo.PcMorphInfo(this, getPoly().getNpcTemplate()));
  11084.         else
  11085.             activeChar.sendPacket(new CharInfo(this));
  11086.        
  11087.         final int relation1 = getRelation(activeChar);
  11088.         activeChar.sendPacket(new RelationChanged(this, relation1, isAutoAttackable(activeChar)));
  11089.         if (getPet() != null)
  11090.             activeChar.sendPacket(new RelationChanged(getPet(), relation1, isAutoAttackable(activeChar)));
  11091.        
  11092.         final int relation2 = activeChar.getRelation(this);
  11093.         sendPacket(new RelationChanged(activeChar, relation2, activeChar.isAutoAttackable(this)));
  11094.         if (activeChar.getPet() != null)
  11095.             sendPacket(new RelationChanged(activeChar.getPet(), relation2, activeChar.isAutoAttackable(this)));
  11096.        
  11097.         if (isInBoat())
  11098.             activeChar.sendPacket(new GetOnVehicle(getObjectId(), getBoat().getObjectId(), getInVehiclePosition()));
  11099.        
  11100.         // No reason to try to broadcast shop message if player isn't in store mode
  11101.         if (isInStoreMode())
  11102.         {
  11103.             switch (getPrivateStoreType())
  11104.             {
  11105.                 case STORE_PRIVATE_SELL:
  11106.                 case STORE_PRIVATE_PACKAGE_SELL:
  11107.                     activeChar.sendPacket(new PrivateStoreMsgSell(this));
  11108.                     break;
  11109.                 case STORE_PRIVATE_BUY:
  11110.                     activeChar.sendPacket(new PrivateStoreMsgBuy(this));
  11111.                     break;
  11112.                 case STORE_PRIVATE_MANUFACTURE:
  11113.                     activeChar.sendPacket(new RecipeShopMsg(this));
  11114.                     break;
  11115.             }
  11116.         }
  11117.     }
  11118. }
Advertisement
Add Comment
Please, Sign In to add comment