Castle.java 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  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 com.l2jserver.gameserver.model.entity;
  16. import gnu.trove.TIntIntHashMap;
  17. import java.sql.Connection;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.util.ArrayList;
  21. import java.util.Calendar;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import javolution.util.FastList;
  27. import javolution.util.FastMap;
  28. import com.l2jserver.Config;
  29. import com.l2jserver.L2DatabaseFactory;
  30. import com.l2jserver.gameserver.CastleUpdater;
  31. import com.l2jserver.gameserver.SevenSigns;
  32. import com.l2jserver.gameserver.ThreadPoolManager;
  33. import com.l2jserver.gameserver.datatables.ClanTable;
  34. import com.l2jserver.gameserver.datatables.DoorTable;
  35. import com.l2jserver.gameserver.datatables.SkillTable;
  36. import com.l2jserver.gameserver.datatables.SkillTreesData;
  37. import com.l2jserver.gameserver.instancemanager.CastleManager;
  38. import com.l2jserver.gameserver.instancemanager.CastleManorManager;
  39. import com.l2jserver.gameserver.instancemanager.CastleManorManager.CropProcure;
  40. import com.l2jserver.gameserver.instancemanager.CastleManorManager.SeedProduction;
  41. import com.l2jserver.gameserver.instancemanager.FortManager;
  42. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager;
  43. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager.Territory;
  44. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  45. import com.l2jserver.gameserver.model.L2Clan;
  46. import com.l2jserver.gameserver.model.L2Manor;
  47. import com.l2jserver.gameserver.model.L2Object;
  48. import com.l2jserver.gameserver.model.L2Skill;
  49. import com.l2jserver.gameserver.model.L2SkillLearn;
  50. import com.l2jserver.gameserver.model.actor.instance.L2ArtefactInstance;
  51. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  52. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  53. import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
  54. import com.l2jserver.gameserver.model.zone.type.L2CastleZone;
  55. import com.l2jserver.gameserver.model.zone.type.L2ResidenceTeleportZone;
  56. import com.l2jserver.gameserver.model.zone.type.L2SiegeZone;
  57. import com.l2jserver.gameserver.network.serverpackets.PlaySound;
  58. import com.l2jserver.gameserver.network.serverpackets.PledgeShowInfoUpdate;
  59. public class Castle
  60. {
  61. protected static final Logger _log = Logger.getLogger(Castle.class.getName());
  62. // =========================================================
  63. // Data Field
  64. private List<CropProcure> _procure = new ArrayList<CropProcure>();
  65. private List<SeedProduction> _production = new ArrayList<SeedProduction>();
  66. private List<CropProcure> _procureNext = new ArrayList<CropProcure>();
  67. private List<SeedProduction> _productionNext = new ArrayList<SeedProduction>();
  68. private boolean _isNextPeriodApproved = false;
  69. private static final String CASTLE_MANOR_DELETE_PRODUCTION = "DELETE FROM castle_manor_production WHERE castle_id=?;";
  70. private static final String CASTLE_MANOR_DELETE_PRODUCTION_PERIOD = "DELETE FROM castle_manor_production WHERE castle_id=? AND period=?;";
  71. private static final String CASTLE_MANOR_DELETE_PROCURE = "DELETE FROM castle_manor_procure WHERE castle_id=?;";
  72. private static final String CASTLE_MANOR_DELETE_PROCURE_PERIOD = "DELETE FROM castle_manor_procure WHERE castle_id=? AND period=?;";
  73. private static final String CASTLE_UPDATE_CROP = "UPDATE castle_manor_procure SET can_buy=? WHERE crop_id=? AND castle_id=? AND period=?";
  74. private static final String CASTLE_UPDATE_SEED = "UPDATE castle_manor_production SET can_produce=? WHERE seed_id=? AND castle_id=? AND period=?";
  75. // =========================================================
  76. // Data Field
  77. private int _castleId = 0;
  78. private List<L2DoorInstance> _doors = new FastList<L2DoorInstance>();
  79. private List<String> _doorDefault = new FastList<String>();
  80. private String _name = "";
  81. private int _ownerId = 0;
  82. private Siege _siege = null;
  83. private Calendar _siegeDate;
  84. private boolean _isTimeRegistrationOver = true; // true if Castle Lords set the time, or 24h is elapsed after the siege
  85. private Calendar _siegeTimeRegistrationEndDate; // last siege end date + 1 day
  86. private int _taxPercent = 0;
  87. private double _taxRate = 0;
  88. private long _treasury = 0;
  89. private boolean _showNpcCrest = false;
  90. private L2SiegeZone _zone = null;
  91. private L2CastleZone _castleZone = null;
  92. private L2ResidenceTeleportZone _teleZone;
  93. private L2Clan _formerOwner = null;
  94. private List<L2ArtefactInstance> _artefacts = new ArrayList<L2ArtefactInstance>(1);
  95. private TIntIntHashMap _engrave = new TIntIntHashMap(1);
  96. private Map<Integer, CastleFunction> _function;
  97. private FastList<L2Skill> _residentialSkills = new FastList<L2Skill>();
  98. private int _bloodAlliance = 0;
  99. /** Castle Functions */
  100. public static final int FUNC_TELEPORT = 1;
  101. public static final int FUNC_RESTORE_HP = 2;
  102. public static final int FUNC_RESTORE_MP = 3;
  103. public static final int FUNC_RESTORE_EXP = 4;
  104. public static final int FUNC_SUPPORT = 5;
  105. public class CastleFunction
  106. {
  107. private int _type;
  108. private int _lvl;
  109. protected int _fee;
  110. protected int _tempFee;
  111. private long _rate;
  112. private long _endDate;
  113. protected boolean _inDebt;
  114. public boolean _cwh;
  115. public CastleFunction(int type, int lvl, int lease, int tempLease, long rate, long time, boolean cwh)
  116. {
  117. _type = type;
  118. _lvl = lvl;
  119. _fee = lease;
  120. _tempFee = tempLease;
  121. _rate = rate;
  122. _endDate = time;
  123. initializeTask(cwh);
  124. }
  125. public int getType()
  126. {
  127. return _type;
  128. }
  129. public int getLvl()
  130. {
  131. return _lvl;
  132. }
  133. public int getLease()
  134. {
  135. return _fee;
  136. }
  137. public long getRate()
  138. {
  139. return _rate;
  140. }
  141. public long getEndTime()
  142. {
  143. return _endDate;
  144. }
  145. public void setLvl(int lvl)
  146. {
  147. _lvl = lvl;
  148. }
  149. public void setLease(int lease)
  150. {
  151. _fee = lease;
  152. }
  153. public void setEndTime(long time)
  154. {
  155. _endDate = time;
  156. }
  157. private void initializeTask(boolean cwh)
  158. {
  159. if (getOwnerId() <= 0)
  160. return;
  161. long currentTime = System.currentTimeMillis();
  162. if (_endDate > currentTime)
  163. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
  164. else
  165. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
  166. }
  167. private class FunctionTask implements Runnable
  168. {
  169. public FunctionTask(boolean cwh)
  170. {
  171. _cwh = cwh;
  172. }
  173. public void run()
  174. {
  175. try
  176. {
  177. if (getOwnerId() <= 0)
  178. return;
  179. if (ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().getAdena() >= _fee || !_cwh)
  180. {
  181. int fee = _fee;
  182. if (getEndTime() == -1)
  183. fee = _tempFee;
  184. setEndTime(System.currentTimeMillis() + getRate());
  185. dbSave();
  186. if (_cwh)
  187. {
  188. ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CS_function_fee", 57, fee, null, null);
  189. if (Config.DEBUG)
  190. _log.warning("deducted " + fee + " adena from " + getName() + " owner's cwh for function id : " + getType());
  191. }
  192. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
  193. }
  194. else
  195. removeFunction(getType());
  196. }
  197. catch (Exception e)
  198. {
  199. _log.log(Level.SEVERE, "", e);
  200. }
  201. }
  202. }
  203. public void dbSave()
  204. {
  205. Connection con = null;
  206. try
  207. {
  208. PreparedStatement statement;
  209. con = L2DatabaseFactory.getInstance().getConnection();
  210. statement = con.prepareStatement("REPLACE INTO castle_functions (castle_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
  211. statement.setInt(1, getCastleId());
  212. statement.setInt(2, getType());
  213. statement.setInt(3, getLvl());
  214. statement.setInt(4, getLease());
  215. statement.setLong(5, getRate());
  216. statement.setLong(6, getEndTime());
  217. statement.execute();
  218. statement.close();
  219. }
  220. catch (Exception e)
  221. {
  222. _log.log(Level.SEVERE, "Exception: Castle.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): "
  223. + e.getMessage(), e);
  224. }
  225. finally
  226. {
  227. L2DatabaseFactory.close(con);
  228. }
  229. }
  230. }
  231. // =========================================================
  232. // Constructor
  233. public Castle(int castleId)
  234. {
  235. _castleId = castleId;
  236. /*if (_castleId == 7 || castleId == 9) // Goddard and Schuttgart
  237. _nbArtifact = 2;*/
  238. load();
  239. loadDoor();
  240. _function = new FastMap<Integer, CastleFunction>();
  241. final FastList<L2SkillLearn> residentialSkills = SkillTreesData.getInstance().getAvailableResidentialSkills(castleId);
  242. for (L2SkillLearn s : residentialSkills)
  243. {
  244. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  245. if (sk != null)
  246. {
  247. _residentialSkills.add(sk);
  248. }
  249. else
  250. {
  251. _log.warning("Castle Id: " + castleId + " has a null residential skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  252. }
  253. }
  254. if (getOwnerId() != 0)
  255. {
  256. loadFunctions();
  257. }
  258. }
  259. // =========================================================
  260. // Method - Public
  261. /** Return function with id */
  262. public CastleFunction getFunction(int type)
  263. {
  264. if (_function.get(type) != null)
  265. return _function.get(type);
  266. return null;
  267. }
  268. public synchronized void engrave(L2Clan clan, L2Object target)
  269. {
  270. if (!_artefacts.contains(target))
  271. return;
  272. _engrave.put(target.getObjectId(), clan.getClanId());
  273. if (_engrave.size() == _artefacts.size())
  274. {
  275. for (L2ArtefactInstance art : _artefacts)
  276. {
  277. if (_engrave.get(art.getObjectId()) != clan.getClanId())
  278. return;
  279. }
  280. _engrave.clear();
  281. setOwner(clan);
  282. }
  283. }
  284. // This method add to the treasury
  285. /** Add amount to castle instance's treasury (warehouse). */
  286. public void addToTreasury(long amount)
  287. {
  288. // check if owned
  289. if (getOwnerId() <= 0)
  290. {
  291. return;
  292. }
  293. if (_name.equalsIgnoreCase("Schuttgart") || _name.equalsIgnoreCase("Goddard"))
  294. {
  295. Castle rune = CastleManager.getInstance().getCastle("rune");
  296. if (rune != null)
  297. {
  298. long runeTax = (long) (amount * rune.getTaxRate());
  299. if (rune.getOwnerId() > 0)
  300. rune.addToTreasury(runeTax);
  301. amount -= runeTax;
  302. }
  303. }
  304. if (!_name.equalsIgnoreCase("aden") && !_name.equalsIgnoreCase("Rune") && !_name.equalsIgnoreCase("Schuttgart") && !_name.equalsIgnoreCase("Goddard")) // If current castle instance is not Aden, Rune, Goddard or Schuttgart.
  305. {
  306. Castle aden = CastleManager.getInstance().getCastle("aden");
  307. if (aden != null)
  308. {
  309. long adenTax = (long) (amount * aden.getTaxRate()); // Find out what Aden gets from the current castle instance's income
  310. if (aden.getOwnerId() > 0)
  311. aden.addToTreasury(adenTax); // Only bother to really add the tax to the treasury if not npc owned
  312. amount -= adenTax; // Subtract Aden's income from current castle instance's income
  313. }
  314. }
  315. addToTreasuryNoTax(amount);
  316. }
  317. /** Add amount to castle instance's treasury (warehouse), no tax paying. */
  318. public boolean addToTreasuryNoTax(long amount)
  319. {
  320. if (getOwnerId() <= 0)
  321. return false;
  322. if (amount < 0)
  323. {
  324. amount *= -1;
  325. if (_treasury < amount)
  326. return false;
  327. _treasury -= amount;
  328. }
  329. else
  330. {
  331. if (_treasury + amount > PcInventory.MAX_ADENA) // TODO is this valid after gracia final?
  332. _treasury = PcInventory.MAX_ADENA;
  333. else
  334. _treasury += amount;
  335. }
  336. Connection con = null;
  337. try
  338. {
  339. con = L2DatabaseFactory.getInstance().getConnection();
  340. PreparedStatement statement = con.prepareStatement("UPDATE castle SET treasury = ? WHERE id = ?");
  341. statement.setLong(1, getTreasury());
  342. statement.setInt(2, getCastleId());
  343. statement.execute();
  344. statement.close();
  345. }
  346. catch (Exception e)
  347. {
  348. }
  349. finally
  350. {
  351. L2DatabaseFactory.close(con);
  352. }
  353. return true;
  354. }
  355. /**
  356. * Move non clan members off castle area and to nearest town.<BR><BR>
  357. */
  358. public void banishForeigners()
  359. {
  360. getCastleZone().banishForeigners(getOwnerId());
  361. }
  362. /**
  363. * Return true if object is inside the zone
  364. */
  365. public boolean checkIfInZone(int x, int y, int z)
  366. {
  367. return getZone().isInsideZone(x, y, z);
  368. }
  369. public L2SiegeZone getZone()
  370. {
  371. if (_zone == null)
  372. {
  373. for (L2SiegeZone zone : ZoneManager.getInstance().getAllZones(L2SiegeZone.class))
  374. {
  375. if (zone.getSiegeObjectId() == getCastleId())
  376. {
  377. _zone = zone;
  378. break;
  379. }
  380. }
  381. }
  382. return _zone;
  383. }
  384. public L2CastleZone getCastleZone()
  385. {
  386. if (_castleZone == null)
  387. {
  388. for (L2CastleZone zone : ZoneManager.getInstance().getAllZones(L2CastleZone.class))
  389. {
  390. if (zone.getCastleId() == getCastleId())
  391. {
  392. _castleZone = zone;
  393. break;
  394. }
  395. }
  396. }
  397. return _castleZone;
  398. }
  399. public L2ResidenceTeleportZone getTeleZone()
  400. {
  401. if (_teleZone == null)
  402. {
  403. for (L2ResidenceTeleportZone zone : ZoneManager.getInstance().getAllZones(L2ResidenceTeleportZone.class))
  404. {
  405. if (zone.getResidenceId() == getCastleId())
  406. {
  407. _teleZone = zone;
  408. break;
  409. }
  410. }
  411. }
  412. return _teleZone;
  413. }
  414. public void oustAllPlayers()
  415. {
  416. getTeleZone().oustAllPlayers();
  417. }
  418. /**
  419. * Get the objects distance to this castle
  420. * @param obj
  421. * @return
  422. */
  423. public double getDistance(L2Object obj)
  424. {
  425. return getZone().getDistanceToZone(obj);
  426. }
  427. public void closeDoor(L2PcInstance activeChar, int doorId)
  428. {
  429. openCloseDoor(activeChar, doorId, false);
  430. }
  431. public void openDoor(L2PcInstance activeChar, int doorId)
  432. {
  433. openCloseDoor(activeChar, doorId, true);
  434. }
  435. public void openCloseDoor(L2PcInstance activeChar, int doorId, boolean open)
  436. {
  437. if (activeChar.getClanId() != getOwnerId())
  438. return;
  439. L2DoorInstance door = getDoor(doorId);
  440. if (door != null)
  441. {
  442. if (open)
  443. door.openMe();
  444. else
  445. door.closeMe();
  446. }
  447. }
  448. // This method is used to begin removing all castle upgrades
  449. public void removeUpgrade()
  450. {
  451. removeDoorUpgrade();
  452. for (Map.Entry<Integer, CastleFunction> fc : _function.entrySet())
  453. removeFunction(fc.getKey());
  454. _function.clear();
  455. }
  456. // This method updates the castle tax rate
  457. public void setOwner(L2Clan clan)
  458. {
  459. // Remove old owner
  460. if (getOwnerId() > 0 && (clan == null || clan.getClanId() != getOwnerId()))
  461. {
  462. L2Clan oldOwner = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  463. if (oldOwner != null)
  464. {
  465. if (_formerOwner == null)
  466. {
  467. _formerOwner = oldOwner;
  468. if (Config.REMOVE_CASTLE_CIRCLETS)
  469. {
  470. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  471. }
  472. }
  473. try
  474. {
  475. L2PcInstance oldleader = oldOwner.getLeader().getPlayerInstance();
  476. if (oldleader != null)
  477. {
  478. if (oldleader.getMountType() == 2)
  479. oldleader.dismount();
  480. }
  481. }
  482. catch (Exception e)
  483. {
  484. _log.log(Level.WARNING, "Exception in setOwner: " + e.getMessage(), e);
  485. }
  486. oldOwner.setHasCastle(0); // Unset has castle flag for old owner
  487. for (L2PcInstance member : oldOwner.getOnlineMembers(0))
  488. {
  489. removeResidentialSkills(member);
  490. member.sendSkillList();
  491. }
  492. }
  493. }
  494. updateOwnerInDB(clan); // Update in database
  495. setShowNpcCrest(false);
  496. // if clan have fortress, remove it
  497. if (clan.getHasFort() > 0)
  498. FortManager.getInstance().getFortByOwner(clan).removeOwner(true);
  499. if (getSiege().getIsInProgress()) // If siege in progress
  500. getSiege().midVictory(); // Mid victory phase of siege
  501. TerritoryWarManager.getInstance().getTerritory(_castleId).setOwnerClan(clan);
  502. for (L2PcInstance member : clan.getOnlineMembers(0))
  503. {
  504. giveResidentialSkills(member);
  505. member.sendSkillList();
  506. }
  507. }
  508. public void removeOwner(L2Clan clan)
  509. {
  510. if (clan != null)
  511. {
  512. _formerOwner = clan;
  513. if (Config.REMOVE_CASTLE_CIRCLETS)
  514. {
  515. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  516. }
  517. for (L2PcInstance member : clan.getOnlineMembers(0))
  518. {
  519. removeResidentialSkills(member);
  520. member.sendSkillList();
  521. }
  522. clan.setHasCastle(0);
  523. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  524. }
  525. updateOwnerInDB(null);
  526. if (getSiege().getIsInProgress())
  527. getSiege().midVictory();
  528. for (Map.Entry<Integer, CastleFunction> fc : _function.entrySet())
  529. removeFunction(fc.getKey());
  530. _function.clear();
  531. }
  532. // This method updates the castle tax rate
  533. public void setTaxPercent(L2PcInstance activeChar, int taxPercent)
  534. {
  535. int maxTax;
  536. switch (SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE))
  537. {
  538. case SevenSigns.CABAL_DAWN:
  539. maxTax = 25;
  540. break;
  541. case SevenSigns.CABAL_DUSK:
  542. maxTax = 5;
  543. break;
  544. default: // no owner
  545. maxTax = 15;
  546. }
  547. if (taxPercent < 0 || taxPercent > maxTax)
  548. {
  549. activeChar.sendMessage("Tax value must be between 0 and " + maxTax + ".");
  550. return;
  551. }
  552. setTaxPercent(taxPercent);
  553. activeChar.sendMessage(getName() + " castle tax changed to " + taxPercent + "%.");
  554. }
  555. public void setTaxPercent(int taxPercent)
  556. {
  557. _taxPercent = taxPercent;
  558. _taxRate = _taxPercent / 100.0;
  559. Connection con = null;
  560. try
  561. {
  562. con = L2DatabaseFactory.getInstance().getConnection();
  563. PreparedStatement statement = con.prepareStatement("Update castle set taxPercent = ? where id = ?");
  564. statement.setInt(1, taxPercent);
  565. statement.setInt(2, getCastleId());
  566. statement.execute();
  567. statement.close();
  568. }
  569. catch (Exception e)
  570. {
  571. }
  572. finally
  573. {
  574. L2DatabaseFactory.close(con);
  575. }
  576. }
  577. /**
  578. * Respawn all doors on castle grounds<BR><BR>
  579. */
  580. public void spawnDoor()
  581. {
  582. spawnDoor(false);
  583. }
  584. /**
  585. * Respawn all doors on castle grounds<BR><BR>
  586. */
  587. public void spawnDoor(boolean isDoorWeak)
  588. {
  589. for (int i = 0; i < getDoors().size(); i++)
  590. {
  591. L2DoorInstance door = getDoors().get(i);
  592. if (door.getCurrentHp() <= 0)
  593. {
  594. door.decayMe(); // Kill current if not killed already
  595. door = DoorTable.parseList(_doorDefault.get(i), false);
  596. DoorTable.getInstance().putDoor(door); //Readd the new door to the DoorTable By Erb
  597. if (isDoorWeak)
  598. door.setCurrentHp(door.getMaxHp() / 2);
  599. door.spawnMe(door.getX(), door.getY(), door.getZ());
  600. getDoors().set(i, door);
  601. }
  602. else if (door.getOpen())
  603. door.closeMe();
  604. }
  605. loadDoorUpgrade(); // Check for any upgrade the doors may have
  606. }
  607. // This method upgrade door
  608. public void upgradeDoor(int doorId, int hp, int pDef, int mDef)
  609. {
  610. L2DoorInstance door = getDoor(doorId);
  611. if (door == null)
  612. return;
  613. door.setCurrentHp(door.getMaxHp() + hp);
  614. saveDoorUpgrade(doorId, hp, pDef, mDef);
  615. }
  616. // =========================================================
  617. // Method - Private
  618. // This method loads castle
  619. private void load()
  620. {
  621. Connection con = null;
  622. try
  623. {
  624. PreparedStatement statement;
  625. ResultSet rs;
  626. con = L2DatabaseFactory.getInstance().getConnection();
  627. statement = con.prepareStatement("Select * from castle where id = ?");
  628. statement.setInt(1, getCastleId());
  629. rs = statement.executeQuery();
  630. while (rs.next())
  631. {
  632. _name = rs.getString("name");
  633. //_OwnerId = rs.getInt("ownerId");
  634. _siegeDate = Calendar.getInstance();
  635. _siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
  636. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  637. _siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
  638. _isTimeRegistrationOver = rs.getBoolean("regTimeOver");
  639. _taxPercent = rs.getInt("taxPercent");
  640. _treasury = rs.getLong("treasury");
  641. _showNpcCrest = rs.getBoolean("showNpcCrest");
  642. _bloodAlliance = rs.getInt("bloodAlliance");
  643. }
  644. rs.close();
  645. statement.close();
  646. _taxRate = _taxPercent / 100.0;
  647. statement = con.prepareStatement("Select clan_id from clan_data where hasCastle = ?");
  648. statement.setInt(1, getCastleId());
  649. rs = statement.executeQuery();
  650. while (rs.next())
  651. {
  652. _ownerId = rs.getInt("clan_id");
  653. }
  654. if (getOwnerId() > 0)
  655. {
  656. L2Clan clan = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  657. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  658. }
  659. rs.close();
  660. statement.close();
  661. }
  662. catch (Exception e)
  663. {
  664. _log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
  665. }
  666. finally
  667. {
  668. L2DatabaseFactory.close(con);
  669. }
  670. }
  671. /** Load All Functions */
  672. private void loadFunctions()
  673. {
  674. Connection con = null;
  675. try
  676. {
  677. PreparedStatement statement;
  678. ResultSet rs;
  679. con = L2DatabaseFactory.getInstance().getConnection();
  680. statement = con.prepareStatement("Select * from castle_functions where castle_id = ?");
  681. statement.setInt(1, getCastleId());
  682. rs = statement.executeQuery();
  683. while (rs.next())
  684. {
  685. _function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
  686. }
  687. rs.close();
  688. statement.close();
  689. }
  690. catch (Exception e)
  691. {
  692. _log.log(Level.SEVERE, "Exception: Castle.loadFunctions(): " + e.getMessage(), e);
  693. }
  694. finally
  695. {
  696. L2DatabaseFactory.close(con);
  697. }
  698. }
  699. /** Remove function In List and in DB */
  700. public void removeFunction(int functionType)
  701. {
  702. _function.remove(functionType);
  703. Connection con = null;
  704. try
  705. {
  706. PreparedStatement statement;
  707. con = L2DatabaseFactory.getInstance().getConnection();
  708. statement = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?");
  709. statement.setInt(1, getCastleId());
  710. statement.setInt(2, functionType);
  711. statement.execute();
  712. statement.close();
  713. }
  714. catch (Exception e)
  715. {
  716. _log.log(Level.SEVERE, "Exception: Castle.removeFunctions(int functionType): " + e.getMessage(), e);
  717. }
  718. finally
  719. {
  720. L2DatabaseFactory.close(con);
  721. }
  722. }
  723. public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
  724. {
  725. if (player == null)
  726. return false;
  727. if (Config.DEBUG)
  728. _log.warning("Called Castle.updateFunctions(int type, int lvl, int lease, long rate, boolean addNew) Owner : " + getOwnerId());
  729. if (lease > 0)
  730. if (!player.destroyItemByItemId("Consume", 57, lease, null, true))
  731. return false;
  732. if (addNew)
  733. {
  734. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, 0, false));
  735. }
  736. else
  737. {
  738. if (lvl == 0 && lease == 0)
  739. removeFunction(type);
  740. else
  741. {
  742. int diffLease = lease - _function.get(type).getLease();
  743. if (Config.DEBUG)
  744. _log.warning("Called Castle.updateFunctions diffLease : " + diffLease);
  745. if (diffLease > 0)
  746. {
  747. _function.remove(type);
  748. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, -1, false));
  749. }
  750. else
  751. {
  752. _function.get(type).setLease(lease);
  753. _function.get(type).setLvl(lvl);
  754. _function.get(type).dbSave();
  755. }
  756. }
  757. }
  758. return true;
  759. }
  760. public void activateInstance()
  761. {
  762. for (final L2DoorInstance door : _doors)
  763. {
  764. door.spawnMe(door.getX(), door.getY(), door.getZ());
  765. }
  766. }
  767. // This method loads castle door data from database
  768. private void loadDoor()
  769. {
  770. Connection con = null;
  771. try
  772. {
  773. con = L2DatabaseFactory.getInstance().getConnection();
  774. PreparedStatement statement = con.prepareStatement("Select * from castle_door where castleId = ?");
  775. statement.setInt(1, getCastleId());
  776. ResultSet rs = statement.executeQuery();
  777. while (rs.next())
  778. {
  779. // Create list of the door default for use when respawning dead doors
  780. _doorDefault.add(rs.getString("name") + ";" + rs.getInt("id") + ";" + rs.getInt("x") + ";" + rs.getInt("y") + ";"
  781. + rs.getInt("z") + ";" + rs.getInt("range_xmin") + ";" + rs.getInt("range_ymin") + ";" + rs.getInt("range_zmin")
  782. + ";" + rs.getInt("range_xmax") + ";" + rs.getInt("range_ymax") + ";" + rs.getInt("range_zmax") + ";"
  783. + rs.getInt("hp") + ";" + rs.getInt("pDef") + ";" + rs.getInt("mDef") + ";0");
  784. L2DoorInstance door = DoorTable.parseList(_doorDefault.get(_doorDefault.size() - 1), false);
  785. door.setIsWall(rs.getBoolean("isWall"));
  786. _doors.add(door);
  787. DoorTable.getInstance().putDoor(door);
  788. }
  789. rs.close();
  790. statement.close();
  791. }
  792. catch (Exception e)
  793. {
  794. _log.log(Level.WARNING, "Exception: loadCastleDoor(): " + e.getMessage(),e );
  795. }
  796. finally
  797. {
  798. L2DatabaseFactory.close(con);
  799. }
  800. }
  801. // This method loads castle door upgrade data from database
  802. private void loadDoorUpgrade()
  803. {
  804. Connection con = null;
  805. try
  806. {
  807. con = L2DatabaseFactory.getInstance().getConnection();
  808. PreparedStatement statement = con.prepareStatement("Select * from castle_doorupgrade where doorId in (Select Id from castle_door where castleId = ?)");
  809. statement.setInt(1, getCastleId());
  810. ResultSet rs = statement.executeQuery();
  811. while (rs.next())
  812. {
  813. upgradeDoor(rs.getInt("id"), rs.getInt("hp"), rs.getInt("pDef"), rs.getInt("mDef"));
  814. }
  815. rs.close();
  816. statement.close();
  817. }
  818. catch (Exception e)
  819. {
  820. _log.log(Level.WARNING, "Exception: loadCastleDoorUpgrade(): " + e.getMessage(), e);
  821. }
  822. finally
  823. {
  824. L2DatabaseFactory.close(con);
  825. }
  826. }
  827. private void removeDoorUpgrade()
  828. {
  829. Connection con = null;
  830. try
  831. {
  832. con = L2DatabaseFactory.getInstance().getConnection();
  833. PreparedStatement statement = con.prepareStatement("delete from castle_doorupgrade where doorId in (select id from castle_door where castleId=?)");
  834. statement.setInt(1, getCastleId());
  835. statement.execute();
  836. statement.close();
  837. }
  838. catch (Exception e)
  839. {
  840. _log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
  841. }
  842. finally
  843. {
  844. L2DatabaseFactory.close(con);
  845. }
  846. }
  847. private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
  848. {
  849. Connection con = null;
  850. try
  851. {
  852. con = L2DatabaseFactory.getInstance().getConnection();
  853. PreparedStatement statement = con.prepareStatement("INSERT INTO castle_doorupgrade (doorId, hp, pDef, mDef) values (?,?,?,?)");
  854. statement.setInt(1, doorId);
  855. statement.setInt(2, hp);
  856. statement.setInt(3, pDef);
  857. statement.setInt(4, mDef);
  858. statement.execute();
  859. statement.close();
  860. }
  861. catch (Exception e)
  862. {
  863. _log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
  864. }
  865. finally
  866. {
  867. L2DatabaseFactory.close(con);
  868. }
  869. }
  870. private void updateOwnerInDB(L2Clan clan)
  871. {
  872. if (clan != null)
  873. _ownerId = clan.getClanId(); // Update owner id property
  874. else
  875. {
  876. _ownerId = 0; // Remove owner
  877. resetManor();
  878. }
  879. Connection con = null;
  880. try
  881. {
  882. con = L2DatabaseFactory.getInstance().getConnection();
  883. PreparedStatement statement;
  884. // ============================================================================
  885. // NEED TO REMOVE HAS CASTLE FLAG FROM CLAN_DATA
  886. // SHOULD BE CHECKED FROM CASTLE TABLE
  887. statement = con.prepareStatement("UPDATE clan_data SET hasCastle=0 WHERE hasCastle=?");
  888. statement.setInt(1, getCastleId());
  889. statement.execute();
  890. statement.close();
  891. statement = con.prepareStatement("UPDATE clan_data SET hasCastle=? WHERE clan_id=?");
  892. statement.setInt(1, getCastleId());
  893. statement.setInt(2, getOwnerId());
  894. statement.execute();
  895. statement.close();
  896. // ============================================================================
  897. // Announce to clan memebers
  898. if (clan != null)
  899. {
  900. clan.setHasCastle(getCastleId()); // Set has castle flag for new owner
  901. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  902. clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
  903. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  904. }
  905. }
  906. catch (Exception e)
  907. {
  908. _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
  909. }
  910. finally
  911. {
  912. L2DatabaseFactory.close(con);
  913. }
  914. }
  915. // =========================================================
  916. // Property
  917. public final int getCastleId()
  918. {
  919. return _castleId;
  920. }
  921. public final L2DoorInstance getDoor(int doorId)
  922. {
  923. if (doorId <= 0)
  924. return null;
  925. for (L2DoorInstance door : getDoors())
  926. {
  927. if (door.getDoorId() == doorId)
  928. return door;
  929. }
  930. return null;
  931. }
  932. public final List<L2DoorInstance> getDoors()
  933. {
  934. return _doors;
  935. }
  936. public final String getName()
  937. {
  938. return _name;
  939. }
  940. public final int getOwnerId()
  941. {
  942. return _ownerId;
  943. }
  944. public final Siege getSiege()
  945. {
  946. if (_siege == null)
  947. _siege = new Siege(new Castle[] { this });
  948. return _siege;
  949. }
  950. public final Calendar getSiegeDate()
  951. {
  952. return _siegeDate;
  953. }
  954. public boolean getIsTimeRegistrationOver()
  955. {
  956. return _isTimeRegistrationOver;
  957. }
  958. public void setIsTimeRegistrationOver(boolean val)
  959. {
  960. _isTimeRegistrationOver = val;
  961. }
  962. public Calendar getTimeRegistrationOverDate()
  963. {
  964. if (_siegeTimeRegistrationEndDate == null)
  965. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  966. return _siegeTimeRegistrationEndDate;
  967. }
  968. public final int getTaxPercent()
  969. {
  970. return _taxPercent;
  971. }
  972. public final double getTaxRate()
  973. {
  974. return _taxRate;
  975. }
  976. public final long getTreasury()
  977. {
  978. return _treasury;
  979. }
  980. public final boolean getShowNpcCrest()
  981. {
  982. return _showNpcCrest;
  983. }
  984. public final void setShowNpcCrest(boolean showNpcCrest)
  985. {
  986. if (_showNpcCrest != showNpcCrest)
  987. {
  988. _showNpcCrest = showNpcCrest;
  989. updateShowNpcCrest();
  990. }
  991. }
  992. public List<SeedProduction> getSeedProduction(int period)
  993. {
  994. return (period == CastleManorManager.PERIOD_CURRENT ? _production : _productionNext);
  995. }
  996. public List<CropProcure> getCropProcure(int period)
  997. {
  998. return (period == CastleManorManager.PERIOD_CURRENT ? _procure : _procureNext);
  999. }
  1000. public void setSeedProduction(List<SeedProduction> seed, int period)
  1001. {
  1002. if (period == CastleManorManager.PERIOD_CURRENT)
  1003. _production = seed;
  1004. else
  1005. _productionNext = seed;
  1006. }
  1007. public void setCropProcure(List<CropProcure> crop, int period)
  1008. {
  1009. if (period == CastleManorManager.PERIOD_CURRENT)
  1010. _procure = crop;
  1011. else
  1012. _procureNext = crop;
  1013. }
  1014. public SeedProduction getSeed(int seedId, int period)
  1015. {
  1016. for (SeedProduction seed : getSeedProduction(period))
  1017. {
  1018. if (seed.getId() == seedId)
  1019. {
  1020. return seed;
  1021. }
  1022. }
  1023. return null;
  1024. }
  1025. public CropProcure getCrop(int cropId, int period)
  1026. {
  1027. for (CropProcure crop : getCropProcure(period))
  1028. {
  1029. if (crop.getId() == cropId)
  1030. {
  1031. return crop;
  1032. }
  1033. }
  1034. return null;
  1035. }
  1036. public long getManorCost(int period)
  1037. {
  1038. List<CropProcure> procure;
  1039. List<SeedProduction> production;
  1040. if (period == CastleManorManager.PERIOD_CURRENT)
  1041. {
  1042. procure = _procure;
  1043. production = _production;
  1044. }
  1045. else
  1046. {
  1047. procure = _procureNext;
  1048. production = _productionNext;
  1049. }
  1050. long total = 0;
  1051. if (production != null)
  1052. {
  1053. for (SeedProduction seed : production)
  1054. {
  1055. total += L2Manor.getInstance().getSeedBuyPrice(seed.getId()) * seed.getStartProduce();
  1056. }
  1057. }
  1058. if (procure != null)
  1059. {
  1060. for (CropProcure crop : procure)
  1061. {
  1062. total += crop.getPrice() * crop.getStartAmount();
  1063. }
  1064. }
  1065. return total;
  1066. }
  1067. //save manor production data
  1068. public void saveSeedData()
  1069. {
  1070. Connection con = null;
  1071. PreparedStatement statement;
  1072. try
  1073. {
  1074. con = L2DatabaseFactory.getInstance().getConnection();
  1075. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION);
  1076. statement.setInt(1, getCastleId());
  1077. statement.execute();
  1078. statement.close();
  1079. if (_production != null)
  1080. {
  1081. int count = 0;
  1082. StringBuilder query = new StringBuilder();
  1083. query.append("INSERT INTO castle_manor_production VALUES ");
  1084. String values[] = new String[_production.size()];
  1085. for (SeedProduction s : _production)
  1086. {
  1087. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + ","
  1088. + s.getPrice() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1089. }
  1090. if (values.length > 0)
  1091. {
  1092. query.append(values[0]);
  1093. for (int i = 1; i < values.length; i++)
  1094. {
  1095. query.append(",");
  1096. query.append(values[i]);
  1097. }
  1098. statement = con.prepareStatement(query.toString());
  1099. statement.execute();
  1100. statement.close();
  1101. }
  1102. }
  1103. if (_productionNext != null)
  1104. {
  1105. int count = 0;
  1106. String query = "INSERT INTO castle_manor_production VALUES ";
  1107. String values[] = new String[_productionNext.size()];
  1108. for (SeedProduction s : _productionNext)
  1109. {
  1110. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + ","
  1111. + s.getPrice() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1112. }
  1113. if (values.length > 0)
  1114. {
  1115. query += values[0];
  1116. for (int i = 1; i < values.length; i++)
  1117. {
  1118. query += "," + values[i];
  1119. }
  1120. statement = con.prepareStatement(query);
  1121. statement.execute();
  1122. statement.close();
  1123. }
  1124. }
  1125. }
  1126. catch (Exception e)
  1127. {
  1128. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1129. }
  1130. finally
  1131. {
  1132. L2DatabaseFactory.close(con);
  1133. }
  1134. }
  1135. //save manor production data for specified period
  1136. public void saveSeedData(int period)
  1137. {
  1138. Connection con = null;
  1139. PreparedStatement statement;
  1140. try
  1141. {
  1142. con = L2DatabaseFactory.getInstance().getConnection();
  1143. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD);
  1144. statement.setInt(1, getCastleId());
  1145. statement.setInt(2, period);
  1146. statement.execute();
  1147. statement.close();
  1148. List<SeedProduction> prod = null;
  1149. prod = getSeedProduction(period);
  1150. if (prod != null)
  1151. {
  1152. int count = 0;
  1153. StringBuilder query = new StringBuilder();
  1154. query.append("INSERT INTO castle_manor_production VALUES ");
  1155. String values[] = new String[prod.size()];
  1156. for (SeedProduction s : prod)
  1157. {
  1158. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + ","
  1159. + s.getPrice() + "," + period + ")";
  1160. }
  1161. if (values.length > 0)
  1162. {
  1163. query.append(values[0]);
  1164. for (int i = 1; i < values.length; i++)
  1165. {
  1166. query.append(",")
  1167. .append(values[i]);
  1168. }
  1169. statement = con.prepareStatement(query.toString());
  1170. statement.execute();
  1171. statement.close();
  1172. }
  1173. }
  1174. }
  1175. catch (Exception e)
  1176. {
  1177. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1178. }
  1179. finally
  1180. {
  1181. L2DatabaseFactory.close(con);
  1182. }
  1183. }
  1184. //save crop procure data
  1185. public void saveCropData()
  1186. {
  1187. Connection con = null;
  1188. PreparedStatement statement;
  1189. try
  1190. {
  1191. con = L2DatabaseFactory.getInstance().getConnection();
  1192. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE);
  1193. statement.setInt(1, getCastleId());
  1194. statement.execute();
  1195. statement.close();
  1196. if (_procure != null && _procure.size() > 0)
  1197. {
  1198. int count = 0;
  1199. StringBuilder query = new StringBuilder();
  1200. query.append("INSERT INTO castle_manor_procure VALUES ");
  1201. String values[] = new String[_procure.size()];
  1202. for (CropProcure cp : _procure)
  1203. {
  1204. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + ","
  1205. + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1206. }
  1207. if (values.length > 0)
  1208. {
  1209. query.append(values[0]);
  1210. for (int i = 1; i < values.length; i++)
  1211. {
  1212. query.append(",");
  1213. query.append(values[i]);
  1214. }
  1215. statement = con.prepareStatement(query.toString());
  1216. statement.execute();
  1217. statement.close();
  1218. }
  1219. }
  1220. if (_procureNext != null && _procureNext.size() > 0)
  1221. {
  1222. int count = 0;
  1223. String query = "INSERT INTO castle_manor_procure VALUES ";
  1224. String values[] = new String[_procureNext.size()];
  1225. for (CropProcure cp : _procureNext)
  1226. {
  1227. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + ","
  1228. + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1229. }
  1230. if (values.length > 0)
  1231. {
  1232. query += values[0];
  1233. for (int i = 1; i < values.length; i++)
  1234. {
  1235. query += "," + values[i];
  1236. }
  1237. statement = con.prepareStatement(query);
  1238. statement.execute();
  1239. statement.close();
  1240. }
  1241. }
  1242. }
  1243. catch (Exception e)
  1244. {
  1245. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1246. }
  1247. finally
  1248. {
  1249. L2DatabaseFactory.close(con);
  1250. }
  1251. }
  1252. // save crop procure data for specified period
  1253. public void saveCropData(int period)
  1254. {
  1255. Connection con = null;
  1256. PreparedStatement statement;
  1257. try
  1258. {
  1259. con = L2DatabaseFactory.getInstance().getConnection();
  1260. statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD);
  1261. statement.setInt(1, getCastleId());
  1262. statement.setInt(2, period);
  1263. statement.execute();
  1264. statement.close();
  1265. List<CropProcure> proc = null;
  1266. proc = getCropProcure(period);
  1267. if (proc != null && proc.size() > 0)
  1268. {
  1269. int count = 0;
  1270. StringBuilder query = new StringBuilder();
  1271. query.append("INSERT INTO castle_manor_procure VALUES ");
  1272. String values[] = new String[proc.size()];
  1273. for (CropProcure cp : proc)
  1274. {
  1275. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + ","
  1276. + cp.getPrice() + "," + cp.getReward() + "," + period + ")";
  1277. }
  1278. if (values.length > 0)
  1279. {
  1280. query.append(values[0]);
  1281. for (int i = 1; i < values.length; i++)
  1282. {
  1283. query.append(",");
  1284. query.append(values[i]);
  1285. }
  1286. statement = con.prepareStatement(query.toString());
  1287. statement.execute();
  1288. statement.close();
  1289. }
  1290. }
  1291. }
  1292. catch (Exception e)
  1293. {
  1294. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1295. }
  1296. finally
  1297. {
  1298. L2DatabaseFactory.close(con);
  1299. }
  1300. }
  1301. public void updateCrop(int cropId, long amount, int period)
  1302. {
  1303. Connection con = null;
  1304. PreparedStatement statement;
  1305. try
  1306. {
  1307. con = L2DatabaseFactory.getInstance().getConnection();
  1308. statement = con.prepareStatement(CASTLE_UPDATE_CROP);
  1309. statement.setLong(1, amount);
  1310. statement.setInt(2, cropId);
  1311. statement.setInt(3, getCastleId());
  1312. statement.setInt(4, period);
  1313. statement.execute();
  1314. statement.close();
  1315. }
  1316. catch (Exception e)
  1317. {
  1318. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1319. }
  1320. finally
  1321. {
  1322. L2DatabaseFactory.close(con);
  1323. }
  1324. }
  1325. public void updateSeed(int seedId, long amount, int period)
  1326. {
  1327. Connection con = null;
  1328. PreparedStatement statement;
  1329. try
  1330. {
  1331. con = L2DatabaseFactory.getInstance().getConnection();
  1332. statement = con.prepareStatement(CASTLE_UPDATE_SEED);
  1333. statement.setLong(1, amount);
  1334. statement.setInt(2, seedId);
  1335. statement.setInt(3, getCastleId());
  1336. statement.setInt(4, period);
  1337. statement.execute();
  1338. statement.close();
  1339. }
  1340. catch (Exception e)
  1341. {
  1342. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1343. }
  1344. finally
  1345. {
  1346. L2DatabaseFactory.close(con);
  1347. }
  1348. }
  1349. public boolean isNextPeriodApproved()
  1350. {
  1351. return _isNextPeriodApproved;
  1352. }
  1353. public void setNextPeriodApproved(boolean val)
  1354. {
  1355. _isNextPeriodApproved = val;
  1356. }
  1357. public void updateClansReputation()
  1358. {
  1359. if (_formerOwner != null)
  1360. {
  1361. if (_formerOwner != ClanTable.getInstance().getClan(getOwnerId()))
  1362. {
  1363. int maxreward = Math.max(0, _formerOwner.getReputationScore());
  1364. _formerOwner.takeReputationScore(Config.LOOSE_CASTLE_POINTS, true);
  1365. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1366. if (owner != null)
  1367. owner.addReputationScore(Math.min(Config.TAKE_CASTLE_POINTS, maxreward), true);
  1368. }
  1369. else
  1370. _formerOwner.addReputationScore(Config.CASTLE_DEFENDED_POINTS, true);
  1371. }
  1372. else
  1373. {
  1374. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1375. if (owner != null)
  1376. {
  1377. owner.addReputationScore(Config.TAKE_CASTLE_POINTS, true);
  1378. }
  1379. }
  1380. }
  1381. public void updateShowNpcCrest()
  1382. {
  1383. Connection con = null;
  1384. PreparedStatement statement;
  1385. try
  1386. {
  1387. con = L2DatabaseFactory.getInstance().getConnection();
  1388. statement = con.prepareStatement("UPDATE castle SET showNpcCrest = ? WHERE id = ?");
  1389. statement.setString(1, String.valueOf(getShowNpcCrest()));
  1390. statement.setInt(2, getCastleId());
  1391. statement.execute();
  1392. statement.close();
  1393. }
  1394. catch (Exception e)
  1395. {
  1396. _log.info("Error saving showNpcCrest for castle " + getName() + ": " + e.getMessage());
  1397. }
  1398. finally
  1399. {
  1400. L2DatabaseFactory.close(con);
  1401. }
  1402. }
  1403. public FastList<L2Skill> getResidentialSkills()
  1404. {
  1405. return _residentialSkills;
  1406. }
  1407. public void giveResidentialSkills(L2PcInstance player)
  1408. {
  1409. if ((_residentialSkills != null) && !_residentialSkills.isEmpty())
  1410. {
  1411. for (L2Skill sk : _residentialSkills)
  1412. {
  1413. player.addSkill(sk, false);
  1414. }
  1415. }
  1416. Territory territory = TerritoryWarManager.getInstance().getTerritory(getCastleId());
  1417. if (territory != null && territory.getOwnedWardIds().contains(getCastleId() + 80))
  1418. {
  1419. for(int wardId : territory.getOwnedWardIds())
  1420. {
  1421. final FastList<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1422. for (L2SkillLearn s : territorySkills)
  1423. {
  1424. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1425. if (sk != null)
  1426. {
  1427. player.addSkill(sk, false);
  1428. }
  1429. else
  1430. {
  1431. _log.warning("Trying to add a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1432. }
  1433. }
  1434. }
  1435. }
  1436. }
  1437. public void removeResidentialSkills(L2PcInstance player)
  1438. {
  1439. if (_residentialSkills != null && !_residentialSkills.isEmpty())
  1440. {
  1441. for (L2Skill sk : _residentialSkills)
  1442. {
  1443. player.removeSkill(sk, false, true);
  1444. }
  1445. }
  1446. if (TerritoryWarManager.getInstance().getTerritory(getCastleId()) != null)
  1447. {
  1448. for(int wardId : TerritoryWarManager.getInstance().getTerritory(getCastleId()).getOwnedWardIds())
  1449. {
  1450. final FastList<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1451. for (L2SkillLearn s : territorySkills)
  1452. {
  1453. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1454. if (sk != null)
  1455. {
  1456. player.removeSkill(sk, false, true);
  1457. }
  1458. else
  1459. {
  1460. _log.warning("Trying to remove a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1461. }
  1462. }
  1463. }
  1464. }
  1465. }
  1466. /**
  1467. * Register Artefact to castle
  1468. * @param artefact
  1469. */
  1470. public void registerArtefact(L2ArtefactInstance artefact)
  1471. {
  1472. if (Config.DEBUG)
  1473. _log.info("ArtefactId: "+ artefact.getObjectId() + " is registered to "+getName()+" castle.");
  1474. _artefacts.add(artefact);
  1475. }
  1476. public List<L2ArtefactInstance> getArtefacts()
  1477. {
  1478. return _artefacts;
  1479. }
  1480. public void resetManor()
  1481. {
  1482. setCropProcure(new FastList<CropProcure>(), CastleManorManager.PERIOD_CURRENT);
  1483. setCropProcure(new FastList<CropProcure>(), CastleManorManager.PERIOD_NEXT);
  1484. setSeedProduction(new FastList<SeedProduction>(), CastleManorManager.PERIOD_CURRENT);
  1485. setSeedProduction(new FastList<SeedProduction>(), CastleManorManager.PERIOD_NEXT);
  1486. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  1487. {
  1488. saveCropData();
  1489. saveSeedData();
  1490. }
  1491. }
  1492. public int getBloodAlliance()
  1493. {
  1494. return _bloodAlliance;
  1495. }
  1496. public void setBloodAlliance(int count)
  1497. {
  1498. _bloodAlliance = count;
  1499. Connection con = null;
  1500. try
  1501. {
  1502. con = L2DatabaseFactory.getInstance().getConnection();
  1503. PreparedStatement statement = con.prepareStatement("Update castle set bloodAlliance = ? where id = ?");
  1504. statement.setInt(1, _bloodAlliance);
  1505. statement.setInt(2, getCastleId());
  1506. statement.execute();
  1507. statement.close();
  1508. }
  1509. catch (Exception e)
  1510. {
  1511. }
  1512. finally
  1513. {
  1514. L2DatabaseFactory.close(con);
  1515. }
  1516. }
  1517. }