SpawnTable.java 16 KB

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