GeoPathFinding.java 14 KB

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