GeoPathFinding.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright (C) 2004-2014 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.pathfinding.geonodes;
  20. import java.io.BufferedReader;
  21. import java.io.File;
  22. import java.io.FileReader;
  23. import java.io.LineNumberReader;
  24. import java.io.RandomAccessFile;
  25. import java.nio.ByteBuffer;
  26. import java.nio.IntBuffer;
  27. import java.nio.MappedByteBuffer;
  28. import java.nio.channels.FileChannel;
  29. import java.util.LinkedList;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.StringTokenizer;
  33. import java.util.logging.Level;
  34. import java.util.logging.Logger;
  35. import javolution.util.FastList;
  36. import javolution.util.FastMap;
  37. import com.l2jserver.Config;
  38. import com.l2jserver.gameserver.GeoData;
  39. import com.l2jserver.gameserver.model.L2World;
  40. import com.l2jserver.gameserver.model.Location;
  41. import com.l2jserver.gameserver.pathfinding.AbstractNode;
  42. import com.l2jserver.gameserver.pathfinding.AbstractNodeLoc;
  43. import com.l2jserver.gameserver.pathfinding.PathFinding;
  44. import com.l2jserver.gameserver.pathfinding.utils.FastNodeList;
  45. /**
  46. * @author -Nemesiss-
  47. */
  48. public class GeoPathFinding extends PathFinding
  49. {
  50. private static Logger _log = Logger.getLogger(GeoPathFinding.class.getName());
  51. private static Map<Short, ByteBuffer> _pathNodes = new FastMap<>();
  52. private static Map<Short, IntBuffer> _pathNodesIndex = new FastMap<>();
  53. public static GeoPathFinding getInstance()
  54. {
  55. return SingletonHolder._instance;
  56. }
  57. @Override
  58. public boolean pathNodesExist(short regionoffset)
  59. {
  60. return _pathNodesIndex.containsKey(regionoffset);
  61. }
  62. @Override
  63. public List<AbstractNodeLoc> findPath(int x, int y, int z, int tx, int ty, int tz, int instanceId, boolean playable)
  64. {
  65. int gx = (x - L2World.MAP_MIN_X) >> 4;
  66. int gy = (y - L2World.MAP_MIN_Y) >> 4;
  67. short gz = (short) z;
  68. int gtx = (tx - L2World.MAP_MIN_X) >> 4;
  69. int gty = (ty - L2World.MAP_MIN_Y) >> 4;
  70. short gtz = (short) tz;
  71. GeoNode start = readNode(gx, gy, gz);
  72. GeoNode end = readNode(gtx, gty, gtz);
  73. if ((start == null) || (end == null))
  74. {
  75. return null;
  76. }
  77. if (Math.abs(start.getLoc().getZ() - z) > 55)
  78. {
  79. return null; // not correct layer
  80. }
  81. if (Math.abs(end.getLoc().getZ() - tz) > 55)
  82. {
  83. return null; // not correct layer
  84. }
  85. if (start == end)
  86. {
  87. return null;
  88. }
  89. // TODO: Find closest path node we CAN access. Now only checks if we can not reach the closest
  90. Location temp = GeoData.getInstance().moveCheck(x, y, z, start.getLoc().getX(), start.getLoc().getY(), start.getLoc().getZ(), instanceId);
  91. if ((temp.getX() != start.getLoc().getX()) || (temp.getY() != start.getLoc().getY()))
  92. {
  93. return null; // cannot reach closest...
  94. }
  95. // TODO: Find closest path node around target, now only checks if final location can be reached
  96. temp = GeoData.getInstance().moveCheck(tx, ty, tz, end.getLoc().getX(), end.getLoc().getY(), end.getLoc().getZ(), instanceId);
  97. if ((temp.getX() != end.getLoc().getX()) || (temp.getY() != end.getLoc().getY()))
  98. {
  99. return null; // cannot reach closest...
  100. }
  101. // return searchAStar(start, end);
  102. return searchByClosest2(start, end);
  103. }
  104. public List<AbstractNodeLoc> searchByClosest2(GeoNode start, GeoNode end)
  105. {
  106. // Always continues checking from the closest to target non-blocked
  107. // node from to_visit list. There's extra length in path if needed
  108. // to go backwards/sideways but when moving generally forwards, this is extra fast
  109. // and accurate. And can reach insane distances (try it with 800 nodes..).
  110. // Minimum required node count would be around 300-400.
  111. // Generally returns a bit (only a bit) more intelligent looking routes than
  112. // the basic version. Not a true distance image (which would increase CPU
  113. // load) level of intelligence though.
  114. // List of Visited Nodes
  115. FastNodeList visited = new FastNodeList(550);
  116. // List of Nodes to Visit
  117. LinkedList<GeoNode> to_visit = new LinkedList<>();
  118. to_visit.add(start);
  119. int targetX = end.getLoc().getNodeX();
  120. int targetY = end.getLoc().getNodeY();
  121. int dx, dy;
  122. boolean added;
  123. int i = 0;
  124. while (i < 550)
  125. {
  126. GeoNode node;
  127. try
  128. {
  129. node = to_visit.removeFirst();
  130. }
  131. catch (Exception e)
  132. {
  133. // No Path found
  134. return null;
  135. }
  136. if (node.equals(end))
  137. {
  138. return constructPath2(node);
  139. }
  140. i++;
  141. visited.add(node);
  142. node.attachNeighbors();
  143. GeoNode[] neighbors = node.getNeighbors();
  144. if (neighbors == null)
  145. {
  146. continue;
  147. }
  148. for (GeoNode n : neighbors)
  149. {
  150. if (!visited.containsRev(n) && !to_visit.contains(n))
  151. {
  152. added = false;
  153. n.setParent(node);
  154. dx = targetX - n.getLoc().getNodeX();
  155. dy = targetY - n.getLoc().getNodeY();
  156. n.setCost((dx * dx) + (dy * dy));
  157. for (int index = 0; index < to_visit.size(); index++)
  158. {
  159. // supposed to find it quite early..
  160. if (to_visit.get(index).getCost() > n.getCost())
  161. {
  162. to_visit.add(index, n);
  163. added = true;
  164. break;
  165. }
  166. }
  167. if (!added)
  168. {
  169. to_visit.addLast(n);
  170. }
  171. }
  172. }
  173. }
  174. // No Path found
  175. return null;
  176. }
  177. public List<AbstractNodeLoc> constructPath2(AbstractNode node)
  178. {
  179. LinkedList<AbstractNodeLoc> path = new LinkedList<>();
  180. int previousDirectionX = -1000;
  181. int previousDirectionY = -1000;
  182. int directionX;
  183. int directionY;
  184. while (node.getParent() != null)
  185. {
  186. // only add a new route point if moving direction changes
  187. directionX = node.getLoc().getNodeX() - node.getParent().getLoc().getNodeX();
  188. directionY = node.getLoc().getNodeY() - node.getParent().getLoc().getNodeY();
  189. if ((directionX != previousDirectionX) || (directionY != previousDirectionY))
  190. {
  191. previousDirectionX = directionX;
  192. previousDirectionY = directionY;
  193. path.addFirst(node.getLoc());
  194. }
  195. node = node.getParent();
  196. }
  197. return path;
  198. }
  199. public GeoNode[] readNeighbors(GeoNode n, int idx)
  200. {
  201. int node_x = n.getLoc().getNodeX();
  202. int node_y = n.getLoc().getNodeY();
  203. // short node_z = n.getLoc().getZ();
  204. short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
  205. ByteBuffer pn = _pathNodes.get(regoffset);
  206. List<AbstractNode> Neighbors = new FastList<>(8);
  207. GeoNode newNode;
  208. short new_node_x, new_node_y;
  209. // Region for sure will change, we must read from correct file
  210. byte neighbor = pn.get(idx++); // N
  211. if (neighbor > 0)
  212. {
  213. neighbor--;
  214. new_node_x = (short) node_x;
  215. new_node_y = (short) (node_y - 1);
  216. newNode = readNode(new_node_x, new_node_y, neighbor);
  217. if (newNode != null)
  218. {
  219. Neighbors.add(newNode);
  220. }
  221. }
  222. neighbor = pn.get(idx++); // NE
  223. if (neighbor > 0)
  224. {
  225. neighbor--;
  226. new_node_x = (short) (node_x + 1);
  227. new_node_y = (short) (node_y - 1);
  228. newNode = readNode(new_node_x, new_node_y, neighbor);
  229. if (newNode != null)
  230. {
  231. Neighbors.add(newNode);
  232. }
  233. }
  234. neighbor = pn.get(idx++); // E
  235. if (neighbor > 0)
  236. {
  237. neighbor--;
  238. new_node_x = (short) (node_x + 1);
  239. new_node_y = (short) node_y;
  240. newNode = readNode(new_node_x, new_node_y, neighbor);
  241. if (newNode != null)
  242. {
  243. Neighbors.add(newNode);
  244. }
  245. }
  246. neighbor = pn.get(idx++); // SE
  247. if (neighbor > 0)
  248. {
  249. neighbor--;
  250. new_node_x = (short) (node_x + 1);
  251. new_node_y = (short) (node_y + 1);
  252. newNode = readNode(new_node_x, new_node_y, neighbor);
  253. if (newNode != null)
  254. {
  255. Neighbors.add(newNode);
  256. }
  257. }
  258. neighbor = pn.get(idx++); // S
  259. if (neighbor > 0)
  260. {
  261. neighbor--;
  262. new_node_x = (short) node_x;
  263. new_node_y = (short) (node_y + 1);
  264. newNode = readNode(new_node_x, new_node_y, neighbor);
  265. if (newNode != null)
  266. {
  267. Neighbors.add(newNode);
  268. }
  269. }
  270. neighbor = pn.get(idx++); // SW
  271. if (neighbor > 0)
  272. {
  273. neighbor--;
  274. new_node_x = (short) (node_x - 1);
  275. new_node_y = (short) (node_y + 1);
  276. newNode = readNode(new_node_x, new_node_y, neighbor);
  277. if (newNode != null)
  278. {
  279. Neighbors.add(newNode);
  280. }
  281. }
  282. neighbor = pn.get(idx++); // W
  283. if (neighbor > 0)
  284. {
  285. neighbor--;
  286. new_node_x = (short) (node_x - 1);
  287. new_node_y = (short) node_y;
  288. newNode = readNode(new_node_x, new_node_y, neighbor);
  289. if (newNode != null)
  290. {
  291. Neighbors.add(newNode);
  292. }
  293. }
  294. neighbor = pn.get(idx++); // NW
  295. if (neighbor > 0)
  296. {
  297. neighbor--;
  298. new_node_x = (short) (node_x - 1);
  299. new_node_y = (short) (node_y - 1);
  300. newNode = readNode(new_node_x, new_node_y, neighbor);
  301. if (newNode != null)
  302. {
  303. Neighbors.add(newNode);
  304. }
  305. }
  306. GeoNode[] result = new GeoNode[Neighbors.size()];
  307. return Neighbors.toArray(result);
  308. }
  309. // Private
  310. private GeoNode readNode(short node_x, short node_y, byte layer)
  311. {
  312. short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
  313. if (!pathNodesExist(regoffset))
  314. {
  315. return null;
  316. }
  317. short nbx = getNodeBlock(node_x);
  318. short nby = getNodeBlock(node_y);
  319. int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
  320. ByteBuffer pn = _pathNodes.get(regoffset);
  321. // reading
  322. byte nodes = pn.get(idx);
  323. idx += (layer * 10) + 1;// byte + layer*10byte
  324. if (nodes < layer)
  325. {
  326. _log.warning("SmthWrong!");
  327. }
  328. short node_z = pn.getShort(idx);
  329. idx += 2;
  330. return new GeoNode(new GeoNodeLoc(node_x, node_y, node_z), idx);
  331. }
  332. private GeoNode readNode(int gx, int gy, short z)
  333. {
  334. short node_x = getNodePos(gx);
  335. short node_y = getNodePos(gy);
  336. short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
  337. if (!pathNodesExist(regoffset))
  338. {
  339. return null;
  340. }
  341. short nbx = getNodeBlock(node_x);
  342. short nby = getNodeBlock(node_y);
  343. int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
  344. ByteBuffer pn = _pathNodes.get(regoffset);
  345. // reading
  346. byte nodes = pn.get(idx++);
  347. int idx2 = 0; // create index to nearlest node by z
  348. short last_z = Short.MIN_VALUE;
  349. while (nodes > 0)
  350. {
  351. short node_z = pn.getShort(idx);
  352. if (Math.abs(last_z - z) > Math.abs(node_z - z))
  353. {
  354. last_z = node_z;
  355. idx2 = idx + 2;
  356. }
  357. idx += 10; // short + 8 byte
  358. nodes--;
  359. }
  360. return new GeoNode(new GeoNodeLoc(node_x, node_y, last_z), idx2);
  361. }
  362. protected GeoPathFinding()
  363. {
  364. final File file = new File(Config.PATHNODE_DIR, "pn_index.txt");
  365. try (FileReader fr = new FileReader(file);
  366. BufferedReader br = new BufferedReader(fr);
  367. LineNumberReader lnr = new LineNumberReader(br))
  368. {
  369. _log.info("Path Engine: - Loading Path Nodes...");
  370. String line;
  371. while ((line = lnr.readLine()) != null)
  372. {
  373. if (line.trim().isEmpty())
  374. {
  375. continue;
  376. }
  377. StringTokenizer st = new StringTokenizer(line, "_");
  378. byte rx = Byte.parseByte(st.nextToken());
  379. byte ry = Byte.parseByte(st.nextToken());
  380. LoadPathNodeFile(rx, ry);
  381. }
  382. }
  383. catch (Exception e)
  384. {
  385. _log.log(Level.WARNING, "", e);
  386. throw new Error("Failed to Read pn_index File.");
  387. }
  388. }
  389. private void LoadPathNodeFile(byte rx, byte ry)
  390. {
  391. if ((rx < L2World.TILE_X_MIN) || (rx > L2World.TILE_X_MAX) || (ry < L2World.TILE_Y_MIN) || (ry > L2World.TILE_Y_MAX))
  392. {
  393. _log.warning("Failed to Load PathNode File: invalid region " + rx + "," + ry + Config.EOL);
  394. return;
  395. }
  396. short regionoffset = getRegionOffset(rx, ry);
  397. File file = new File(Config.PATHNODE_DIR, rx + "_" + ry + ".pn");
  398. _log.info("Path Engine: - Loading: " + file.getName() + " -> region offset: " + regionoffset + " X: " + rx + " Y: " + ry);
  399. int node = 0, size, index = 0;
  400. // Create a read-only memory-mapped file
  401. try (RandomAccessFile raf = new RandomAccessFile(file, "r");
  402. FileChannel roChannel = raf.getChannel())
  403. {
  404. size = (int) roChannel.size();
  405. MappedByteBuffer nodes;
  406. if (Config.FORCE_GEODATA)
  407. {
  408. // it is not guarantee, because the underlying operating system may have paged out some of the buffer's data
  409. nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
  410. }
  411. else
  412. {
  413. nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
  414. }
  415. // Indexing pathnode files, so we will know where each block starts
  416. IntBuffer indexs = IntBuffer.allocate(65536);
  417. while (node < 65536)
  418. {
  419. byte layer = nodes.get(index);
  420. indexs.put(node++, index);
  421. index += (layer * 10) + 1;
  422. }
  423. _pathNodesIndex.put(regionoffset, indexs);
  424. _pathNodes.put(regionoffset, nodes);
  425. }
  426. catch (Exception e)
  427. {
  428. _log.log(Level.WARNING, "Failed to Load PathNode File: " + file.getAbsolutePath() + " : " + e.getMessage(), e);
  429. }
  430. }
  431. private static class SingletonHolder
  432. {
  433. protected static final GeoPathFinding _instance = new GeoPathFinding();
  434. }
  435. }