2
0

SpawnTable.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /*
  2. * Copyright (C) 2004-2014 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.datatables;
  20. import java.sql.Connection;
  21. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.sql.Statement;
  24. import java.util.Collections;
  25. import java.util.HashMap;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import java.util.logging.Level;
  29. import java.util.logging.Logger;
  30. import javolution.util.FastMap;
  31. import javolution.util.FastSet;
  32. import org.w3c.dom.NamedNodeMap;
  33. import org.w3c.dom.Node;
  34. import com.l2jserver.Config;
  35. import com.l2jserver.L2DatabaseFactory;
  36. import com.l2jserver.gameserver.engines.DocumentParser;
  37. import com.l2jserver.gameserver.instancemanager.DayNightSpawnManager;
  38. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  39. import com.l2jserver.gameserver.model.L2Spawn;
  40. import com.l2jserver.gameserver.model.StatsSet;
  41. import com.l2jserver.gameserver.model.actor.templates.L2NpcTemplate;
  42. import com.l2jserver.gameserver.model.interfaces.IProcedure;
  43. /**
  44. * Spawn data retriever.
  45. * @author Zoey76
  46. */
  47. public final class SpawnTable extends DocumentParser
  48. {
  49. private static final Logger _log = Logger.getLogger(SpawnTable.class.getName());
  50. // SQL
  51. private static final String SELECT_SPAWNS = "SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, respawn_random, loc_id, periodOfDay FROM spawnlist";
  52. private static final String SELECT_CUSTOM_SPAWNS = "SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, respawn_random, loc_id, periodOfDay FROM custom_spawnlist";
  53. private static final Map<Integer, Set<L2Spawn>> _spawnTable = new FastMap<Integer, Set<L2Spawn>>().shared();
  54. private int _xmlSpawnCount = 0;
  55. protected SpawnTable()
  56. {
  57. load();
  58. }
  59. /**
  60. * Wrapper to load all spawns.
  61. */
  62. @Override
  63. public void load()
  64. {
  65. if (!Config.ALT_DEV_NO_SPAWNS)
  66. {
  67. fillSpawnTable(false);
  68. final int spawnCount = _spawnTable.size();
  69. _log.info(getClass().getSimpleName() + ": Loaded " + spawnCount + " npc spawns.");
  70. if (Config.CUSTOM_SPAWNLIST_TABLE)
  71. {
  72. fillSpawnTable(true);
  73. _log.info(getClass().getSimpleName() + ": Loaded " + (_spawnTable.size() - spawnCount) + " custom npc spawns.");
  74. }
  75. // Load XML list
  76. parseDatapackDirectory("data/spawnlist", false);
  77. _log.info(getClass().getSimpleName() + ": Loaded " + _xmlSpawnCount + " npc spawns from XML.");
  78. }
  79. }
  80. private boolean checkTemplate(int npcId)
  81. {
  82. L2NpcTemplate npcTemplate = NpcData.getInstance().getTemplate(npcId);
  83. if (npcTemplate == null)
  84. {
  85. _log.warning(getClass().getSimpleName() + ": Data missing in NPC table for ID: " + npcId + ".");
  86. return false;
  87. }
  88. if (npcTemplate.isType("L2SiegeGuard") || npcTemplate.isType("L2RaidBoss") || (!Config.ALLOW_CLASS_MASTERS && npcTemplate.isType("L2ClassMaster")))
  89. {
  90. // Don't spawn
  91. return false;
  92. }
  93. return true;
  94. }
  95. @Override
  96. protected void parseDocument()
  97. {
  98. NamedNodeMap attrs;
  99. for (Node list = getCurrentDocument().getFirstChild(); list != null; list = list.getNextSibling())
  100. {
  101. if (list.getNodeName().equalsIgnoreCase("list"))
  102. {
  103. attrs = list.getAttributes();
  104. // skip disabled spawnlists
  105. if (!Boolean.parseBoolean(attrs.getNamedItem("enabled").getNodeValue()))
  106. {
  107. continue;
  108. }
  109. for (Node param = list.getFirstChild(); param != null; param = param.getNextSibling())
  110. {
  111. attrs = param.getAttributes();
  112. if (param.getNodeName().equalsIgnoreCase("spawn"))
  113. {
  114. String territoryName = null;
  115. String spawnName = null;
  116. Map<String, Integer> map = null;
  117. // Check, if spawn name specified
  118. if (attrs.getNamedItem("name") != null)
  119. {
  120. spawnName = parseString(attrs, "name");
  121. }
  122. // Check, if spawn territory specified and exists
  123. if ((attrs.getNamedItem("zone") != null) && (ZoneManager.getInstance().getSpawnTerritory(attrs.getNamedItem("zone").getNodeValue()) != null))
  124. {
  125. territoryName = parseString(attrs, "zone");
  126. }
  127. for (Node npctag = param.getFirstChild(); npctag != null; npctag = npctag.getNextSibling())
  128. {
  129. attrs = npctag.getAttributes();
  130. // Check if there are any AI parameters
  131. if (npctag.getNodeName().equalsIgnoreCase("AIData"))
  132. {
  133. attrs = npctag.getAttributes();
  134. if (map == null)
  135. {
  136. map = new HashMap<>();
  137. }
  138. for (Node c = npctag.getFirstChild(); c != null; c = c.getNextSibling())
  139. {
  140. // Skip odd nodes
  141. if (c.getNodeName().equals("#text"))
  142. {
  143. continue;
  144. }
  145. int val;
  146. switch (c.getNodeName())
  147. {
  148. case "disableRandomAnimation":
  149. case "disableRandomWalk":
  150. val = Boolean.parseBoolean(c.getTextContent()) ? 1 : 0;
  151. break;
  152. default:
  153. val = Integer.parseInt(c.getTextContent());
  154. }
  155. map.put(c.getNodeName(), val);
  156. }
  157. }
  158. // Check for NPC spawns
  159. else if (npctag.getNodeName().equalsIgnoreCase("npc"))
  160. {
  161. // mandatory
  162. final int templateId = parseInteger(attrs, "id");
  163. // coordinates are optional, if territory is specified; mandatory otherwise
  164. int x = 0;
  165. int y = 0;
  166. int z = 0;
  167. try
  168. {
  169. x = parseInteger(attrs, "x");
  170. y = parseInteger(attrs, "y");
  171. z = parseInteger(attrs, "z");
  172. }
  173. catch (NullPointerException npe)
  174. {
  175. // x, y, z can be unspecified, if this spawn is territory based, do nothing
  176. }
  177. if ((x == 0) && (y == 0) && (territoryName == null)) // Both coordinates and zone are unspecified
  178. {
  179. _log.warning("XML Spawnlist: Spawn could not be initialized, both coordinates and zone are unspecified for ID " + templateId);
  180. continue;
  181. }
  182. StatsSet spawnInfo = new StatsSet();
  183. spawnInfo.set("npcTemplateid", templateId);
  184. spawnInfo.set("x", x);
  185. spawnInfo.set("y", y);
  186. spawnInfo.set("z", z);
  187. spawnInfo.set("territoryName", territoryName);
  188. spawnInfo.set("spawnName", spawnName);
  189. // trying to read optional parameters
  190. if (attrs.getNamedItem("heading") != null)
  191. {
  192. spawnInfo.set("heading", parseInteger(attrs, "heading"));
  193. }
  194. if (attrs.getNamedItem("count") != null)
  195. {
  196. spawnInfo.set("count", parseInteger(attrs, "count"));
  197. }
  198. if (attrs.getNamedItem("respawnDelay") != null)
  199. {
  200. spawnInfo.set("respawnDelay", parseInteger(attrs, "respawnDelay"));
  201. }
  202. if (attrs.getNamedItem("respawnRandom") != null)
  203. {
  204. spawnInfo.set("respawnRandom", parseInteger(attrs, "respawnRandom"));
  205. }
  206. if (attrs.getNamedItem("periodOfDay") != null)
  207. {
  208. String period = attrs.getNamedItem("periodOfDay").getNodeValue();
  209. if (period.equalsIgnoreCase("day") || period.equalsIgnoreCase("night"))
  210. {
  211. spawnInfo.set("periodOfDay", period.equalsIgnoreCase("day") ? 1 : 2);
  212. }
  213. }
  214. _xmlSpawnCount += addSpawn(spawnInfo, map);
  215. }
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. /**
  223. * Retrieves spawn data from database.
  224. * @param isCustom if {@code true} the spawns are loaded as custom from custom spawn table
  225. * @return the spawn count
  226. */
  227. private int fillSpawnTable(boolean isCustom)
  228. {
  229. int npcSpawnCount = 0;
  230. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  231. Statement s = con.createStatement();
  232. ResultSet rs = s.executeQuery(isCustom ? SELECT_CUSTOM_SPAWNS : SELECT_SPAWNS))
  233. {
  234. while (rs.next())
  235. {
  236. StatsSet spawnInfo = new StatsSet();
  237. int npcId = rs.getInt("npc_templateid");
  238. // Check basic requirements first
  239. if (!checkTemplate(npcId))
  240. {
  241. // Don't spawn
  242. continue;
  243. }
  244. spawnInfo.set("npcTemplateid", npcId);
  245. spawnInfo.set("count", rs.getInt("count"));
  246. spawnInfo.set("x", rs.getInt("locx"));
  247. spawnInfo.set("y", rs.getInt("locy"));
  248. spawnInfo.set("z", rs.getInt("locz"));
  249. spawnInfo.set("heading", rs.getInt("heading"));
  250. spawnInfo.set("respawnDelay", rs.getInt("respawn_delay"));
  251. spawnInfo.set("respawnRandom", rs.getInt("respawn_random"));
  252. spawnInfo.set("locId", rs.getInt("loc_id"));
  253. spawnInfo.set("periodOfDay", rs.getInt("periodOfDay"));
  254. spawnInfo.set("isCustomSpawn", isCustom);
  255. npcSpawnCount += addSpawn(spawnInfo);
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. _log.log(Level.WARNING, getClass().getSimpleName() + ": Spawn could not be initialized: " + e.getMessage(), e);
  261. }
  262. return npcSpawnCount;
  263. }
  264. /**
  265. * Creates NPC spawn
  266. * @param spawnInfo StatsSet of spawn parameters
  267. * @param AIData Map of specific AI parameters for this spawn
  268. * @return count NPC instances, spawned by this spawn
  269. */
  270. private int addSpawn(StatsSet spawnInfo, Map<String, Integer> AIData)
  271. {
  272. L2Spawn spawnDat;
  273. int ret = 0;
  274. try
  275. {
  276. spawnDat = new L2Spawn(NpcData.getInstance().getTemplate(spawnInfo.getInt("npcTemplateid")));
  277. spawnDat.setAmount(spawnInfo.getInt("count", 1));
  278. spawnDat.setX(spawnInfo.getInt("x", 0));
  279. spawnDat.setY(spawnInfo.getInt("y", 0));
  280. spawnDat.setZ(spawnInfo.getInt("z", 0));
  281. spawnDat.setHeading(spawnInfo.getInt("heading", -1));
  282. spawnDat.setRespawnDelay(spawnInfo.getInt("respawnDelay", 0), spawnInfo.getInt("respawnRandom", 0));
  283. spawnDat.setLocationId(spawnInfo.getInt("locId", 0));
  284. String territoryName = spawnInfo.getString("territoryName", "");
  285. String spawnName = spawnInfo.getString("spawnName", "");
  286. spawnDat.setCustom(spawnInfo.getBoolean("isCustomSpawn", false));
  287. if (!spawnName.isEmpty())
  288. {
  289. spawnDat.setName(spawnName);
  290. }
  291. if (!territoryName.isEmpty())
  292. {
  293. spawnDat.setSpawnTerritory(ZoneManager.getInstance().getSpawnTerritory(territoryName));
  294. }
  295. // Register AI Data for this spawn
  296. NpcPersonalAIData.getInstance().storeData(spawnDat, AIData);
  297. switch (spawnInfo.getInt("periodOfDay", 0))
  298. {
  299. case 0: // default
  300. ret += spawnDat.init();
  301. break;
  302. case 1: // Day
  303. DayNightSpawnManager.getInstance().addDayCreature(spawnDat);
  304. ret = 1;
  305. break;
  306. case 2: // Night
  307. DayNightSpawnManager.getInstance().addNightCreature(spawnDat);
  308. ret = 1;
  309. break;
  310. }
  311. addSpawn(spawnDat);
  312. }
  313. catch (Exception e)
  314. {
  315. // problem with initializing spawn, go to next one
  316. _log.log(Level.WARNING, "Spawn could not be initialized: " + e.getMessage(), e);
  317. }
  318. return ret;
  319. }
  320. /**
  321. * Wrapper for {@link #addSpawn(StatsSet, Map)}.
  322. * @param spawnInfo StatsSet of spawn parameters
  323. * @return count NPC instances, spawned by this spawn
  324. */
  325. private int addSpawn(StatsSet spawnInfo)
  326. {
  327. return addSpawn(spawnInfo, null);
  328. }
  329. public Map<Integer, Set<L2Spawn>> getSpawnTable()
  330. {
  331. return _spawnTable;
  332. }
  333. /**
  334. * Get the spawns for the NPC Id.
  335. * @param npcId the NPC Id
  336. * @return the spawn set for the given npcId
  337. */
  338. public Set<L2Spawn> getSpawns(int npcId)
  339. {
  340. return _spawnTable.containsKey(npcId) ? _spawnTable.get(npcId) : Collections.<L2Spawn> emptySet();
  341. }
  342. /**
  343. * Get the first NPC spawn.
  344. * @param npcId the NPC Id to search
  345. * @return the first not null spawn, if any
  346. */
  347. public L2Spawn getFirstSpawn(int npcId)
  348. {
  349. if (_spawnTable.containsKey(npcId))
  350. {
  351. for (L2Spawn spawn : _spawnTable.get(npcId))
  352. {
  353. if (spawn != null)
  354. {
  355. return spawn;
  356. }
  357. }
  358. }
  359. return null;
  360. }
  361. /**
  362. * Add a new spawn to the spawn table.
  363. * @param spawn the spawn to add
  364. * @param storeInDb if {@code true} it'll be saved in the database
  365. */
  366. public void addNewSpawn(L2Spawn spawn, boolean storeInDb)
  367. {
  368. addSpawn(spawn);
  369. if (storeInDb)
  370. {
  371. final String spawnTable = spawn.isCustom() && Config.CUSTOM_SPAWNLIST_TABLE ? "custom_spawnlist" : "spawnlist";
  372. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  373. PreparedStatement insert = con.prepareStatement("INSERT INTO " + spawnTable + "(count,npc_templateid,locx,locy,locz,heading,respawn_delay,respawn_random,loc_id) values(?,?,?,?,?,?,?,?,?)"))
  374. {
  375. insert.setInt(1, spawn.getAmount());
  376. insert.setInt(2, spawn.getId());
  377. insert.setInt(3, spawn.getX());
  378. insert.setInt(4, spawn.getY());
  379. insert.setInt(5, spawn.getZ());
  380. insert.setInt(6, spawn.getHeading());
  381. insert.setInt(7, spawn.getRespawnDelay() / 1000);
  382. insert.setInt(8, spawn.getRespawnMaxDelay() - spawn.getRespawnMinDelay());
  383. insert.setInt(9, spawn.getLocationId());
  384. insert.execute();
  385. }
  386. catch (Exception e)
  387. {
  388. _log.log(Level.WARNING, getClass().getSimpleName() + ": Could not store spawn in the DB:" + e.getMessage(), e);
  389. }
  390. }
  391. }
  392. /**
  393. * Delete an spawn from the spawn table.
  394. * @param spawn the spawn to delete
  395. * @param updateDb if {@code true} database will be updated
  396. */
  397. public void deleteSpawn(L2Spawn spawn, boolean updateDb)
  398. {
  399. if (!removeSpawn(spawn))
  400. {
  401. return;
  402. }
  403. if (updateDb)
  404. {
  405. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  406. PreparedStatement delete = con.prepareStatement("DELETE FROM " + (spawn.isCustom() ? "custom_spawnlist" : "spawnlist") + " WHERE locx=? AND locy=? AND locz=? AND npc_templateid=? AND heading=?"))
  407. {
  408. delete.setInt(1, spawn.getX());
  409. delete.setInt(2, spawn.getY());
  410. delete.setInt(3, spawn.getZ());
  411. delete.setInt(4, spawn.getId());
  412. delete.setInt(5, spawn.getHeading());
  413. delete.execute();
  414. }
  415. catch (Exception e)
  416. {
  417. _log.log(Level.WARNING, getClass().getSimpleName() + ": Spawn " + spawn + " could not be removed from DB: " + e.getMessage(), e);
  418. }
  419. }
  420. }
  421. /**
  422. * Add a spawn to the spawn set if present, otherwise add a spawn set and add the spawn to the newly created spawn set.
  423. * @param spawn the NPC spawn to add
  424. */
  425. private void addSpawn(L2Spawn spawn)
  426. {
  427. if (!_spawnTable.containsKey(spawn.getId()))
  428. {
  429. _spawnTable.put(spawn.getId(), new FastSet<L2Spawn>().shared());
  430. }
  431. _spawnTable.get(spawn.getId()).add(spawn);
  432. }
  433. /**
  434. * Remove a spawn from the spawn set, if the spawn set is empty, remove it as well.
  435. * @param spawn the NPC spawn to remove
  436. * @return {@code true} if the spawn was successfully removed, {@code false} otherwise
  437. */
  438. private boolean removeSpawn(L2Spawn spawn)
  439. {
  440. if (_spawnTable.containsKey(spawn.getId()))
  441. {
  442. final Set<L2Spawn> set = _spawnTable.get(spawn.getId());
  443. boolean removed = set.remove(spawn);
  444. if (set.isEmpty())
  445. {
  446. _spawnTable.remove(spawn.getId());
  447. }
  448. return removed;
  449. }
  450. return false;
  451. }
  452. /**
  453. * Execute a procedure over all spawns.<br>
  454. * <font size="4" color="red">Do not use it!</font>
  455. * @param procedure the procedure to execute
  456. * @return {@code true} if all procedures were executed, {@code false} otherwise
  457. */
  458. public boolean forEachSpawn(IProcedure<L2Spawn, Boolean> procedure)
  459. {
  460. for (Set<L2Spawn> set : _spawnTable.values())
  461. {
  462. for (L2Spawn spawn : set)
  463. {
  464. if (!procedure.execute(spawn))
  465. {
  466. return false;
  467. }
  468. }
  469. }
  470. return true;
  471. }
  472. public static SpawnTable getInstance()
  473. {
  474. return SingletonHolder._instance;
  475. }
  476. private static class SingletonHolder
  477. {
  478. protected static final SpawnTable _instance = new SpawnTable();
  479. }
  480. }