WalkingManager.java 16 KB

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