GeoPathFinding.java 13 KB

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