WalkingManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. String chatString = null;
  113. NpcStringId npcString = null;
  114. Node node = attrs.getNamedItem("string");
  115. if (node != null)
  116. {
  117. chatString = node.getNodeValue();
  118. }
  119. else
  120. {
  121. node = attrs.getNamedItem("npcString");
  122. if (node != null)
  123. {
  124. npcString = NpcStringId.getNpcStringId(node.getNodeValue());
  125. if (npcString == null)
  126. {
  127. _log.warning(getClass().getSimpleName() + ": Unknown npcstring '" + node.getNodeValue() + ".");
  128. continue;
  129. }
  130. }
  131. else
  132. {
  133. node = attrs.getNamedItem("npcStringId");
  134. if (node != null)
  135. {
  136. npcString = NpcStringId.getNpcStringId(Integer.parseInt(node.getNodeValue()));
  137. if (npcString == null)
  138. {
  139. _log.warning(getClass().getSimpleName() + ": Unknown npcstring '" + node.getNodeValue() + ".");
  140. continue;
  141. }
  142. }
  143. }
  144. }
  145. list.add(new L2NpcWalkerNode(0, npcString, chatString, x, y, z, delay, parseBoolean(attrs, "run")));
  146. }
  147. else if (r.getNodeName().equals("target"))
  148. {
  149. NamedNodeMap attrs = r.getAttributes();
  150. try
  151. {
  152. int npcId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
  153. int x = 0, y = 0, z = 0;
  154. x = Integer.parseInt(attrs.getNamedItem("spawnX").getNodeValue());
  155. y = Integer.parseInt(attrs.getNamedItem("spawnY").getNodeValue());
  156. 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("Walking Manager: 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.getMoveX()) && (npc.getY() == node.getMoveY()))
  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.getMoveX(), node.getMoveY(), node.getMoveZ(), 3000, true, false))
  248. {
  249. npc.sendDebugMessage("Route " + routeName + ", NPC is too far from starting point, walking will no start");
  250. return;
  251. }
  252. npc.sendDebugMessage("Starting to move at route " + routeName);
  253. npc.setIsRunning(node.getRunning());
  254. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new Location(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  255. walk.setWalkCheckTask(ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new Runnable()
  256. {
  257. @Override
  258. public void run()
  259. {
  260. startMoving(npc, routeName);
  261. }
  262. }, 60000, 60000)); // start walk check task, for resuming walk after fight
  263. npc.getKnownList().startTrackingTask();
  264. _activeRoutes.put(npc.getObjectId(), walk); // register route
  265. }
  266. else
  267. {
  268. npc.sendDebugMessage("Trying to start move at route " + routeName + ", but cannot now, scheduled");
  269. ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  270. {
  271. @Override
  272. public void run()
  273. {
  274. startMoving(npc, routeName);
  275. }
  276. }, 60000);
  277. }
  278. }
  279. else
  280. // walk was stopped due to some reason (arrived to node, script action, fight or something else), resume it
  281. {
  282. if (_activeRoutes.containsKey(npc.getObjectId()) && ((npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE) || (npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_IDLE)))
  283. {
  284. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  285. if (walk == null)
  286. {
  287. return;
  288. }
  289. // Prevent call simultaneously from scheduled task and onArrived() or temporarily stop walking for resuming in future
  290. if (walk.isBlocked() || walk.isSuspended())
  291. {
  292. npc.sendDebugMessage("Trying continue to move at route " + routeName + ", but cannot now (operation is blocked)");
  293. return;
  294. }
  295. walk.setBlocked(true);
  296. L2NpcWalkerNode node = walk.getCurrentNode();
  297. npc.sendDebugMessage("Route id: " + routeName + ", continue to node " + walk.getCurrentNodeId());
  298. npc.setIsRunning(node.getRunning());
  299. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new Location(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 0));
  300. walk.setBlocked(false);
  301. walk.setStoppedByAttack(false);
  302. }
  303. else
  304. {
  305. npc.sendDebugMessage("Trying continue to move at route " + routeName + ", but cannot now (wrong AI state)");
  306. }
  307. }
  308. }
  309. }
  310. /**
  311. * Cancel NPC moving permanently
  312. * @param npc NPC to cancel
  313. */
  314. public synchronized void cancelMoving(L2Npc npc)
  315. {
  316. if (_activeRoutes.containsKey(npc.getObjectId()))
  317. {
  318. final WalkInfo walk = _activeRoutes.remove(npc.getObjectId());
  319. walk.getWalkCheckTask().cancel(true);
  320. npc.getKnownList().stopTrackingTask();
  321. }
  322. }
  323. /**
  324. * Resumes previously stopped moving
  325. * @param npc NPC to resume
  326. */
  327. public void resumeMoving(final L2Npc npc)
  328. {
  329. if (!_activeRoutes.containsKey(npc.getObjectId()))
  330. {
  331. return;
  332. }
  333. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  334. walk.setSuspended(false);
  335. walk.setStoppedByAttack(false);
  336. startMoving(npc, walk.getRoute().getName());
  337. }
  338. /**
  339. * Pause NPC moving until it will be resumed
  340. * @param npc NPC to pause moving
  341. * @param suspend {@code true} if moving was temporarily suspended for some reasons of AI-controlling script
  342. * @param stoppedByAttack {@code true} if moving was suspended because of NPC was attacked or desired to attack
  343. */
  344. public void stopMoving(L2Npc npc, boolean suspend, boolean stoppedByAttack)
  345. {
  346. L2MonsterInstance monster = null;
  347. if (npc.isMonster())
  348. {
  349. if (((L2MonsterInstance) npc).getLeader() == null)
  350. {
  351. monster = (L2MonsterInstance) npc;
  352. }
  353. else
  354. {
  355. monster = ((L2MonsterInstance) npc).getLeader();
  356. }
  357. }
  358. if (((monster != null) && !isRegistered(monster)) || !isRegistered(npc))
  359. {
  360. return;
  361. }
  362. WalkInfo walk = monster != null ? _activeRoutes.get(monster.getObjectId()) : _activeRoutes.get(npc.getObjectId());
  363. walk.setSuspended(suspend);
  364. walk.setStoppedByAttack(stoppedByAttack);
  365. if (monster != null)
  366. {
  367. monster.stopMove(null);
  368. monster.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  369. }
  370. else
  371. {
  372. npc.stopMove(null);
  373. npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  374. }
  375. }
  376. /**
  377. * Manage "node arriving"-related tasks: schedule move to next node; send ON_NODE_ARRIVED event to Quest script
  378. * @param npc NPC to manage
  379. */
  380. public void onArrived(final L2Npc npc)
  381. {
  382. if (_activeRoutes.containsKey(npc.getObjectId()))
  383. {
  384. // Notify quest
  385. if (npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED) != null)
  386. {
  387. for (Quest quest : npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_NODE_ARRIVED))
  388. {
  389. quest.notifyNodeArrived(npc);
  390. }
  391. }
  392. WalkInfo walk = _activeRoutes.get(npc.getObjectId());
  393. // Opposite should not happen... but happens sometime
  394. if ((walk.getCurrentNodeId() >= 0) && (walk.getCurrentNodeId() < walk.getRoute().getNodesCount()))
  395. {
  396. L2NpcWalkerNode node = walk.getRoute().getNodeList().get(walk.getCurrentNodeId());
  397. if (npc.isInsideRadius(node.getMoveX(), node.getMoveY(), node.getMoveZ(), 10, false, false))
  398. {
  399. npc.sendDebugMessage("Route: " + walk.getRoute().getName() + ", arrived to node " + walk.getCurrentNodeId());
  400. npc.sendDebugMessage("Done in " + ((System.currentTimeMillis() - walk.getLastAction()) / 1000) + " s.");
  401. walk.calculateNextNode(npc);
  402. int delay = node.getDelay();
  403. walk.setBlocked(true); // prevents to be ran from walk check task, if there is delay in this node.
  404. if (node.getNpcString() != null)
  405. {
  406. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, node.getNpcString()));
  407. }
  408. else
  409. {
  410. final String text = node.getChatText();
  411. if ((text != null) && !text.isEmpty())
  412. {
  413. Broadcast.toKnownPlayers(npc, new NpcSay(npc, Say2.NPC_ALL, text));
  414. }
  415. }
  416. if (npc.isDebug())
  417. {
  418. walk.setLastAction(System.currentTimeMillis());
  419. }
  420. ThreadPoolManager.getInstance().scheduleGeneral(new ArrivedTask(npc, walk), 100 + (delay * 1000L));
  421. }
  422. }
  423. }
  424. }
  425. /**
  426. * Manage "on death"-related tasks: permanently cancel moving of died NPC
  427. * @param npc NPC to manage
  428. */
  429. public void onDeath(L2Npc npc)
  430. {
  431. cancelMoving(npc);
  432. }
  433. /**
  434. * Manage "on spawn"-related tasks: start NPC moving, if there is route attached to its spawn point
  435. * @param npc NPC to manage
  436. */
  437. public void onSpawn(L2Npc npc)
  438. {
  439. if (_routesToAttach.containsKey(npc.getNpcId()))
  440. {
  441. final String routeName = _routesToAttach.get(npc.getNpcId()).getRouteName(npc);
  442. if (!routeName.isEmpty())
  443. {
  444. startMoving(npc, routeName);
  445. }
  446. }
  447. }
  448. public static final WalkingManager getInstance()
  449. {
  450. return SingletonHolder._instance;
  451. }
  452. private static class SingletonHolder
  453. {
  454. protected static final WalkingManager _instance = new WalkingManager();
  455. }
  456. }