WalkingManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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.ArrivedTask;
  30. import com.l2jserver.gameserver.model.L2CharPosition;
  31. import com.l2jserver.gameserver.model.L2NpcWalkerNode;
  32. import com.l2jserver.gameserver.model.L2WalkRoute;
  33. import com.l2jserver.gameserver.model.Location;
  34. import com.l2jserver.gameserver.model.WalkInfo;
  35. import com.l2jserver.gameserver.model.actor.L2Npc;
  36. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  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 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. String chatString = null;
  114. NpcStringId npcString = 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() + ".");
  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() + ".");
  141. continue;
  142. }
  143. }
  144. }
  145. }
  146. list.add(new L2NpcWalkerNode(0, npcString, chatString, x, y, z, delay, parseBoolean(attrs, "run")));
  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 = 0, y = 0, z = 0;
  155. x = Integer.parseInt(attrs.getNamedItem("spawnX").getNodeValue());
  156. y = Integer.parseInt(attrs.getNamedItem("spawnY").getNodeValue());
  157. 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("Walking Manager: 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. 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. 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.getMoveX()) && (npc.getY() == node.getMoveY()))
  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.getMoveX(), node.getMoveY(), node.getMoveZ(), 3000, true, false))
  249. {
  250. npc.sendDebugMessage("Route " + routeName + ", NPC is too far from starting point, walking will no start");
  251. return;
  252. }
  253. npc.sendDebugMessage("Starting to move at route " + routeName);
  254. npc.setIsRunning(node.getRunning());
  255. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  256. walk.setWalkCheckTask(ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new Runnable()
  257. {
  258. @Override
  259. public void run()
  260. {
  261. startMoving(npc, routeName);
  262. }
  263. }, 60000, 60000)); // start walk check task, for resuming walk after fight
  264. npc.getKnownList().startTrackingTask();
  265. _activeRoutes.put(npc.getObjectId(), walk); // register route
  266. }
  267. else
  268. {
  269. npc.sendDebugMessage("Trying to start move at route " + routeName + ", but cannot now, scheduled");
  270. ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  271. {
  272. @Override
  273. public void run()
  274. {
  275. startMoving(npc, routeName);
  276. }
  277. }, 60000);
  278. }
  279. }
  280. else
  281. // walk was stopped due to some reason (arrived to node, script action, fight or something else), resume it
  282. {
  283. if (_activeRoutes.containsKey(npc.getObjectId()) && ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE)))
  284. {
  285. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  286. // Prevent call simultaneously from scheduled task and onArrived() or temporarily stop walking for resuming in future
  287. if (walk.isBlocked() || walk.isSuspended())
  288. {
  289. npc.sendDebugMessage("Trying continue to move at route " + routeName + ", but cannot now (operation is blocked)");
  290. return;
  291. }
  292. walk.setBlocked(true);
  293. L2NpcWalkerNode node = walk.getCurrentNode();
  294. npc.sendDebugMessage("Route id: " + routeName + ", continue to node " + walk.getCurrentNodeId());
  295. npc.setIsRunning(node.getRunning());
  296. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  297. walk.setBlocked(false);
  298. walk.setStoppedByAttack(false);
  299. }
  300. else
  301. {
  302. npc.sendDebugMessage("Trying continue to move at route " + routeName + ", but cannot now (wrong AI state)");
  303. }
  304. }
  305. }
  306. }
  307. /**
  308. * Cancel NPC moving permanently
  309. * @param npc NPC to cancel
  310. */
  311. public synchronized void cancelMoving(L2Npc npc)
  312. {
  313. if (_activeRoutes.containsKey(npc.getObjectId()))
  314. {
  315. final WalkInfo walk = _activeRoutes.remove(npc.getObjectId());
  316. walk.getWalkCheckTask().cancel(true);
  317. npc.getKnownList().stopTrackingTask();
  318. }
  319. }
  320. /**
  321. * Resumes previously stopped moving
  322. * @param npc NPC to resume
  323. */
  324. public void resumeMoving(final L2Npc npc)
  325. {
  326. if (!_activeRoutes.containsKey(npc.getObjectId()))
  327. {
  328. return;
  329. }
  330. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  331. walk.setSuspended(false);
  332. walk.setStoppedByAttack(false);
  333. startMoving(npc, walk.getRoute().getName());
  334. }
  335. /**
  336. * Pause NPC moving until it will be resumed
  337. * @param npc NPC to pause moving
  338. * @param suspend {@code true} if moving was temporarily suspended for some reasons of AI-controlling script
  339. * @param stoppedByAttack {@code true} if moving was suspended because of NPC was attacked or desired to attack
  340. */
  341. public void stopMoving(L2Npc npc, boolean suspend, boolean stoppedByAttack)
  342. {
  343. L2MonsterInstance monster = null;
  344. if (npc.isMonster())
  345. {
  346. if (((L2MonsterInstance) npc).getLeader() == null)
  347. {
  348. monster = (L2MonsterInstance) npc;
  349. }
  350. else
  351. {
  352. monster = ((L2MonsterInstance) npc).getLeader();
  353. }
  354. }
  355. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  356. {
  357. return;
  358. }
  359. WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  360. walk.setSuspended(suspend);
  361. walk.setStoppedByAttack(stoppedByAttack);
  362. if (monster != null)
  363. {
  364. monster.stopMove(null);
  365. monster.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  366. }
  367. else
  368. {
  369. npc.stopMove(null);
  370. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  371. }
  372. }
  373. /**
  374. * Manage "node arriving"-related tasks: schedule move to next node; send ON_NODE_ARRIVED event to Quest script
  375. * @param npc NPC to manage
  376. */
  377. public void onArrived(final L2Npc npc)
  378. {
  379. if (_activeRoutes.containsKey(npc.getObjectId()))
  380. {
  381. // Notify quest
  382. if (npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED) != null)
  383. {
  384. for (Quest quest : npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED))
  385. {
  386. quest.notifyNodeArrived(npc);
  387. }
  388. }
  389. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  390. // Opposite should not happen... but happens sometime
  391. if ((walk.getCurrentNodeId() >= 0) && (walk.getCurrentNodeId() < walk.getRoute().getNodesCount()))
  392. {
  393. L2NpcWalkerNode node = walk.getRoute().getNodeList().get(walk.getCurrentNodeId());
  394. if (npc.isInsideRadius(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 10, false, false))
  395. {
  396. npc.sendDebugMessage("Route: " + walk.getRoute().getName() + ", arrived to node " + walk.getCurrentNodeId());
  397. npc.sendDebugMessage("Done in " + ((System.currentTimeMillis() - walk.getLastAction()) / 1000) + " s.");
  398. walk.calculateNextNode(npc);
  399. int delay = node.getDelay();
  400. walk.setBlocked(true); // prevents to be ran from walk check task, if there is delay in this node.
  401. if (node.getNpcString() != null)
  402. {
  403. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, node.getNpcString()));
  404. }
  405. else
  406. {
  407. final String text = node.getChatText();
  408. if ((text != null) && !text.isEmpty())
  409. {
  410. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, text));
  411. }
  412. }
  413. if (npc.isDebug())
  414. {
  415. walk.setLastAction(System.currentTimeMillis());
  416. }
  417. ThreadPoolManager.getInstance().scheduleGeneral(new ArrivedTask(npc, walk), 100 + (delay * 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. }