2
0

ZoneManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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.instancemanager;
  16. import gnu.trove.procedure.TObjectProcedure;
  17. import java.lang.reflect.Constructor;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import org.w3c.dom.Document;
  27. import org.w3c.dom.NamedNodeMap;
  28. import org.w3c.dom.Node;
  29. import com.l2jserver.Config;
  30. import com.l2jserver.gameserver.engines.DocumentParser;
  31. import com.l2jserver.gameserver.model.L2Object;
  32. import com.l2jserver.gameserver.model.L2World;
  33. import com.l2jserver.gameserver.model.L2WorldRegion;
  34. import com.l2jserver.gameserver.model.actor.L2Character;
  35. import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
  36. import com.l2jserver.gameserver.model.zone.L2ZoneRespawn;
  37. import com.l2jserver.gameserver.model.zone.L2ZoneType;
  38. import com.l2jserver.gameserver.model.zone.form.ZoneCuboid;
  39. import com.l2jserver.gameserver.model.zone.form.ZoneCylinder;
  40. import com.l2jserver.gameserver.model.zone.form.ZoneNPoly;
  41. import com.l2jserver.gameserver.model.zone.type.L2ArenaZone;
  42. import com.l2jserver.gameserver.model.zone.type.L2OlympiadStadiumZone;
  43. import com.l2jserver.gameserver.model.zone.type.L2RespawnZone;
  44. /**
  45. * This class manages the zones
  46. * @author durgus
  47. */
  48. public class ZoneManager extends DocumentParser
  49. {
  50. private static final Logger _log = Logger.getLogger(ZoneManager.class.getName());
  51. private final Map<Class<? extends L2ZoneType>, Map<Integer, ? extends L2ZoneType>> _classZones = new HashMap<Class<? extends L2ZoneType>, Map<Integer, ? extends L2ZoneType>>();
  52. private int _lastDynamicId = 300000;
  53. private List<L2ItemInstance> _debugItems;
  54. /**
  55. * @return
  56. */
  57. public static final ZoneManager getInstance()
  58. {
  59. return SingletonHolder._instance;
  60. }
  61. protected ZoneManager()
  62. {
  63. load();
  64. }
  65. public void reload()
  66. {
  67. // Get the world regions
  68. int count = 0;
  69. L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();
  70. for (int x = 0; x < worldRegions.length; x++)
  71. {
  72. for (int y = 0; y < worldRegions[x].length; y++)
  73. {
  74. worldRegions[x][y].getZones().clear();
  75. count++;
  76. }
  77. }
  78. GrandBossManager.getInstance().getZones().clear();
  79. _log.info("Removed zones in " + count + " regions.");
  80. // Load the zones
  81. load();
  82. L2World.getInstance().forEachObject(new ForEachCharacterRevalidateZone());
  83. }
  84. protected final class ForEachCharacterRevalidateZone implements TObjectProcedure<L2Object>
  85. {
  86. @Override
  87. public final boolean execute(final L2Object o)
  88. {
  89. if (o instanceof L2Character)
  90. ((L2Character) o).revalidateZone(true);
  91. return true;
  92. }
  93. }
  94. @Override
  95. protected void parseDocument(Document doc)
  96. {
  97. // Get the world regions
  98. L2WorldRegion[][] worldRegions = L2World.getInstance().getAllWorldRegions();
  99. NamedNodeMap attrs;
  100. Node attribute;
  101. String zoneName;
  102. int[][] coords;
  103. int zoneId, minZ, maxZ;
  104. String zoneType, zoneShape;
  105. List<int[]> rs = new ArrayList<>();
  106. for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
  107. {
  108. if ("list".equalsIgnoreCase(n.getNodeName()))
  109. {
  110. attrs = n.getAttributes();
  111. attribute = attrs.getNamedItem("enabled");
  112. if (attribute != null && !Boolean.parseBoolean(attribute.getNodeValue()))
  113. continue;
  114. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  115. {
  116. if ("zone".equalsIgnoreCase(d.getNodeName()))
  117. {
  118. attrs = d.getAttributes();
  119. attribute = attrs.getNamedItem("id");
  120. if (attribute != null)
  121. zoneId = Integer.parseInt(attribute.getNodeValue());
  122. else
  123. zoneId = _lastDynamicId++;
  124. attribute = attrs.getNamedItem("name");
  125. if (attribute != null)
  126. zoneName = attribute.getNodeValue();
  127. else
  128. zoneName = null;
  129. minZ = parseInt(attrs, "minZ");
  130. maxZ = parseInt(attrs, "maxZ");
  131. zoneType = attrs.getNamedItem("type").getNodeValue();
  132. zoneShape = attrs.getNamedItem("shape").getNodeValue();
  133. // Create the zone
  134. Class<?> newZone = null;
  135. Constructor<?> zoneConstructor = null;
  136. L2ZoneType temp = null;
  137. try
  138. {
  139. newZone = Class.forName("com.l2jserver.gameserver.model.zone.type.L2" + zoneType);
  140. zoneConstructor = newZone.getConstructor(int.class);
  141. temp = (L2ZoneType) zoneConstructor.newInstance(zoneId);
  142. }
  143. catch (Exception e)
  144. {
  145. _log.warning("ZoneData: No such zone type: " + zoneType + " in file: " + getCurrentFile().getName());
  146. continue;
  147. }
  148. // Get the zone shape from xml
  149. try
  150. {
  151. coords = null;
  152. int[] point;
  153. rs.clear();
  154. for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling())
  155. {
  156. if ("node".equalsIgnoreCase(cd.getNodeName()))
  157. {
  158. attrs = cd.getAttributes();
  159. point = new int[2];
  160. point[0] = parseInt(attrs, "X");
  161. point[1] = parseInt(attrs, "Y");
  162. rs.add(point);
  163. }
  164. }
  165. coords = rs.toArray(new int[rs.size()][2]);
  166. if (coords == null || coords.length == 0)
  167. {
  168. _log.warning("ZoneData: missing data for zone: " + zoneId + " XML file: " + getCurrentFile().getName());
  169. continue;
  170. }
  171. // Create this zone. Parsing for cuboids is a
  172. // bit different than for other polygons
  173. // cuboids need exactly 2 points to be defined.
  174. // Other polygons need at least 3 (one per
  175. // vertex)
  176. if (zoneShape.equalsIgnoreCase("Cuboid"))
  177. {
  178. if (coords.length == 2)
  179. temp.setZone(new ZoneCuboid(coords[0][0], coords[1][0], coords[0][1], coords[1][1], minZ, maxZ));
  180. else
  181. {
  182. _log.warning("ZoneData: Missing cuboid vertex in sql data for zone: " + zoneId + " in file: " + getCurrentFile().getName());
  183. continue;
  184. }
  185. }
  186. else if (zoneShape.equalsIgnoreCase("NPoly"))
  187. {
  188. // nPoly needs to have at least 3 vertices
  189. if (coords.length > 2)
  190. {
  191. final int[] aX = new int[coords.length];
  192. final int[] aY = new int[coords.length];
  193. for (int i = 0; i < coords.length; i++)
  194. {
  195. aX[i] = coords[i][0];
  196. aY[i] = coords[i][1];
  197. }
  198. temp.setZone(new ZoneNPoly(aX, aY, minZ, maxZ));
  199. }
  200. else
  201. {
  202. _log.warning("ZoneData: Bad data for zone: " + zoneId + " in file: " + getCurrentFile().getName());
  203. continue;
  204. }
  205. }
  206. else if (zoneShape.equalsIgnoreCase("Cylinder"))
  207. {
  208. // A Cylinder zone requires a center point
  209. // at x,y and a radius
  210. attrs = d.getAttributes();
  211. final int zoneRad = Integer.parseInt(attrs.getNamedItem("rad").getNodeValue());
  212. if (coords.length == 1 && zoneRad > 0)
  213. temp.setZone(new ZoneCylinder(coords[0][0], coords[0][1], minZ, maxZ, zoneRad));
  214. else
  215. {
  216. _log.warning("ZoneData: Bad data for zone: " + zoneId + " in file: " + getCurrentFile().getName());
  217. continue;
  218. }
  219. }
  220. }
  221. catch (Exception e)
  222. {
  223. _log.log(Level.WARNING, "ZoneData: Failed to load zone " + zoneId + " coordinates: " + e.getMessage(), e);
  224. }
  225. // Check for additional parameters
  226. for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling())
  227. {
  228. if ("stat".equalsIgnoreCase(cd.getNodeName()))
  229. {
  230. attrs = cd.getAttributes();
  231. String name = attrs.getNamedItem("name").getNodeValue();
  232. String val = attrs.getNamedItem("val").getNodeValue();
  233. temp.setParameter(name, val);
  234. }
  235. else if ("spawn".equalsIgnoreCase(cd.getNodeName()) && temp instanceof L2ZoneRespawn)
  236. {
  237. attrs = cd.getAttributes();
  238. int spawnX = Integer.parseInt(attrs.getNamedItem("X").getNodeValue());
  239. int spawnY = Integer.parseInt(attrs.getNamedItem("Y").getNodeValue());
  240. int spawnZ = Integer.parseInt(attrs.getNamedItem("Z").getNodeValue());
  241. Node val = attrs.getNamedItem("type");
  242. ((L2ZoneRespawn) temp).parseLoc(spawnX, spawnY, spawnZ, val == null ? null : val.getNodeValue());
  243. }
  244. else if ("race".equalsIgnoreCase(cd.getNodeName()) && temp instanceof L2RespawnZone)
  245. {
  246. attrs = cd.getAttributes();
  247. String race = attrs.getNamedItem("name").getNodeValue();
  248. String point = attrs.getNamedItem("point").getNodeValue();
  249. ((L2RespawnZone) temp).addRaceRespawnPoint(race, point);
  250. }
  251. }
  252. if (checkId(zoneId))
  253. _log.config("Caution: Zone (" + zoneId + ") from file: " + getCurrentFile().getName() + " overrides previos definition.");
  254. if (zoneName != null && !zoneName.isEmpty())
  255. temp.setName(zoneName);
  256. addZone(zoneId, temp);
  257. // Register the zone into any world region it
  258. // intersects with...
  259. // currently 11136 test for each zone :>
  260. int ax, ay, bx, by;
  261. for (int x = 0; x < worldRegions.length; x++)
  262. {
  263. for (int y = 0; y < worldRegions[x].length; y++)
  264. {
  265. ax = (x - L2World.OFFSET_X) << L2World.SHIFT_BY;
  266. bx = ((x + 1) - L2World.OFFSET_X) << L2World.SHIFT_BY;
  267. ay = (y - L2World.OFFSET_Y) << L2World.SHIFT_BY;
  268. by = ((y + 1) - L2World.OFFSET_Y) << L2World.SHIFT_BY;
  269. if (temp.getZone().intersectsRectangle(ax, bx, ay, by))
  270. {
  271. if (Config.DEBUG)
  272. {
  273. _log.info("Zone (" + zoneId + ") added to: " + x + " " + y);
  274. }
  275. worldRegions[x][y].addZone(temp);
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. }
  283. }
  284. @Override
  285. public final void load()
  286. {
  287. _log.info("Loading zones...");
  288. _classZones.clear();
  289. long started = System.currentTimeMillis();
  290. parseDirectory("data/zones");
  291. started = System.currentTimeMillis() - started;
  292. _log.info("Done: loaded " + _classZones.size() + " zone classes and " + getSize() + " zones in " + (started / 1000) + " seconds.");
  293. }
  294. public int getSize()
  295. {
  296. int i = 0;
  297. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  298. {
  299. i += map.size();
  300. }
  301. return i;
  302. }
  303. public boolean checkId(int id)
  304. {
  305. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  306. {
  307. if (map.containsKey(id))
  308. return true;
  309. }
  310. return false;
  311. }
  312. /**
  313. * Add new zone
  314. * @param <T>
  315. * @param id
  316. * @param zone
  317. */
  318. @SuppressWarnings("unchecked")
  319. public <T extends L2ZoneType> void addZone(Integer id, T zone)
  320. {
  321. Map<Integer, T> map = (Map<Integer, T>) _classZones.get(zone.getClass());
  322. if (map == null)
  323. {
  324. map = new HashMap<Integer, T>();
  325. map.put(id, zone);
  326. _classZones.put(zone.getClass(), map);
  327. }
  328. else
  329. map.put(id, zone);
  330. }
  331. /**
  332. * Returns all zones registered with the ZoneManager. To minimize iteration processing retrieve zones from L2WorldRegion for a specific location instead.
  333. * @return zones
  334. * @see #getAllZones(Class)
  335. */
  336. @Deprecated
  337. public Collection<L2ZoneType> getAllZones()
  338. {
  339. List<L2ZoneType> zones = new ArrayList<L2ZoneType>();
  340. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  341. {
  342. zones.addAll(map.values());
  343. }
  344. return zones;
  345. }
  346. /**
  347. * Return all zones by class type
  348. * @param <T>
  349. * @param zoneType Zone class
  350. * @return Collection of zones
  351. */
  352. @SuppressWarnings("unchecked")
  353. public <T extends L2ZoneType> Collection<T> getAllZones(Class<T> zoneType)
  354. {
  355. return (Collection<T>) _classZones.get(zoneType).values();
  356. }
  357. /**
  358. * Get zone by ID
  359. * @param id
  360. * @return
  361. * @see #getZoneById(int, Class)
  362. */
  363. public L2ZoneType getZoneById(int id)
  364. {
  365. for (Map<Integer, ? extends L2ZoneType> map : _classZones.values())
  366. {
  367. if (map.containsKey(id))
  368. return map.get(id);
  369. }
  370. return null;
  371. }
  372. /**
  373. * Get zone by ID and zone class
  374. * @param <T>
  375. * @param id
  376. * @param zoneType
  377. * @return zone
  378. */
  379. @SuppressWarnings("unchecked")
  380. public <T extends L2ZoneType> T getZoneById(int id, Class<T> zoneType)
  381. {
  382. return (T) _classZones.get(zoneType).get(id);
  383. }
  384. /**
  385. * Returns all zones from where the object is located
  386. * @param object
  387. * @return zones
  388. */
  389. public List<L2ZoneType> getZones(L2Object object)
  390. {
  391. return getZones(object.getX(), object.getY(), object.getZ());
  392. }
  393. /**
  394. * @param <T>
  395. * @param object
  396. * @param type
  397. * @return zone from where the object is located by type
  398. */
  399. public <T extends L2ZoneType> T getZone(L2Object object, Class<T> type)
  400. {
  401. if (object == null)
  402. return null;
  403. return getZone(object.getX(), object.getY(), object.getZ(), type);
  404. }
  405. /**
  406. * Returns all zones from given coordinates (plane)
  407. * @param x
  408. * @param y
  409. * @return zones
  410. */
  411. public List<L2ZoneType> getZones(int x, int y)
  412. {
  413. L2WorldRegion region = L2World.getInstance().getRegion(x, y);
  414. List<L2ZoneType> temp = new ArrayList<L2ZoneType>();
  415. for (L2ZoneType zone : region.getZones())
  416. {
  417. if (zone.isInsideZone(x, y))
  418. temp.add(zone);
  419. }
  420. return temp;
  421. }
  422. /**
  423. * Returns all zones from given coordinates
  424. * @param x
  425. * @param y
  426. * @param z
  427. * @return zones
  428. */
  429. public List<L2ZoneType> getZones(int x, int y, int z)
  430. {
  431. L2WorldRegion region = L2World.getInstance().getRegion(x, y);
  432. List<L2ZoneType> temp = new ArrayList<L2ZoneType>();
  433. for (L2ZoneType zone : region.getZones())
  434. {
  435. if (zone.isInsideZone(x, y, z))
  436. temp.add(zone);
  437. }
  438. return temp;
  439. }
  440. /**
  441. * @param <T>
  442. * @param x
  443. * @param y
  444. * @param z
  445. * @param type
  446. * @return zone from given coordinates
  447. */
  448. @SuppressWarnings("unchecked")
  449. public <T extends L2ZoneType> T getZone(int x, int y, int z, Class<T> type)
  450. {
  451. L2WorldRegion region = L2World.getInstance().getRegion(x, y);
  452. for (L2ZoneType zone : region.getZones())
  453. {
  454. if (zone.isInsideZone(x, y, z) && type.isInstance(zone))
  455. return (T) zone;
  456. }
  457. return null;
  458. }
  459. public final L2ArenaZone getArena(L2Character character)
  460. {
  461. if (character == null)
  462. return null;
  463. for (L2ZoneType temp : ZoneManager.getInstance().getZones(character.getX(), character.getY(), character.getZ()))
  464. {
  465. if (temp instanceof L2ArenaZone && temp.isCharacterInZone(character))
  466. return ((L2ArenaZone) temp);
  467. }
  468. return null;
  469. }
  470. public final L2OlympiadStadiumZone getOlympiadStadium(L2Character character)
  471. {
  472. if (character == null)
  473. return null;
  474. for (L2ZoneType temp : ZoneManager.getInstance().getZones(character.getX(), character.getY(), character.getZ()))
  475. {
  476. if (temp instanceof L2OlympiadStadiumZone && temp.isCharacterInZone(character))
  477. return ((L2OlympiadStadiumZone) temp);
  478. }
  479. return null;
  480. }
  481. /**
  482. * For testing purposes only
  483. * @param <T>
  484. * @param obj
  485. * @param type
  486. * @return
  487. */
  488. @SuppressWarnings("unchecked")
  489. public <T extends L2ZoneType> T getClosestZone(L2Object obj, Class<T> type)
  490. {
  491. T zone = getZone(obj, type);
  492. if (zone == null)
  493. {
  494. double closestdis = Double.MAX_VALUE;
  495. for (T temp : (Collection<T>) _classZones.get(type).values())
  496. {
  497. double distance = temp.getDistanceToZone(obj);
  498. if (distance < closestdis)
  499. {
  500. closestdis = distance;
  501. zone = temp;
  502. }
  503. }
  504. }
  505. return zone;
  506. }
  507. /**
  508. * General storage for debug items used for visualizing zones.
  509. * @return list of items
  510. */
  511. public List<L2ItemInstance> getDebugItems()
  512. {
  513. if (_debugItems == null)
  514. _debugItems = new ArrayList<L2ItemInstance>();
  515. return _debugItems;
  516. }
  517. /**
  518. * Remove all debug items from l2world
  519. */
  520. public void clearDebugItems()
  521. {
  522. if (_debugItems != null)
  523. {
  524. Iterator<L2ItemInstance> it = _debugItems.iterator();
  525. while (it.hasNext())
  526. {
  527. L2ItemInstance item = it.next();
  528. if (item != null)
  529. item.decayMe();
  530. it.remove();
  531. }
  532. }
  533. }
  534. private static class SingletonHolder
  535. {
  536. protected static final ZoneManager _instance = new ZoneManager();
  537. }
  538. }