Castle.java 42 KB

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