vector3d.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. // Copyright (C) 2002-2012 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine".
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h
  4. #pragma once
  5. #include "irrMath.h"
  6. #include <functional>
  7. namespace irr
  8. {
  9. namespace core
  10. {
  11. //! 3d vector template class with lots of operators and methods.
  12. /** The vector3d class is used in Irrlicht for three main purposes:
  13. 1) As a direction vector (most of the methods assume this).
  14. 2) As a position in 3d space (which is synonymous with a direction vector from the origin to this position).
  15. 3) To hold three Euler rotations, where X is pitch, Y is yaw and Z is roll.
  16. */
  17. template <class T>
  18. class vector3d
  19. {
  20. public:
  21. //! Default constructor (null vector).
  22. constexpr vector3d() :
  23. X(0), Y(0), Z(0) {}
  24. //! Constructor with three different values
  25. constexpr vector3d(T nx, T ny, T nz) :
  26. X(nx), Y(ny), Z(nz) {}
  27. //! Constructor with the same value for all elements
  28. explicit constexpr vector3d(T n) :
  29. X(n), Y(n), Z(n) {}
  30. // operators
  31. vector3d<T> operator-() const { return vector3d<T>(-X, -Y, -Z); }
  32. vector3d<T> operator+(const vector3d<T> &other) const { return vector3d<T>(X + other.X, Y + other.Y, Z + other.Z); }
  33. vector3d<T> &operator+=(const vector3d<T> &other)
  34. {
  35. X += other.X;
  36. Y += other.Y;
  37. Z += other.Z;
  38. return *this;
  39. }
  40. vector3d<T> operator+(const T val) const { return vector3d<T>(X + val, Y + val, Z + val); }
  41. vector3d<T> &operator+=(const T val)
  42. {
  43. X += val;
  44. Y += val;
  45. Z += val;
  46. return *this;
  47. }
  48. vector3d<T> operator-(const vector3d<T> &other) const { return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z); }
  49. vector3d<T> &operator-=(const vector3d<T> &other)
  50. {
  51. X -= other.X;
  52. Y -= other.Y;
  53. Z -= other.Z;
  54. return *this;
  55. }
  56. vector3d<T> operator-(const T val) const { return vector3d<T>(X - val, Y - val, Z - val); }
  57. vector3d<T> &operator-=(const T val)
  58. {
  59. X -= val;
  60. Y -= val;
  61. Z -= val;
  62. return *this;
  63. }
  64. vector3d<T> operator*(const vector3d<T> &other) const { return vector3d<T>(X * other.X, Y * other.Y, Z * other.Z); }
  65. vector3d<T> &operator*=(const vector3d<T> &other)
  66. {
  67. X *= other.X;
  68. Y *= other.Y;
  69. Z *= other.Z;
  70. return *this;
  71. }
  72. vector3d<T> operator*(const T v) const { return vector3d<T>(X * v, Y * v, Z * v); }
  73. vector3d<T> &operator*=(const T v)
  74. {
  75. X *= v;
  76. Y *= v;
  77. Z *= v;
  78. return *this;
  79. }
  80. vector3d<T> operator/(const vector3d<T> &other) const { return vector3d<T>(X / other.X, Y / other.Y, Z / other.Z); }
  81. vector3d<T> &operator/=(const vector3d<T> &other)
  82. {
  83. X /= other.X;
  84. Y /= other.Y;
  85. Z /= other.Z;
  86. return *this;
  87. }
  88. vector3d<T> operator/(const T v) const { return vector3d<T>(X / v, Y / v, Z / v); }
  89. vector3d<T> &operator/=(const T v)
  90. {
  91. X /= v;
  92. Y /= v;
  93. Z /= v;
  94. return *this;
  95. }
  96. T &operator[](u32 index)
  97. {
  98. _IRR_DEBUG_BREAK_IF(index > 2) // access violation
  99. return *(&X + index);
  100. }
  101. const T &operator[](u32 index) const
  102. {
  103. _IRR_DEBUG_BREAK_IF(index > 2) // access violation
  104. return *(&X + index);
  105. }
  106. //! sort in order X, Y, Z.
  107. constexpr bool operator<=(const vector3d<T> &other) const
  108. {
  109. return !(*this > other);
  110. }
  111. //! sort in order X, Y, Z.
  112. constexpr bool operator>=(const vector3d<T> &other) const
  113. {
  114. return !(*this < other);
  115. }
  116. //! sort in order X, Y, Z.
  117. constexpr bool operator<(const vector3d<T> &other) const
  118. {
  119. return X < other.X || (X == other.X && Y < other.Y) ||
  120. (X == other.X && Y == other.Y && Z < other.Z);
  121. }
  122. //! sort in order X, Y, Z.
  123. constexpr bool operator>(const vector3d<T> &other) const
  124. {
  125. return X > other.X || (X == other.X && Y > other.Y) ||
  126. (X == other.X && Y == other.Y && Z > other.Z);
  127. }
  128. constexpr bool operator==(const vector3d<T> &other) const
  129. {
  130. return X == other.X && Y == other.Y && Z == other.Z;
  131. }
  132. constexpr bool operator!=(const vector3d<T> &other) const
  133. {
  134. return !(*this == other);
  135. }
  136. // functions
  137. //! Checks if this vector equals the other one.
  138. /** Takes floating point rounding errors into account.
  139. \param other Vector to compare with.
  140. \return True if the two vector are (almost) equal, else false. */
  141. bool equals(const vector3d<T> &other) const
  142. {
  143. return core::equals(X, other.X) && core::equals(Y, other.Y) && core::equals(Z, other.Z);
  144. }
  145. vector3d<T> &set(const T nx, const T ny, const T nz)
  146. {
  147. X = nx;
  148. Y = ny;
  149. Z = nz;
  150. return *this;
  151. }
  152. vector3d<T> &set(const vector3d<T> &p)
  153. {
  154. X = p.X;
  155. Y = p.Y;
  156. Z = p.Z;
  157. return *this;
  158. }
  159. //! Get length of the vector.
  160. T getLength() const { return core::squareroot(X * X + Y * Y + Z * Z); }
  161. //! Get squared length of the vector.
  162. /** This is useful because it is much faster than getLength().
  163. \return Squared length of the vector. */
  164. T getLengthSQ() const { return X * X + Y * Y + Z * Z; }
  165. //! Get the dot product with another vector.
  166. T dotProduct(const vector3d<T> &other) const
  167. {
  168. return X * other.X + Y * other.Y + Z * other.Z;
  169. }
  170. //! Get distance from another point.
  171. /** Here, the vector is interpreted as point in 3 dimensional space. */
  172. T getDistanceFrom(const vector3d<T> &other) const
  173. {
  174. return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z).getLength();
  175. }
  176. //! Returns squared distance from another point.
  177. /** Here, the vector is interpreted as point in 3 dimensional space. */
  178. T getDistanceFromSQ(const vector3d<T> &other) const
  179. {
  180. return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z).getLengthSQ();
  181. }
  182. //! Calculates the cross product with another vector.
  183. /** \param p Vector to multiply with.
  184. \return Cross product of this vector with p. */
  185. vector3d<T> crossProduct(const vector3d<T> &p) const
  186. {
  187. return vector3d<T>(Y * p.Z - Z * p.Y, Z * p.X - X * p.Z, X * p.Y - Y * p.X);
  188. }
  189. //! Returns if this vector interpreted as a point is on a line between two other points.
  190. /** It is assumed that the point is on the line.
  191. \param begin Beginning vector to compare between.
  192. \param end Ending vector to compare between.
  193. \return True if this vector is between begin and end, false if not. */
  194. bool isBetweenPoints(const vector3d<T> &begin, const vector3d<T> &end) const
  195. {
  196. const T f = (end - begin).getLengthSQ();
  197. return getDistanceFromSQ(begin) <= f &&
  198. getDistanceFromSQ(end) <= f;
  199. }
  200. //! Normalizes the vector.
  201. /** In case of the 0 vector the result is still 0, otherwise
  202. the length of the vector will be 1.
  203. \return Reference to this vector after normalization. */
  204. vector3d<T> &normalize()
  205. {
  206. f64 length = X * X + Y * Y + Z * Z;
  207. if (length == 0) // this check isn't an optimization but prevents getting NAN in the sqrt.
  208. return *this;
  209. length = core::reciprocal_squareroot(length);
  210. X = (T)(X * length);
  211. Y = (T)(Y * length);
  212. Z = (T)(Z * length);
  213. return *this;
  214. }
  215. //! Sets the length of the vector to a new value
  216. vector3d<T> &setLength(T newlength)
  217. {
  218. normalize();
  219. return (*this *= newlength);
  220. }
  221. //! Inverts the vector.
  222. vector3d<T> &invert()
  223. {
  224. X *= -1;
  225. Y *= -1;
  226. Z *= -1;
  227. return *this;
  228. }
  229. //! Rotates the vector by a specified number of degrees around the Y axis and the specified center.
  230. /** CAREFUL: For historical reasons rotateXZBy uses a right-handed rotation
  231. (maybe to make it more similar to the 2D vector rotations which are counterclockwise).
  232. To have this work the same way as rest of Irrlicht (nodes, matrices, other rotateBy functions) pass -1*degrees in here.
  233. \param degrees Number of degrees to rotate around the Y axis.
  234. \param center The center of the rotation. */
  235. void rotateXZBy(f64 degrees, const vector3d<T> &center = vector3d<T>())
  236. {
  237. degrees *= DEGTORAD64;
  238. f64 cs = cos(degrees);
  239. f64 sn = sin(degrees);
  240. X -= center.X;
  241. Z -= center.Z;
  242. set((T)(X * cs - Z * sn), Y, (T)(X * sn + Z * cs));
  243. X += center.X;
  244. Z += center.Z;
  245. }
  246. //! Rotates the vector by a specified number of degrees around the Z axis and the specified center.
  247. /** \param degrees: Number of degrees to rotate around the Z axis.
  248. \param center: The center of the rotation. */
  249. void rotateXYBy(f64 degrees, const vector3d<T> &center = vector3d<T>())
  250. {
  251. degrees *= DEGTORAD64;
  252. f64 cs = cos(degrees);
  253. f64 sn = sin(degrees);
  254. X -= center.X;
  255. Y -= center.Y;
  256. set((T)(X * cs - Y * sn), (T)(X * sn + Y * cs), Z);
  257. X += center.X;
  258. Y += center.Y;
  259. }
  260. //! Rotates the vector by a specified number of degrees around the X axis and the specified center.
  261. /** \param degrees: Number of degrees to rotate around the X axis.
  262. \param center: The center of the rotation. */
  263. void rotateYZBy(f64 degrees, const vector3d<T> &center = vector3d<T>())
  264. {
  265. degrees *= DEGTORAD64;
  266. f64 cs = cos(degrees);
  267. f64 sn = sin(degrees);
  268. Z -= center.Z;
  269. Y -= center.Y;
  270. set(X, (T)(Y * cs - Z * sn), (T)(Y * sn + Z * cs));
  271. Z += center.Z;
  272. Y += center.Y;
  273. }
  274. //! Creates an interpolated vector between this vector and another vector.
  275. /** \param other The other vector to interpolate with.
  276. \param d Interpolation value between 0.0f (all the other vector) and 1.0f (all this vector).
  277. Note that this is the opposite direction of interpolation to getInterpolated_quadratic()
  278. \return An interpolated vector. This vector is not modified. */
  279. vector3d<T> getInterpolated(const vector3d<T> &other, f64 d) const
  280. {
  281. const f64 inv = 1.0 - d;
  282. return vector3d<T>((T)(other.X * inv + X * d), (T)(other.Y * inv + Y * d), (T)(other.Z * inv + Z * d));
  283. }
  284. //! Creates a quadratically interpolated vector between this and two other vectors.
  285. /** \param v2 Second vector to interpolate with.
  286. \param v3 Third vector to interpolate with (maximum at 1.0f)
  287. \param d Interpolation value between 0.0f (all this vector) and 1.0f (all the 3rd vector).
  288. Note that this is the opposite direction of interpolation to getInterpolated() and interpolate()
  289. \return An interpolated vector. This vector is not modified. */
  290. vector3d<T> getInterpolated_quadratic(const vector3d<T> &v2, const vector3d<T> &v3, f64 d) const
  291. {
  292. // this*(1-d)*(1-d) + 2 * v2 * (1-d) + v3 * d * d;
  293. const f64 inv = (T)1.0 - d;
  294. const f64 mul0 = inv * inv;
  295. const f64 mul1 = (T)2.0 * d * inv;
  296. const f64 mul2 = d * d;
  297. return vector3d<T>((T)(X * mul0 + v2.X * mul1 + v3.X * mul2),
  298. (T)(Y * mul0 + v2.Y * mul1 + v3.Y * mul2),
  299. (T)(Z * mul0 + v2.Z * mul1 + v3.Z * mul2));
  300. }
  301. //! Sets this vector to the linearly interpolated vector between a and b.
  302. /** \param a first vector to interpolate with, maximum at 1.0f
  303. \param b second vector to interpolate with, maximum at 0.0f
  304. \param d Interpolation value between 0.0f (all vector b) and 1.0f (all vector a)
  305. Note that this is the opposite direction of interpolation to getInterpolated_quadratic()
  306. */
  307. vector3d<T> &interpolate(const vector3d<T> &a, const vector3d<T> &b, f64 d)
  308. {
  309. X = (T)((f64)b.X + ((a.X - b.X) * d));
  310. Y = (T)((f64)b.Y + ((a.Y - b.Y) * d));
  311. Z = (T)((f64)b.Z + ((a.Z - b.Z) * d));
  312. return *this;
  313. }
  314. //! Get the rotations that would make a (0,0,1) direction vector point in the same direction as this direction vector.
  315. /** Thanks to Arras on the Irrlicht forums for this method. This utility method is very useful for
  316. orienting scene nodes towards specific targets. For example, if this vector represents the difference
  317. between two scene nodes, then applying the result of getHorizontalAngle() to one scene node will point
  318. it at the other one.
  319. Example code:
  320. // Where target and seeker are of type ISceneNode*
  321. const vector3df toTarget(target->getAbsolutePosition() - seeker->getAbsolutePosition());
  322. const vector3df requiredRotation = toTarget.getHorizontalAngle();
  323. seeker->setRotation(requiredRotation);
  324. \return A rotation vector containing the X (pitch) and Y (raw) rotations (in degrees) that when applied to a
  325. +Z (e.g. 0, 0, 1) direction vector would make it point in the same direction as this vector. The Z (roll) rotation
  326. is always 0, since two Euler rotations are sufficient to point in any given direction. */
  327. vector3d<T> getHorizontalAngle() const
  328. {
  329. vector3d<T> angle;
  330. // tmp avoids some precision troubles on some compilers when working with T=s32
  331. f64 tmp = (atan2((f64)X, (f64)Z) * RADTODEG64);
  332. angle.Y = (T)tmp;
  333. if (angle.Y < 0)
  334. angle.Y += 360;
  335. if (angle.Y >= 360)
  336. angle.Y -= 360;
  337. const f64 z1 = core::squareroot(X * X + Z * Z);
  338. tmp = (atan2((f64)z1, (f64)Y) * RADTODEG64 - 90.0);
  339. angle.X = (T)tmp;
  340. if (angle.X < 0)
  341. angle.X += 360;
  342. if (angle.X >= 360)
  343. angle.X -= 360;
  344. return angle;
  345. }
  346. //! Get the spherical coordinate angles
  347. /** This returns Euler degrees for the point represented by
  348. this vector. The calculation assumes the pole at (0,1,0) and
  349. returns the angles in X and Y.
  350. */
  351. vector3d<T> getSphericalCoordinateAngles() const
  352. {
  353. vector3d<T> angle;
  354. const f64 length = X * X + Y * Y + Z * Z;
  355. if (length) {
  356. if (X != 0) {
  357. angle.Y = (T)(atan2((f64)Z, (f64)X) * RADTODEG64);
  358. } else if (Z < 0)
  359. angle.Y = 180;
  360. angle.X = (T)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64);
  361. }
  362. return angle;
  363. }
  364. //! Builds a direction vector from (this) rotation vector.
  365. /** This vector is assumed to be a rotation vector composed of 3 Euler angle rotations, in degrees.
  366. The implementation performs the same calculations as using a matrix to do the rotation.
  367. \param[in] forwards The direction representing "forwards" which will be rotated by this vector.
  368. If you do not provide a direction, then the +Z axis (0, 0, 1) will be assumed to be forwards.
  369. \return A direction vector calculated by rotating the forwards direction by the 3 Euler angles
  370. (in degrees) represented by this vector. */
  371. vector3d<T> rotationToDirection(const vector3d<T> &forwards = vector3d<T>(0, 0, 1)) const
  372. {
  373. const f64 cr = cos(core::DEGTORAD64 * X);
  374. const f64 sr = sin(core::DEGTORAD64 * X);
  375. const f64 cp = cos(core::DEGTORAD64 * Y);
  376. const f64 sp = sin(core::DEGTORAD64 * Y);
  377. const f64 cy = cos(core::DEGTORAD64 * Z);
  378. const f64 sy = sin(core::DEGTORAD64 * Z);
  379. const f64 srsp = sr * sp;
  380. const f64 crsp = cr * sp;
  381. const f64 pseudoMatrix[] = {
  382. (cp * cy), (cp * sy), (-sp),
  383. (srsp * cy - cr * sy), (srsp * sy + cr * cy), (sr * cp),
  384. (crsp * cy + sr * sy), (crsp * sy - sr * cy), (cr * cp)};
  385. return vector3d<T>(
  386. (T)(forwards.X * pseudoMatrix[0] +
  387. forwards.Y * pseudoMatrix[3] +
  388. forwards.Z * pseudoMatrix[6]),
  389. (T)(forwards.X * pseudoMatrix[1] +
  390. forwards.Y * pseudoMatrix[4] +
  391. forwards.Z * pseudoMatrix[7]),
  392. (T)(forwards.X * pseudoMatrix[2] +
  393. forwards.Y * pseudoMatrix[5] +
  394. forwards.Z * pseudoMatrix[8]));
  395. }
  396. //! Fills an array of 4 values with the vector data (usually floats).
  397. /** Useful for setting in shader constants for example. The fourth value
  398. will always be 0. */
  399. void getAs4Values(T *array) const
  400. {
  401. array[0] = X;
  402. array[1] = Y;
  403. array[2] = Z;
  404. array[3] = 0;
  405. }
  406. //! Fills an array of 3 values with the vector data (usually floats).
  407. /** Useful for setting in shader constants for example.*/
  408. void getAs3Values(T *array) const
  409. {
  410. array[0] = X;
  411. array[1] = Y;
  412. array[2] = Z;
  413. }
  414. //! X coordinate of the vector
  415. T X;
  416. //! Y coordinate of the vector
  417. T Y;
  418. //! Z coordinate of the vector
  419. T Z;
  420. };
  421. //! partial specialization for integer vectors
  422. // Implementer note: inline keyword needed due to template specialization for s32. Otherwise put specialization into a .cpp
  423. template <>
  424. inline vector3d<s32> vector3d<s32>::operator/(s32 val) const
  425. {
  426. return core::vector3d<s32>(X / val, Y / val, Z / val);
  427. }
  428. template <>
  429. inline vector3d<s32> &vector3d<s32>::operator/=(s32 val)
  430. {
  431. X /= val;
  432. Y /= val;
  433. Z /= val;
  434. return *this;
  435. }
  436. template <>
  437. inline vector3d<s32> vector3d<s32>::getSphericalCoordinateAngles() const
  438. {
  439. vector3d<s32> angle;
  440. const f64 length = X * X + Y * Y + Z * Z;
  441. if (length) {
  442. if (X != 0) {
  443. angle.Y = round32((f32)(atan2((f64)Z, (f64)X) * RADTODEG64));
  444. } else if (Z < 0)
  445. angle.Y = 180;
  446. angle.X = round32((f32)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64));
  447. }
  448. return angle;
  449. }
  450. //! Typedef for a f32 3d vector.
  451. typedef vector3d<f32> vector3df;
  452. //! Typedef for an integer 3d vector.
  453. typedef vector3d<s32> vector3di;
  454. //! Function multiplying a scalar and a vector component-wise.
  455. template <class S, class T>
  456. vector3d<T> operator*(const S scalar, const vector3d<T> &vector)
  457. {
  458. return vector * scalar;
  459. }
  460. } // end namespace core
  461. } // end namespace irr
  462. namespace std
  463. {
  464. template <class T>
  465. struct hash<irr::core::vector3d<T>>
  466. {
  467. size_t operator()(const irr::core::vector3d<T> &vec) const
  468. {
  469. size_t h1 = hash<T>()(vec.X);
  470. size_t h2 = hash<T>()(vec.Y);
  471. size_t h3 = hash<T>()(vec.Z);
  472. return (h1 << (5 * sizeof(h1)) | h1 >> (3 * sizeof(h1))) ^ (h2 << (2 * sizeof(h2)) | h2 >> (6 * sizeof(h2))) ^ h3;
  473. }
  474. };
  475. }