WalkingManager.java 16 KB

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