navigation_using_navigationpathqueryobjects.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. .. _doc_navigation_using_navigationpathqueryobjects:
  2. Using NavigationPathQueryObjects
  3. ================================
  4. .. tip::
  5. Path query parameters expose various options to improve pathfinding performance or lower memory consumption.
  6. They cater to more advanced pathfinding needs that the high-level nodes can not always cover.
  7. See the respective option sections below.
  8. ``NavigationPathQueryObjects`` can be used together with ``NavigationServer.query_path()``
  9. to obtain a heavily **customized** navigation path including optional **metadata** about the path.
  10. This requires more setup compared to obtaining a normal NavigationPath but lets you tailor
  11. the pathfinding and provided path data to the different needs of a project.
  12. NavigationPathQueryObjects consist of a pair of objects, a ``NavigationPathQueryParameters`` object holding the customization options
  13. for the query and a ``NavigationPathQueryResult`` that receives (regular) updates with the resulting path and metadata from the query.
  14. 2D and 3D versions of ``NavigationPathQueryParameters`` are available as
  15. :ref:`NavigationPathQueryParameters2D<class_NavigationPathQueryParameters2D>` and
  16. :ref:`NavigationPathQueryParameters3D<class_NavigationPathQueryParameters3D>` respectively.
  17. 2D and 3D versions of ``NavigationPathQueryResult`` are available as
  18. :ref:`NavigationPathQueryResult2D<class_NavigationPathQueryResult2D>` and
  19. :ref:`NavigationPathQueryResult3D<class_NavigationPathQueryResult3D>` respectively.
  20. Creating a basic path query
  21. ---------------------------
  22. Both parameters and result are used as a pair with the ``NavigationServer.query_path()`` function.
  23. For the available customization options, see further below. See also the descriptions for each parameter in the class reference.
  24. While not a strict requirement, both objects are intended to be created once in advance, stored in a
  25. persistent variable for the agent and reused for every followup path query with updated parameters.
  26. Reusing the same objects improves performance when frequently creating objects or allocating memory.
  27. The following script creates the objects and provides a ``query_path()`` function to create new navigation paths.
  28. The resulting path is identical to using ``NavigationServer.map_get_path()`` while reusing the objects.
  29. .. tabs::
  30. .. code-tab:: gdscript 2D GDScript
  31. extends Node2D
  32. # Prepare query objects.
  33. var query_parameters := NavigationPathQueryParameters2D.new()
  34. var query_result := NavigationPathQueryResult2D.new()
  35. func query_path(p_start_position: Vector2, p_target_position: Vector2, p_navigation_layers: int = 1) -> PackedVector2Array:
  36. if not is_inside_tree():
  37. return PackedVector2Array()
  38. var map: RID = get_world_2d().get_navigation_map()
  39. if NavigationServer2D.map_get_iteration_id(map) == 0:
  40. # This map has never synced and is empty, no point in querying it.
  41. return PackedVector2Array()
  42. query_parameters.map = map
  43. query_parameters.start_position = p_start_position
  44. query_parameters.target_position = p_target_position
  45. query_parameters.navigation_layers = p_navigation_layers
  46. NavigationServer2D.query_path(query_parameters, query_result)
  47. var path: PackedVector2Array = query_result.get_path()
  48. return path
  49. .. code-tab:: gdscript 3D GDScript
  50. extends Node3D
  51. # Prepare query objects.
  52. var query_parameters := NavigationPathQueryParameters3D.new()
  53. var query_result := NavigationPathQueryResult3D.new()
  54. func query_path(p_start_position: Vector3, p_target_position: Vector3, p_navigation_layers: int = 1) -> PackedVector3Array:
  55. if not is_inside_tree():
  56. return PackedVector3Array()
  57. var map: RID = get_world_3d().get_navigation_map()
  58. if NavigationServer3D.map_get_iteration_id(map) == 0:
  59. # This map has never synced and is empty, no point in querying it.
  60. return PackedVector3Array()
  61. query_parameters.map = map
  62. query_parameters.start_position = p_start_position
  63. query_parameters.target_position = p_target_position
  64. query_parameters.navigation_layers = p_navigation_layers
  65. NavigationServer3D.query_path(query_parameters, query_result)
  66. var path: PackedVector3Array = query_result.get_path()
  67. return path
  68. Path postprocessing options
  69. ---------------------------
  70. .. figure:: img/path_postprocess_diff.webp
  71. :align: center
  72. :alt: Path post-processing differences depending on navigation mesh polygon layout
  73. Path post-processing differences depending on navigation mesh polygon layout.
  74. A path query search travels from the closest navigation mesh polygon edge to the closest edge along the available polygons.
  75. If possible it builds a polygon corridor towards the target position polygon.
  76. This raw "search" polygon corridor path is not very optimized and usually a bad fit for agents to travel along.
  77. E.g. the closest edge point on a navigation mesh polygon might cause a huge detour for agents on larger polygons.
  78. In order to improve the quality of paths returned by the query various ``path_postprocessing`` options exist.
  79. - The ``PATH_POSTPROCESSING_CORRIDORFUNNEL`` post-processing shortens paths by funneling paths around corners **inside the available polygon corridor**.
  80. This is the default post-processing and usually also the most useful as it gives the shortest path result **inside the available polygon corridor**.
  81. If the polygon corridor is already suboptimal, e.g. due to a suboptimal navigation mesh layout,
  82. the funnel can snap to unexpected polygon corners causing detours.
  83. - The ``PATH_POSTPROCESSING_EDGECENTERED`` post-processing forces all path points to be placed in the middle of the crossed polygon edges **inside the available polygon corridor**.
  84. This post-processing is usually only useful when used with strictly tile-like navigation mesh polygons that are all
  85. evenly sized and where the expected path following is also constrained to cell centers,
  86. e.g. typical grid game with movement constrained to grid cell centers.
  87. - The ``PATH_POSTPROCESSING_NONE`` post-processing returns the path as is how the pathfinding traveled **inside the available polygon corridor**.
  88. This post-processing is very useful for debug as it shows how the path search traveled from closest edge point to closet edge point and what polygons it picked.
  89. A lot of unexpected or suboptimal path results can be immediately explained by looking at this raw path and polygon corridor.
  90. Path simplification
  91. -------------------
  92. .. tip::
  93. Path simplification can help steering agents or agents that jitter on thin polygon edges.
  94. .. figure:: img/path_simplification_diff.webp
  95. :align: center
  96. :alt: Path point difference with or without path simplification
  97. Path point difference with or without path simplification.
  98. If ``simplify_path`` is enabled a variant of the Ramer-Douglas-Peucker path simplification algorithm is applied to the path.
  99. This algorithm straightens paths by removing less relevant path points depending on the ``simplify_epsilon`` used.
  100. Path simplification helps with all kinds of agent movement problems in "open fields" that are caused by having many unnecessary polygon edges.
  101. E.g. a terrain mesh when baked to a navigation mesh can cause an excessive polygon count due to all the small (but for pathfinding almost meaningless) height variations in the terrain.
  102. Path simplification also helps with "steering" agents because they only have more critical corner path points to aim for.
  103. .. Warning::
  104. Path simplification is an additional final post-processing of the path. It adds extra performance costs to the query so only enable when actually needed.
  105. .. note::
  106. Path simplification is exposed on the NavigationServer as a generic function. It can be used outside of navigation queries for all kinds of position arrays as well.
  107. Path metadata
  108. -------------
  109. .. tip::
  110. Disabling unneeded path metadata options can improve performance and lower memory consumption.
  111. A path query can return additional metadata for every path point.
  112. - The ``PATH_METADATA_INCLUDE_TYPES`` flag collects an array with the primitive information about the point owners, e.g. if a point belongs to a region or link.
  113. - The ``PATH_METADATA_INCLUDE_RIDS`` flag collects an array with the :ref:`RIDs<class_RID>` of the point owners. Depending on point owner primitive, these RIDs can be used with the various NavigationServer functions related to regions or links.
  114. - The ``PATH_METADATA_INCLUDE_OWNERS`` flag collects an array with the ``ObjectIDs`` of the point owners. These object IDs can be used with :ref:`@GlobalScope.instance_from_id()<class_@GlobalScope_method_instance_from_id>` to retrieve the node behind that object instance, e.g. a NavigationRegion or NavigationLink node.
  115. By default all path metadata is collected as this metadata can be essential for more advanced navigation gameplay.
  116. - E.g. to know what path point maps to what object or node owner inside the SceneTree.
  117. - E.g. to know if a path point is the start or end of a navigation link that requires scripted takeover.
  118. For the most basic path uses metadata is not always needed.
  119. Path metadata collection can be selectively disabled to gain some performance and reduce memory consumption.
  120. Excluding or including regions
  121. ------------------------------
  122. .. tip::
  123. Region filters can greatly help with performance on large navigation maps that are region partitioned.
  124. Query parameters allow limiting the pathfinding to specific region navigation meshes.
  125. If a large navigation map is well partitioned into smaller regions this can greatly help with performance as the
  126. query can skip a large number of polygons at one of the earliest checks in the path search.
  127. - By default and if left empty all regions of the queried navigation map are included.
  128. - If a region :ref:`RID<class_RID>` is added to the ``excluded_regions`` array the region's navigation mesh will be ignored in the path search.
  129. - If a region :ref:`RID<class_RID>` is added to the ``included_regions`` array the region's navigation mesh will be considered in the path search and also all other regions not included will be ignored as well.
  130. - If a region ends up both included and excluded it is considered excluded.
  131. Region filters are very effective for performance when paired with navigation region chunks that are aligned on a grid.
  132. This way the filter can be set to only include the start position chunk and surrounding chunks instead of the entire navigation map.
  133. Even if the target might be outside these surrounding chunks (can always add more "rings") the pathfinding will
  134. try to create a path to the polygon closest to the target.
  135. This usually creates half-paths heading in the general direction that are good enough,
  136. all for a fraction of the performance cost of a full map search.
  137. The following addition to the basic path query script showcases the idea how to integrate a region chunk mapping with the region filters.
  138. This is not a full working example.
  139. .. tabs::
  140. .. code-tab:: gdscript 2D GDScript
  141. extends Node2D
  142. # ...
  143. var chunk_id_to_region_rid: Dictionary[Vector2i, RID] = {}
  144. func query_path(p_start_position: Vector2, p_target_position: Vector2, p_navigation_layers: int = 1) -> PackedVector2Array:
  145. # ...
  146. var regions_around_start_position: Array[RID] = []
  147. var chunk_rings: int = 1 # Increase for very small regions or more quality.
  148. var start_chunk_id: Vector2i = floor(p_start_position / float(chunk_size))
  149. for y: int in range(start_chunk_id.y - chunk_rings, start_chunk_id.y + chunk_rings):
  150. for x: int in range(start_chunk_id.x - chunk_rings, start_chunk_id.x + chunk_rings):
  151. var chunk_id: Vector2i = Vector2i(x, y)
  152. if chunk_id_to_region_rid.has(chunk_id):
  153. var region: RID = chunk_id_to_region_rid[chunk_id]
  154. regions_around_start_position.push_back(region)
  155. query_parameters.included_regions = regions_around_start_position
  156. # ...
  157. .. code-tab:: gdscript 3D GDScript
  158. extends Node3D
  159. # ...
  160. var chunk_id_to_region_rid: Dictionary[Vector3i, RID] = {}
  161. func query_path(p_start_position: Vector3, p_target_position: Vector3, p_navigation_layers: int = 1) -> PackedVector3Array:
  162. # ...
  163. var regions_around_start_position: Array[RID] = []
  164. var chunk_rings: int = 1 # Increase for very small regions or more quality.
  165. var start_chunk_id: Vector3i = floor(p_start_position / float(chunk_size))
  166. var y: int = 0 # Assume a planar navigation map for simplicity.
  167. for z: int in range(start_chunk_id.z - chunk_rings, start_chunk_id.z + chunk_rings):
  168. for x: int in range(start_chunk_id.x - chunk_rings, start_chunk_id.x + chunk_rings):
  169. var chunk_id: Vector3i = Vector3i(x, y, z)
  170. if chunk_id_to_region_rid.has(chunk_id):
  171. var region: RID = chunk_id_to_region_rid[chunk_id]
  172. regions_around_start_position.push_back(region)
  173. query_parameters.included_regions = regions_around_start_position
  174. # ...
  175. Path clipping and limits
  176. ------------------------
  177. .. tip::
  178. Sensibly set limits can greatly help with performance on large navigation maps, especially when targets end up being unreachable.
  179. .. figure:: img/path_clip_and_limits.gif
  180. :align: center
  181. :alt: Clipping returned paths to specific distances
  182. Clipping returned paths to specific distances.
  183. Query parameters allow clipping returned paths to specific lengths.
  184. These options clip the path as a part of post-processing. The path is still searched as if at full length,
  185. so it will have the same quality.
  186. Path length clipping can be helpful in creating paths that better fit constrained gameplay, e.g. tactical games with limited movement ranges.
  187. - The ``path_return_max_length`` property can be used to clip the returned path to a specific max length.
  188. - The ``path_return_max_radius`` property can be used to clip the returned path inside a circle (2D) or sphere (3D) radius around the start position.
  189. Query parameters allow limiting the path search to only search up to a specific distance or a specific number of searched polygons.
  190. These options are for performance and affect the path search directly.
  191. - The ``path_search_max_distance`` property can be used to stop the path search when going over this distance from the start position.
  192. - The ``path_search_max_polygons`` property can be used to stop the path search when going over this searched polygon number.
  193. When the path search is stopped by reaching a limit the path resets and creates a path from the start position polygon
  194. to the polygon found so far that is closest to the target position.
  195. .. warning::
  196. While good for performance, if path search limit values are set too low they can affect the path quality very negatively.
  197. Depending on polygon layout and search pattern the returned paths might go into completely wrong directions instead of the direction of the target.