SplineUtility.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using Unity.Collections;
  3. using System.Runtime.InteropServices;
  4. using Unity.Collections.LowLevel.Unsafe;
  5. namespace UnityEngine.U2D
  6. {
  7. public class SplineUtility
  8. {
  9. public static float SlopeAngle(Vector2 start, Vector2 end)
  10. {
  11. Vector2 dir = start - end;
  12. dir.Normalize();
  13. Vector2 dvup = new Vector2(0, 1f);
  14. Vector2 dvrt = new Vector2(1f, 0);
  15. float dr = Vector2.Dot(dir, dvrt);
  16. float du = Vector2.Dot(dir, dvup);
  17. float cu = Mathf.Acos(du);
  18. float sn = dr >= 0 ? 1.0f : -1.0f;
  19. float an = cu * Mathf.Rad2Deg * sn;
  20. // Adjust angles when direction is parallel to Up Axis.
  21. an = (du != 1f) ? an : 0;
  22. an = (du != -1f) ? an : -180f;
  23. return an;
  24. }
  25. public static void CalculateTangents(Vector3 point, Vector3 prevPoint, Vector3 nextPoint, Vector3 forward, float scale, out Vector3 rightTangent, out Vector3 leftTangent)
  26. {
  27. Vector3 v1 = (prevPoint - point).normalized;
  28. Vector3 v2 = (nextPoint - point).normalized;
  29. Vector3 v3 = v1 + v2;
  30. Vector3 cross = forward;
  31. if (prevPoint != nextPoint)
  32. {
  33. bool colinear = Mathf.Abs(v1.x * v2.y - v1.y * v2.x + v1.x * v2.z - v1.z * v2.x + v1.y * v2.z - v1.z * v2.y) < 0.01f;
  34. if (colinear)
  35. {
  36. rightTangent = v2 * scale;
  37. leftTangent = v1 * scale;
  38. return;
  39. }
  40. cross = Vector3.Cross(v1, v2);
  41. }
  42. rightTangent = Vector3.Cross(cross, v3).normalized * scale;
  43. leftTangent = -rightTangent;
  44. }
  45. public static int NextIndex(int index, int pointCount)
  46. {
  47. return Mod(index + 1, pointCount);
  48. }
  49. public static int PreviousIndex(int index, int pointCount)
  50. {
  51. return Mod(index - 1, pointCount);
  52. }
  53. private static int Mod(int x, int m)
  54. {
  55. int r = x % m;
  56. return r < 0 ? r + m : r;
  57. }
  58. }
  59. // Copy utility.
  60. internal class SpriteShapeCopyUtility<T> where T : struct
  61. {
  62. internal static void Copy(NativeSlice<T> dst, T[] src, int length)
  63. {
  64. NativeSlice<T> dstSet = new NativeSlice<T>(dst, 0, length);
  65. dstSet.CopyFrom(src);
  66. }
  67. internal static void Copy(T[] dst, NativeSlice<T> src, int length)
  68. {
  69. NativeSlice<T> dstSet = new NativeSlice<T>(src, 0, length);
  70. dstSet.CopyTo(dst);
  71. }
  72. }
  73. }