WalkingManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.instancemanager;
  20. import java.util.ArrayList;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import org.w3c.dom.Document;
  25. import org.w3c.dom.NamedNodeMap;
  26. import org.w3c.dom.Node;
  27. import com.l2jserver.gameserver.ThreadPoolManager;
  28. import com.l2jserver.gameserver.ai.CtrlIntention;
  29. import com.l2jserver.gameserver.instancemanager.tasks.StartMovingTask;
  30. import com.l2jserver.gameserver.model.L2NpcWalkerNode;
  31. import com.l2jserver.gameserver.model.L2WalkRoute;
  32. import com.l2jserver.gameserver.model.Location;
  33. import com.l2jserver.gameserver.model.WalkInfo;
  34. import com.l2jserver.gameserver.model.actor.L2Npc;
  35. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  36. import com.l2jserver.gameserver.model.actor.tasks.npc.walker.ArrivedTask;
  37. import com.l2jserver.gameserver.model.events.EventDispatcher;
  38. import com.l2jserver.gameserver.model.events.impl.character.npc.OnNpcMoveNodeArrived;
  39. import com.l2jserver.gameserver.model.holders.NpcRoutesHolder;
  40. import com.l2jserver.gameserver.network.NpcStringId;
  41. import com.l2jserver.gameserver.network.clientpackets.Say2;
  42. import com.l2jserver.gameserver.network.serverpackets.NpcSay;
  43. import com.l2jserver.gameserver.util.Broadcast;
  44. import com.l2jserver.util.data.xml.IXmlReader;
  45. /**
  46. * This class manages walking monsters.
  47. * @author GKR
  48. */
  49. public final class WalkingManager implements IXmlReader
  50. {
  51. // Repeat style:
  52. // 0 - go back
  53. // 1 - go to first point (circle style)
  54. // 2 - teleport to first point (conveyor style)
  55. // 3 - random walking between points.
  56. public static final byte REPEAT_GO_BACK = 0;
  57. public static final byte REPEAT_GO_FIRST = 1;
  58. public static final byte REPEAT_TELE_FIRST = 2;
  59. public static final byte REPEAT_RANDOM = 3;
  60. private final Map<String, L2WalkRoute> _routes = new HashMap<>(); // all available routes
  61. private final Map<Integer, WalkInfo> _activeRoutes = new HashMap<>(); // each record represents NPC, moving by predefined route from _routes, and moving progress
  62. private final Map<Integer, NpcRoutesHolder> _routesToAttach = new HashMap<>(); // each record represents NPC and all available routes for it
  63. protected WalkingManager()
  64. {
  65. load();
  66. }
  67. @Override
  68. public final void load()
  69. {
  70. parseDatapackFile("data/Routes.xml");
  71. LOGGER.info("{}: Loaded {} walking routes.", getClass().getSimpleName(), _routes.size());
  72. }
  73. @Override
  74. public void parseDocument(Document doc)
  75. {
  76. Node n = doc.getFirstChild();
  77. for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
  78. {
  79. if (d.getNodeName().equals("route"))
  80. {
  81. final String routeName = parseString(d.getAttributes(), "name");
  82. boolean repeat = parseBoolean(d.getAttributes(), "repeat");
  83. String repeatStyle = d.getAttributes().getNamedItem("repeatStyle").getNodeValue();
  84. byte repeatType;
  85. if (repeatStyle.equalsIgnoreCase("back"))
  86. {
  87. repeatType = REPEAT_GO_BACK;
  88. }
  89. else if (repeatStyle.equalsIgnoreCase("cycle"))
  90. {
  91. repeatType = REPEAT_GO_FIRST;
  92. }
  93. else if (repeatStyle.equalsIgnoreCase("conveyor"))
  94. {
  95. repeatType = REPEAT_TELE_FIRST;
  96. }
  97. else if (repeatStyle.equalsIgnoreCase("random"))
  98. {
  99. repeatType = REPEAT_RANDOM;
  100. }
  101. else
  102. {
  103. repeatType = -1;
  104. }
  105. final List<L2NpcWalkerNode> list = new ArrayList<>();
  106. for (Node r = d.getFirstChild(); r != null; r = r.getNextSibling())
  107. {
  108. if (r.getNodeName().equals("point"))
  109. {
  110. NamedNodeMap attrs = r.getAttributes();
  111. int x = parseInteger(attrs, "X");
  112. int y = parseInteger(attrs, "Y");
  113. int z = parseInteger(attrs, "Z");
  114. int delay = parseInteger(attrs, "delay");
  115. boolean run = parseBoolean(attrs, "run");
  116. NpcStringId npcString = null;
  117. String chatString = null;
  118. Node node = attrs.getNamedItem("string");
  119. if (node != null)
  120. {
  121. chatString = node.getNodeValue();
  122. }
  123. else
  124. {
  125. node = attrs.getNamedItem("npcString");
  126. if (node != null)
  127. {
  128. npcString = NpcStringId.getNpcStringId(node.getNodeValue());
  129. if (npcString == null)
  130. {
  131. LOGGER.warn("{}: Unknown NPC String {} for route {}!", getClass().getSimpleName(), node.getNodeValue(), routeName);
  132. continue;
  133. }
  134. }
  135. else
  136. {
  137. node = attrs.getNamedItem("npcStringId");
  138. if (node != null)
  139. {
  140. npcString = NpcStringId.getNpcStringId(Integer.parseInt(node.getNodeValue()));
  141. if (npcString == null)
  142. {
  143. LOGGER.warn("{}: Unknown npcString {} for route {}!", getClass().getSimpleName(), node.getNodeValue(), routeName);
  144. continue;
  145. }
  146. }
  147. }
  148. }
  149. list.add(new L2NpcWalkerNode(x, y, z, delay, run, npcString, chatString));
  150. }
  151. else if (r.getNodeName().equals("target"))
  152. {
  153. NamedNodeMap attrs = r.getAttributes();
  154. try
  155. {
  156. int npcId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
  157. int x = Integer.parseInt(attrs.getNamedItem("spawnX").getNodeValue());
  158. int y = Integer.parseInt(attrs.getNamedItem("spawnY").getNodeValue());
  159. int z = Integer.parseInt(attrs.getNamedItem("spawnZ").getNodeValue());
  160. NpcRoutesHolder holder = _routesToAttach.containsKey(npcId) ? _routesToAttach.get(npcId) : new NpcRoutesHolder();
  161. holder.addRoute(routeName, new Location(x, y, z));
  162. _routesToAttach.put(npcId, holder);
  163. }
  164. catch (Exception e)
  165. {
  166. LOGGER.warn("{}: Error in target definition for route {}!", getClass().getSimpleName(), routeName);
  167. }
  168. }
  169. }
  170. _routes.put(routeName, new L2WalkRoute(routeName, list, repeat, false, repeatType));
  171. }
  172. }
  173. }
  174. /**
  175. * @param npc NPC to check
  176. * @return {@code true} if given NPC, or its leader is controlled by Walking Manager and moves currently.
  177. */
  178. public boolean isOnWalk(L2Npc npc)
  179. {
  180. L2MonsterInstance monster = null;
  181. if (npc.isMonster())
  182. {
  183. if (((L2MonsterInstance) npc).getLeader() == null)
  184. {
  185. monster = (L2MonsterInstance) npc;
  186. }
  187. else
  188. {
  189. monster = ((L2MonsterInstance) npc).getLeader();
  190. }
  191. }
  192. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  193. {
  194. return false;
  195. }
  196. final WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  197. if (walk.isStoppedByAttack() || walk.isSuspended())
  198. {
  199. return false;
  200. }
  201. return true;
  202. }
  203. public L2WalkRoute getRoute(String route)
  204. {
  205. return _routes.get(route);
  206. }
  207. /**
  208. * @param npc NPC to check
  209. * @return {@code true} if given NPC controlled by Walking Manager.
  210. */
  211. public boolean isRegistered(L2Npc npc)
  212. {
  213. return _activeRoutes.containsKey(npc.getObjectId());
  214. }
  215. /**
  216. * @param npc
  217. * @return name of route
  218. */
  219. public String getRouteName(L2Npc npc)
  220. {
  221. return _activeRoutes.containsKey(npc.getObjectId()) ? _activeRoutes.get(npc.getObjectId()).getRoute().getName() : "";
  222. }
  223. /**
  224. * Start to move given NPC by given route
  225. * @param npc NPC to move
  226. * @param routeName name of route to move by
  227. */
  228. public void startMoving(final L2Npc npc, final String routeName)
  229. {
  230. if (_routes.containsKey(routeName) && (npc != null) && !npc.isDead()) // check, if these route and NPC present
  231. {
  232. if (!_activeRoutes.containsKey(npc.getObjectId())) // new walk task
  233. {
  234. // only if not already moved / not engaged in battle... should not happens if called on spawn
  235. if ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE))
  236. {
  237. final WalkInfo walk = new WalkInfo(routeName);
  238. if (npc.isDebug())
  239. {
  240. walk.setLastAction(System.currentTimeMillis());
  241. }
  242. L2NpcWalkerNode node = walk.getCurrentNode();
  243. // adjust next waypoint, if NPC spawns at first waypoint
  244. if ((npc.getX() == node.getX()) && (npc.getY() == node.getY()))
  245. {
  246. walk.calculateNextNode(npc);
  247. node = walk.getCurrentNode();
  248. npc.sendDebugMessage("Route '" + routeName + "': spawn point is same with first waypoint, adjusted to next");
  249. }
  250. if (!npc.isInsideRadius(node, 3000, true, false))
  251. {
  252. final String message = "Route '" + routeName + "': NPC (id=" + npc.getId() + ", x=" + npc.getX() + ", y=" + npc.getY() + ", z=" + npc.getZ() + ") is too far from starting point (node x=" + node.getX() + ", y=" + node.getY() + ", z=" + node.getZ() + ", range=" + npc.calculateDistance(node, true, true) + "), walking will not start";
  253. LOGGER.warn("{}: {}", getClass().getSimpleName(), message);
  254. npc.sendDebugMessage(message);
  255. return;
  256. }
  257. npc.sendDebugMessage("Starting to move at route '" + routeName + "'");
  258. npc.setIsRunning(node.runToLocation());
  259. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, node);
  260. walk.setWalkCheckTask(ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new StartMovingTask(npc, routeName), 60000, 60000)); // start walk check task, for resuming walk after fight
  261. npc.getKnownList().startTrackingTask();
  262. _activeRoutes.put(npc.getObjectId(), walk); // register route
  263. }
  264. else
  265. {
  266. npc.sendDebugMessage("Failed to start moving along route '" + routeName + "', scheduled");
  267. ThreadPoolManager.getInstance().scheduleGeneral(new StartMovingTask(npc, routeName), 60000);
  268. }
  269. }
  270. else
  271. // walk was stopped due to some reason (arrived to node, script action, fight or something else), resume it
  272. {
  273. if (_activeRoutes.containsKey(npc.getObjectId()) && ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE)))
  274. {
  275. final WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  276. if (walk == null)
  277. {
  278. return;
  279. }
  280. // Prevent call simultaneously from scheduled task and onArrived() or temporarily stop walking for resuming in future
  281. if (walk.isBlocked() || walk.isSuspended())
  282. {
  283. npc.sendDebugMessage("Failed to continue moving along route '" + routeName + "' (operation is blocked)");
  284. return;
  285. }
  286. walk.setBlocked(true);
  287. final L2NpcWalkerNode node = walk.getCurrentNode();
  288. npc.sendDebugMessage("Route '" + routeName + "', continuing to node " + walk.getCurrentNodeId());
  289. npc.setIsRunning(node.runToLocation());
  290. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, node);
  291. walk.setBlocked(false);
  292. walk.setStoppedByAttack(false);
  293. }
  294. else
  295. {
  296. npc.sendDebugMessage("Failed to continue moving along route '" + routeName + "' (wrong AI state - " + npc.getAI().getIntention() + ")");
  297. }
  298. }
  299. }
  300. }
  301. /**
  302. * Cancel NPC moving permanently
  303. * @param npc NPC to cancel
  304. */
  305. public synchronized void cancelMoving(L2Npc npc)
  306. {
  307. final WalkInfo walk = _activeRoutes.remove(npc.getObjectId());
  308. if (walk != null)
  309. {
  310. walk.getWalkCheckTask().cancel(true);
  311. npc.getKnownList().stopTrackingTask();
  312. }
  313. }
  314. /**
  315. * Resumes previously stopped moving
  316. * @param npc NPC to resume
  317. */
  318. public void resumeMoving(final L2Npc npc)
  319. {
  320. final WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  321. if (walk != null)
  322. {
  323. walk.setSuspended(false);
  324. walk.setStoppedByAttack(false);
  325. startMoving(npc, walk.getRoute().getName());
  326. }
  327. }
  328. /**
  329. * Pause NPC moving until it will be resumed
  330. * @param npc NPC to pause moving
  331. * @param suspend {@code true} if moving was temporarily suspended for some reasons of AI-controlling script
  332. * @param stoppedByAttack {@code true} if moving was suspended because of NPC was attacked or desired to attack
  333. */
  334. public void stopMoving(L2Npc npc, boolean suspend, boolean stoppedByAttack)
  335. {
  336. L2MonsterInstance monster = null;
  337. if (npc.isMonster())
  338. {
  339. if (((L2MonsterInstance) npc).getLeader() == null)
  340. {
  341. monster = (L2MonsterInstance) npc;
  342. }
  343. else
  344. {
  345. monster = ((L2MonsterInstance) npc).getLeader();
  346. }
  347. }
  348. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  349. {
  350. return;
  351. }
  352. final WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  353. walk.setSuspended(suspend);
  354. walk.setStoppedByAttack(stoppedByAttack);
  355. if (monster != null)
  356. {
  357. monster.stopMove(null);
  358. monster.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  359. }
  360. else
  361. {
  362. npc.stopMove(null);
  363. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  364. }
  365. }
  366. /**
  367. * Manage "node arriving"-related tasks: schedule move to next node; send ON_NODE_ARRIVED event to Quest script
  368. * @param npc NPC to manage
  369. */
  370. public void onArrived(final L2Npc npc)
  371. {
  372. if (_activeRoutes.containsKey(npc.getObjectId()))
  373. {
  374. // Notify quest
  375. EventDispatcher.getInstance().notifyEventAsync(new OnNpcMoveNodeArrived(npc), npc);
  376. final WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  377. // Opposite should not happen... but happens sometime
  378. if ((walk.getCurrentNodeId() >= 0) && (walk.getCurrentNodeId() < walk.getRoute().getNodesCount()))
  379. {
  380. final L2NpcWalkerNode node = walk.getRoute().getNodeList().get(walk.getCurrentNodeId());
  381. if (npc.isInsideRadius(node, 10, false, false))
  382. {
  383. npc.sendDebugMessage("Route '" + walk.getRoute().getName() + "', arrived to node " + walk.getCurrentNodeId());
  384. npc.sendDebugMessage("Done in " + ((System.currentTimeMillis() - walk.getLastAction()) / 1000) + " s");
  385. walk.calculateNextNode(npc);
  386. walk.setBlocked(true); // prevents to be ran from walk check task, if there is delay in this node.
  387. if (node.getNpcString() != null)
  388. {
  389. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, node.getNpcString()));
  390. }
  391. else if (!node.getChatText().isEmpty())
  392. {
  393. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, node.getChatText()));
  394. }
  395. if (npc.isDebug())
  396. {
  397. walk.setLastAction(System.currentTimeMillis());
  398. }
  399. ThreadPoolManager.getInstance().scheduleGeneral(new ArrivedTask(npc, walk), 100 + (node.getDelay() * 1000L));
  400. }
  401. }
  402. }
  403. }
  404. /**
  405. * Manage "on death"-related tasks: permanently cancel moving of died NPC
  406. * @param npc NPC to manage
  407. */
  408. public void onDeath(L2Npc npc)
  409. {
  410. cancelMoving(npc);
  411. }
  412. /**
  413. * Manage "on spawn"-related tasks: start NPC moving, if there is route attached to its spawn point
  414. * @param npc NPC to manage
  415. */
  416. public void onSpawn(L2Npc npc)
  417. {
  418. if (_routesToAttach.containsKey(npc.getId()))
  419. {
  420. final String routeName = _routesToAttach.get(npc.getId()).getRouteName(npc);
  421. if (!routeName.isEmpty())
  422. {
  423. startMoving(npc, routeName);
  424. }
  425. }
  426. }
  427. public static final WalkingManager getInstance()
  428. {
  429. return SingletonHolder._instance;
  430. }
  431. private static class SingletonHolder
  432. {
  433. protected static final WalkingManager _instance = new WalkingManager();
  434. }
  435. }