Castle.java 42 KB

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