Ray.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Runtime.InteropServices;
  5. namespace BansheeEngine
  6. {
  7. /** @addtogroup Math
  8. * @{
  9. */
  10. /// <summary>
  11. /// A ray in 3D space represented with an origin and direction.
  12. /// </summary>
  13. [StructLayout(LayoutKind.Sequential), SerializeObject]
  14. public struct Ray // Note: Must match C++ struct Ray
  15. {
  16. public Vector3 origin;
  17. public Vector3 direction;
  18. /// <summary>
  19. /// Creates a new ray.
  20. /// </summary>
  21. /// <param name="origin">Coordinates for the origin of the ray.</param>
  22. /// <param name="direction">Normalized direction of the ray.</param>
  23. public Ray(Vector3 origin, Vector3 direction)
  24. {
  25. this.origin = origin;
  26. this.direction = direction;
  27. }
  28. /// <summary>
  29. /// Multiples ray by a scalar and retrieves a point along the ray.
  30. /// </summary>
  31. /// <param name="ray">Ray to transform.</param>
  32. /// <param name="t">How far along the ray to retrieve the point.</param>
  33. /// <returns>Point along the ray <paramref name="t"/> units away from the origin.</returns>
  34. public static Vector3 operator*(Ray ray, float t)
  35. {
  36. return ray.origin + ray.direction * t;
  37. }
  38. /// <summary>
  39. /// Transforms the ray by the specified matrix. If the matrix is affine use
  40. /// <see cref="TransformAffine"/> as it is faster.
  41. /// </summary>
  42. /// <param name="matrix">Matrix to transform the ray by.</param>
  43. public void Transform(Matrix4 matrix)
  44. {
  45. Vector3 end = this * 1.0f;
  46. origin = matrix.Multiply(origin);
  47. end = matrix.Multiply(end);
  48. direction = Vector3.Normalize(end - origin);
  49. }
  50. /// <summary>
  51. /// Transforms the ray by the specified affine matrix.
  52. /// </summary>
  53. /// <param name="matrix">Affine matrix to transform the ray by.</param>
  54. public void TransformAffine(Matrix4 matrix)
  55. {
  56. Vector3 end = this * 1.0f;
  57. origin = matrix.MultiplyDirection(origin);
  58. end = matrix.MultiplyDirection(end);
  59. direction = Vector3.Normalize(end - origin);
  60. }
  61. /// <inheritdoc/>
  62. public override string ToString()
  63. {
  64. return String.Format("(origin: {0} direction: {1})", origin, direction);
  65. }
  66. };
  67. /** @} */
  68. }