vectors_advanced.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. .. _doc_vectors_advanced:
  2. Advanced Vector Math
  3. ====================
  4. Planes
  5. ~~~~~~
  6. The dot product has another interesting property with unit vectors.
  7. Imagine that perpendicular to that vector (and through the origin)
  8. passes a plane. Planes divide the entire space into positive
  9. (over the plane) and negative (under the plane), and (contrary to
  10. popular belief) you can also use their math in 2D:
  11. .. image:: img/tutovec10.png
  12. Unit vectors that are perpendicular to a surface (so, they describe the
  13. orientation of the surface) are called **unit normal vectors**. Though,
  14. usually they are just abbreviated as \*normals. Normals appear in
  15. planes, 3D geometry (to determine where each face or vertex is siding),
  16. etc. A **normal** *is* a **unit vector**, but it's called *normal*
  17. because of its usage. (Just like we call Origin to (0,0)!).
  18. It's as simple as it looks. The plane passes by the origin and the
  19. surface of it is perpendicular to the unit vector (or *normal*). The
  20. side towards the vector points to is the positive half-space, while the
  21. other side is the negative half-space. In 3D this is exactly the same,
  22. except that the plane is an infinite surface (imagine an infinite, flat
  23. sheet of paper that you can orient and is pinned to the origin) instead
  24. of a line.
  25. Distance to plane
  26. -----------------
  27. Now that it's clear what a plane is, let's go back to the dot product.
  28. The dot product between a **unit vector** and any **point in space**
  29. (yes, this time we do dot product between vector and position), returns
  30. the **distance from the point to the plane**:
  31. ::
  32. var distance = normal.dot(point)
  33. But not just the absolute distance, if the point is in the negative half
  34. space the distance will be negative, too:
  35. .. image:: img/tutovec11.png
  36. This allows us to tell which side of the plane a point is.
  37. Away from the origin
  38. --------------------
  39. I know what you are thinking! So far this is nice, but *real* planes are
  40. everywhere in space, not only passing through the origin. You want real
  41. *plane* action and you want it *now*.
  42. Remember that planes not only split space in two, but they also have
  43. *polarity*. This means that it is possible to have perfectly overlapping
  44. planes, but their negative and positive half-spaces are swapped.
  45. With this in mind, let's describe a full plane as a **normal** *N* and a
  46. **distance from the origin** scalar *D*. Thus, our plane is represented
  47. by N and D. For example:
  48. .. image:: img/tutovec12.png
  49. For 3D math, Godot provides a :ref:`Plane <class_Plane>`
  50. built-in type that handles this.
  51. Basically, N and D can represent any plane in space, be it for 2D or 3D
  52. (depending on the amount of dimensions of N) and the math is the same
  53. for both. It's the same as before, but D is the distance from the origin
  54. to the plane, travelling in N direction. As an example, imagine you want
  55. to reach a point in the plane, you will just do:
  56. ::
  57. var point_in_plane = N*D
  58. This will stretch (resize) the normal vector and make it touch the
  59. plane. This math might seem confusing, but it's actually much simpler
  60. than it seems. If we want to tell, again, the distance from the point to
  61. the plane, we do the same but adjusting for distance:
  62. ::
  63. var distance = N.dot(point) - D
  64. The same thing, using a built-in function:
  65. ::
  66. var distance = plane.distance_to(point)
  67. This will, again, return either a positive or negative distance.
  68. Flipping the polarity of the plane is also very simple, just negate both
  69. N and D. This will result in a plane in the same position, but with
  70. inverted negative and positive half spaces:
  71. ::
  72. N = -N
  73. D = -D
  74. Of course, Godot also implements this operator in :ref:`Plane <class_Plane>`,
  75. so doing:
  76. ::
  77. var inverted_plane = -plane
  78. Will work as expected.
  79. So, remember, a plane is just that and its main practical use is
  80. calculating the distance to it. So, why is it useful to calculate the
  81. distance from a point to a plane? It's extremely useful! Let's see some
  82. simple examples..
  83. Constructing a plane in 2D
  84. --------------------------
  85. Planes clearly don't come out of nowhere, so they must be built.
  86. Constructing them in 2D is easy, this can be done from either a normal
  87. (unit vector) and a point, or from two points in space.
  88. In the case of a normal and a point, most of the work is done, as the
  89. normal is already computed, so just calculate D from the dot product of
  90. the normal and the point.
  91. ::
  92. var N = normal
  93. var D = normal.dot(point)
  94. For two points in space, there are actually two planes that pass through
  95. them, sharing the same space but with normal pointing to the opposite
  96. directions. To compute the normal from the two points, the direction
  97. vector must be obtained first, and then it needs to be rotated 90°
  98. degrees to either side:
  99. ::
  100. # calculate vector from a to b
  101. var dvec = (point_b - point_a).normalized()
  102. # rotate 90 degrees
  103. var normal = Vector2(dvec.y, -dvec.x)
  104. # or alternatively
  105. # var normal = Vector2(-dvec.y, dvec.x)
  106. # depending the desired side of the normal
  107. The rest is the same as the previous example, either point_a or
  108. point_b will work since they are in the same plane:
  109. ::
  110. var N = normal
  111. var D = normal.dot(point_a)
  112. # this works the same
  113. # var D = normal.dot(point_b)
  114. Doing the same in 3D is a little more complex and will be explained
  115. further down.
  116. Some examples of planes
  117. -----------------------
  118. Here is a simple example of what planes are useful for. Imagine you have
  119. a `convex <http://www.mathsisfun.com/definitions/convex.html>`__
  120. polygon. For example, a rectangle, a trapezoid, a triangle, or just any
  121. polygon where no faces bend inwards.
  122. For every segment of the polygon, we compute the plane that passes by
  123. that segment. Once we have the list of planes, we can do neat things,
  124. for example checking if a point is inside the polygon.
  125. We go through all planes, if we can find a plane where the distance to
  126. the point is positive, then the point is outside the polygon. If we
  127. can't, then the point is inside.
  128. .. image:: img/tutovec13.png
  129. Code should be something like this:
  130. ::
  131. var inside = true
  132. for p in planes:
  133. # check if distance to plane is positive
  134. if (N.dot(point) - D > 0):
  135. inside = false
  136. break # with one that fails, it's enough
  137. Pretty cool, huh? But this gets much better! With a little more effort,
  138. similar logic will let us know when two convex polygons are overlapping
  139. too. This is called the Separating Axis Theorem (or SAT) and most
  140. physics engines use this to detect collision.
  141. The idea is really simple! With a point, just checking if a plane
  142. returns a positive distance is enough to tell if the point is outside.
  143. With another polygon, we must find a plane where *all* *the* ***other***
  144. *polygon* *points* return a positive distance to it. This check is
  145. performed with the planes of A against the points of B, and then with
  146. the planes of B against the points of A:
  147. .. image:: img/tutovec14.png
  148. Code should be something like this:
  149. ::
  150. var overlapping = true
  151. for p in planes_of_A:
  152. var all_out = true
  153. for v in points_of_B:
  154. if (p.distance_to(v) < 0):
  155. all_out = false
  156. break
  157. if (all_out):
  158. # a separating plane was found
  159. # do not continue testing
  160. overlapping = false
  161. break
  162. if (overlapping):
  163. # only do this check if no separating plane
  164. # was found in planes of A
  165. for p in planes_of_B:
  166. var all_out = true
  167. for v in points_of_A:
  168. if (p.distance_to(v) < 0):
  169. all_out = false
  170. break
  171. if (all_out):
  172. overlapping = false
  173. break
  174. if (overlapping):
  175. print("Polygons Collided!")
  176. As you can see, planes are quite useful, and this is the tip of the
  177. iceberg. You might be wondering what happens with non convex polygons.
  178. This is usually just handled by splitting the concave polygon into
  179. smaller convex polygons, or using a technique such as BSP (which is not
  180. used much nowadays).
  181. Collision detection in 3D
  182. ~~~~~~~~~~~~~~~~~~~~~~~~~
  183. This is another bonus bit, a reward for being patient and keeping up
  184. with this long tutorial. Here is another piece of wisdom. This might
  185. not be something with a direct use case (Godot already does collision
  186. detection pretty well) but It's a really cool algorithm to understand
  187. anyway, because it's used by almost all physics engines and collision
  188. detection libraries :)
  189. Remember that converting a convex shape in 2D to an array of 2D planes
  190. was useful for collision detection? You could detect if a point was
  191. inside any convex shape, or if two 2D convex shapes were overlapping.
  192. Well, this works in 3D too, if two 3D polyhedral shapes are colliding,
  193. you won't be able to find a separating plane. If a separating plane is
  194. found, then the shapes are definitely not colliding.
  195. To refresh a bit a separating plane means that all vertices of polygon A
  196. are in one side of the plane, and all vertices of polygon B are in the
  197. other side. This plane is always one of the face-planes of either
  198. polygon A or polygon B.
  199. In 3D though, there is a problem to this approach, because it is
  200. possible that, in some cases a separating plane can't be found. This is
  201. an example of such situation:
  202. .. image:: img/tutovec22.png
  203. To avoid it, some extra planes need to be tested as separators, these
  204. planes are the cross product between the edges of polygon A and the
  205. edges of polygon B
  206. .. image:: img/tutovec23.png
  207. So the final algorithm is something like:
  208. ::
  209. var overlapping = true
  210. for p in planes_of_A:
  211. var all_out = true
  212. for v in points_of_B:
  213. if (p.distance_to(v) < 0):
  214. all_out = false
  215. break
  216. if (all_out):
  217. # a separating plane was found
  218. # do not continue testing
  219. overlapping = false
  220. break
  221. if (overlapping):
  222. # only do this check if no separating plane
  223. # was found in planes of A
  224. for p in planes_of_B:
  225. var all_out = true
  226. for v in points_of_A:
  227. if (p.distance_to(v) < 0):
  228. all_out = false
  229. break
  230. if (all_out):
  231. overlapping = false
  232. break
  233. if (overlapping):
  234. for ea in edges_of_A:
  235. for eb in edges_of_B:
  236. var n = ea.cross(eb)
  237. if (n.length() == 0):
  238. continue
  239. var max_A = -1e20 # tiny number
  240. var min_A = 1e20 # huge number
  241. # we are using the dot product directly
  242. # so we can map a maximum and minimum range
  243. # for each polygon, then check if they
  244. # overlap.
  245. for v in points_of_A:
  246. var d = n.dot(v)
  247. if (d > max_A):
  248. max_A = d
  249. if (d < min_A):
  250. min_A = d
  251. var max_B = -1e20 # tiny number
  252. var min_B = 1e20 # huge number
  253. for v in points_of_B:
  254. var d = n.dot(v)
  255. if (d > max_B):
  256. max_B = d
  257. if (d < min_B):
  258. min_B = d
  259. if (min_A > max_B or min_B > max_A):
  260. # not overlapping!
  261. overlapping = false
  262. break
  263. if (not overlapping):
  264. break
  265. if (overlapping):
  266. print("Polygons collided!")