Castle.java 42 KB

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