CatmullRomSpline.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using UnityEngine;
  2. namespace ARLocation
  3. {
  4. /// <summary>
  5. /// A (open-ended) catmull-rom spline, which interpolates a set points by joining
  6. /// catmull-rom curves together.
  7. /// </summary>
  8. public class CatmullRomSpline : Spline
  9. {
  10. /// <summary>
  11. /// The start-point control/handle.
  12. /// </summary>
  13. private Vector3 startHandle;
  14. /// <summary>
  15. /// The end-point control/handle.
  16. /// </summary>
  17. private Vector3 endHandle;
  18. /// <summary>
  19. /// The alpha/tension parameter of the spline.
  20. /// </summary>
  21. public float Alpha
  22. {
  23. get
  24. {
  25. return alpha;
  26. }
  27. set
  28. {
  29. alpha = value;
  30. CalculateSegments(lastSampleSize);
  31. }
  32. }
  33. float alpha;
  34. int lastSampleSize;
  35. /// <summary>
  36. /// Creates a new Catmull-rom spline.
  37. /// </summary>
  38. /// <param name="points">The interpolated points.</param>
  39. /// <param name="n">The number of samples used in each segment of the spline.</param>
  40. /// <param name="alpha"></param>
  41. public CatmullRomSpline(Vector3[] points, int n, float alpha)
  42. {
  43. Points = (Vector3[])points.Clone();
  44. this.alpha = alpha;
  45. CalculateSegments(n);
  46. }
  47. /// <summary>
  48. /// Calculate the catmull-rom segments. Also estimates the curve's length.
  49. /// </summary>
  50. /// <param name="n">The number sample points used to estimate each segment's length.</param>
  51. public sealed override void CalculateSegments(int n)
  52. {
  53. lastSampleSize = n;
  54. segmentCount = (Points.Length - 1);
  55. lengths = new float[segmentCount];
  56. segments = new Curve[segmentCount];
  57. startHandle = 2 * Points[0] - Points[1];
  58. endHandle = 2 * Points[segmentCount] - Points[segmentCount - 1];
  59. Length = 0;
  60. for (var i = 0; i < segmentCount; i++)
  61. {
  62. segments[i] = new CatmullRomCurve(
  63. i == 0 ? startHandle : Points[i - 1],
  64. Points[i],
  65. Points[i + 1],
  66. (i + 1) == segmentCount ? endHandle : Points[i + 2],
  67. Alpha
  68. );
  69. Length += segments[i].EstimateLength(n);
  70. lengths[i] = Length;
  71. }
  72. }
  73. }
  74. }