Ray.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "BoundingBox.h"
  24. #include "Frustum.h"
  25. #include "Plane.h"
  26. #include "Ray.h"
  27. #include "Sphere.h"
  28. namespace Urho3D
  29. {
  30. Vector3 Ray::Project(const Vector3& point) const
  31. {
  32. Vector3 offset = point - origin_;
  33. return origin_ + offset.DotProduct(direction_) * direction_;
  34. }
  35. float Ray::Distance(const Vector3& point) const
  36. {
  37. Vector3 projected = Project(point);
  38. return (point - projected).Length();
  39. }
  40. Vector3 Ray::ClosestPoint(const Ray& ray) const
  41. {
  42. // Algorithm based on http://paulbourke.net/geometry/lineline3d/
  43. Vector3 p13 = origin_ - ray.origin_;
  44. Vector3 p43 = ray.direction_;
  45. Vector3 p21 = direction_;
  46. float d1343 = p13.DotProduct(p43);
  47. float d4321 = p43.DotProduct(p21);
  48. float d1321 = p13.DotProduct(p21);
  49. float d4343 = p43.DotProduct(p43);
  50. float d2121 = p21.DotProduct(p21);
  51. float d = d2121 * d4343 - d4321 * d4321;
  52. if (Abs(d) < M_EPSILON)
  53. return origin_;
  54. float n = d1343 * d4321 - d1321 * d4343;
  55. float a = n / d;
  56. return origin_ + a * direction_;
  57. }
  58. float Ray::HitDistance(const Plane& plane) const
  59. {
  60. float d = plane.normal_.DotProduct(direction_);
  61. if (Abs(d) >= M_EPSILON)
  62. {
  63. float t = -(plane.normal_.DotProduct(origin_) - plane.intercept_) / d;
  64. if (t >= 0.0f)
  65. return t;
  66. else
  67. return M_INFINITY;
  68. }
  69. else
  70. return M_INFINITY;
  71. }
  72. float Ray::HitDistance(const BoundingBox& box) const
  73. {
  74. // If undefined, no hit (infinite distance)
  75. if (!box.defined_)
  76. return M_INFINITY;
  77. // Check for ray origin being inside the box
  78. if (box.IsInside(origin_))
  79. return 0.0f;
  80. float dist = M_INFINITY;
  81. // Check for intersecting in the X-direction
  82. if (origin_.x_ < box.min_.x_ && direction_.x_ > 0.0f)
  83. {
  84. float x = (box.min_.x_ - origin_.x_) / direction_.x_;
  85. if (x < dist)
  86. {
  87. Vector3 point = origin_ + x * direction_;
  88. if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  89. dist = x;
  90. }
  91. }
  92. if (origin_.x_ > box.max_.x_ && direction_.x_ < 0.0f)
  93. {
  94. float x = (box.max_.x_ - origin_.x_) / direction_.x_;
  95. if (x < dist)
  96. {
  97. Vector3 point = origin_ + x * direction_;
  98. if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  99. dist = x;
  100. }
  101. }
  102. // Check for intersecting in the Y-direction
  103. if (origin_.y_ < box.min_.y_ && direction_.y_ > 0.0f)
  104. {
  105. float x = (box.min_.y_ - origin_.y_) / direction_.y_;
  106. if (x < dist)
  107. {
  108. Vector3 point = origin_ + x * direction_;
  109. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  110. dist = x;
  111. }
  112. }
  113. if (origin_.y_ > box.max_.y_ && direction_.y_ < 0.0f)
  114. {
  115. float x = (box.max_.y_ - origin_.y_) / direction_.y_;
  116. if (x < dist)
  117. {
  118. Vector3 point = origin_ + x * direction_;
  119. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  120. dist = x;
  121. }
  122. }
  123. // Check for intersecting in the Z-direction
  124. if (origin_.z_ < box.min_.z_ && direction_.z_ > 0.0f)
  125. {
  126. float x = (box.min_.z_ - origin_.z_) / direction_.z_;
  127. if (x < dist)
  128. {
  129. Vector3 point = origin_ + x * direction_;
  130. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
  131. dist = x;
  132. }
  133. }
  134. if (origin_.z_ > box.max_.z_ && direction_.z_ < 0.0f)
  135. {
  136. float x = (box.max_.z_ - origin_.z_) / direction_.z_;
  137. if (x < dist)
  138. {
  139. Vector3 point = origin_ + x * direction_;
  140. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
  141. dist = x;
  142. }
  143. }
  144. return dist;
  145. }
  146. float Ray::HitDistance(const Frustum& frustum, bool solidInside) const
  147. {
  148. float maxOutside = 0.0f;
  149. float minInside = M_INFINITY;
  150. bool allInside = true;
  151. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  152. {
  153. const Plane& plane = frustum.planes_[i];
  154. float distance = HitDistance(frustum.planes_[i]);
  155. if (plane.Distance(origin_) < 0.0f)
  156. {
  157. maxOutside = Max(maxOutside, distance);
  158. allInside = false;
  159. }
  160. else
  161. minInside = Min(minInside, distance);
  162. }
  163. if (allInside)
  164. return solidInside ? 0.0f : minInside;
  165. else if (maxOutside <= minInside)
  166. return maxOutside;
  167. else
  168. return M_INFINITY;
  169. }
  170. float Ray::HitDistance(const Sphere& sphere) const
  171. {
  172. Vector3 centeredOrigin = origin_ - sphere.center_;
  173. float squaredRadius = sphere.radius_ * sphere.radius_;
  174. // Check if ray originates inside the sphere
  175. if (centeredOrigin.LengthSquared() <= squaredRadius)
  176. return 0.0f;
  177. // Calculate intersection by quadratic equation
  178. float a = direction_.DotProduct(direction_);
  179. float b = 2.0f * centeredOrigin.DotProduct(direction_);
  180. float c = centeredOrigin.DotProduct(centeredOrigin) - squaredRadius;
  181. float d = b * b - 4.0f * a * c;
  182. // No solution
  183. if (d < 0.0f)
  184. return M_INFINITY;
  185. // Get the nearer solution
  186. float dSqrt = sqrtf(d);
  187. float dist = (-b - dSqrt) / (2.0f * a);
  188. if (dist >= 0.0f)
  189. return dist;
  190. else
  191. return (-b + dSqrt) / (2.0f * a);
  192. }
  193. float Ray::HitDistance(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
  194. {
  195. // Based on Fast, Minimum Storage Ray/Triangle Intersection by Möller & Trumbore
  196. // http://www.graphics.cornell.edu/pubs/1997/MT97.pdf
  197. // Calculate edge vectors
  198. Vector3 edge1(v1 - v0);
  199. Vector3 edge2(v2 - v0);
  200. // Calculate determinant & check backfacing
  201. Vector3 p(direction_.CrossProduct(edge2));
  202. float det = edge1.DotProduct(p);
  203. if (det >= M_EPSILON)
  204. {
  205. // Calculate u & v parameters and test
  206. Vector3 t(origin_ - v0);
  207. float u = t.DotProduct(p);
  208. if (u >= 0.0f && u <= det)
  209. {
  210. Vector3 q(t.CrossProduct(edge1));
  211. float v = direction_.DotProduct(q);
  212. if (v >= 0.0f && u + v <= det)
  213. {
  214. // There is an intersection, so calculate distance
  215. return edge2.DotProduct(q) / det;
  216. }
  217. }
  218. }
  219. return M_INFINITY;
  220. }
  221. float Ray::HitDistance(const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount) const
  222. {
  223. float nearest = M_INFINITY;
  224. const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
  225. unsigned index = 0;
  226. while (index + 2 < vertexCount)
  227. {
  228. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexSize]));
  229. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexSize]));
  230. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexSize]));
  231. nearest = Min(nearest, HitDistance(v0, v1, v2));
  232. index += 3;
  233. }
  234. return nearest;
  235. }
  236. float Ray::HitDistance(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize,
  237. unsigned indexStart, unsigned indexCount) const
  238. {
  239. float nearest = M_INFINITY;
  240. const unsigned char* vertices = (const unsigned char*)vertexData;
  241. // 16-bit indices
  242. if (indexSize == sizeof(unsigned short))
  243. {
  244. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  245. const unsigned short* indicesEnd = indices + indexCount;
  246. while (indices < indicesEnd)
  247. {
  248. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  249. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  250. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  251. nearest = Min(nearest, HitDistance(v0, v1, v2));
  252. indices += 3;
  253. }
  254. }
  255. // 32-bit indices
  256. else
  257. {
  258. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  259. const unsigned* indicesEnd = indices + indexCount;
  260. while (indices < indicesEnd)
  261. {
  262. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  263. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  264. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  265. nearest = Min(nearest, HitDistance(v0, v1, v2));
  266. indices += 3;
  267. }
  268. }
  269. return nearest;
  270. }
  271. bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount) const
  272. {
  273. float currentFrontFace = M_INFINITY;
  274. float currentBackFace = M_INFINITY;
  275. const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
  276. unsigned index = 0;
  277. while (index + 2 < vertexCount)
  278. {
  279. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexSize]));
  280. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexSize]));
  281. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexSize]));
  282. float frontFaceDistance = HitDistance(v0, v1, v2);
  283. float backFaceDistance = HitDistance(v2, v1, v0);
  284. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  285. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  286. // checking reversed frontfaces
  287. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  288. index += 3;
  289. }
  290. // If the closest face is a backface, that means that the ray originates from the inside of the geometry
  291. // NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
  292. // (ray doesnt hit either) by this conditional
  293. if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
  294. return currentBackFace < currentFrontFace;
  295. // It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
  296. // As such, it is safe to assume they are not
  297. return false;
  298. }
  299. bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize,
  300. unsigned indexStart, unsigned indexCount) const
  301. {
  302. float currentFrontFace = M_INFINITY;
  303. float currentBackFace = M_INFINITY;
  304. const unsigned char* vertices = (const unsigned char*)vertexData;
  305. // 16-bit indices
  306. if (indexSize == sizeof(unsigned short))
  307. {
  308. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  309. const unsigned short* indicesEnd = indices + indexCount;
  310. while (indices < indicesEnd)
  311. {
  312. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  313. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  314. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  315. float frontFaceDistance = HitDistance(v0, v1, v2);
  316. float backFaceDistance = HitDistance(v2, v1, v0);
  317. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  318. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  319. // checking reversed frontfaces
  320. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  321. indices += 3;
  322. }
  323. }
  324. // 32-bit indices
  325. else
  326. {
  327. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  328. const unsigned* indicesEnd = indices + indexCount;
  329. while (indices < indicesEnd)
  330. {
  331. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  332. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  333. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  334. float frontFaceDistance = HitDistance(v0, v1, v2);
  335. float backFaceDistance = HitDistance(v2, v1, v0);
  336. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  337. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  338. // checking reversed frontfaces
  339. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  340. indices += 3;
  341. }
  342. }
  343. // If the closest face is a backface, that means that the ray originates from the inside of the geometry
  344. // NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
  345. // (ray doesnt hit either) by this conditional
  346. if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
  347. return currentBackFace < currentFrontFace;
  348. // It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
  349. // As such, it is safe to assume they are not
  350. return false;
  351. }
  352. Ray Ray::Transformed(const Matrix3x4& transform) const
  353. {
  354. Ray ret;
  355. ret.origin_ = transform * origin_;
  356. ret.direction_ = transform * Vector4(direction_, 0.0f);
  357. return ret;
  358. }
  359. }