WorldUvMapper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Shatter Toolkit
  2. // Copyright 2015 Gustav Olsson
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace ShatterToolkit
  6. {
  7. public class WorldUvMapper : UvMapper
  8. {
  9. /// <summary>
  10. /// Determines the scale to be applied to the uv-coordinates. (1,1) will repeat the texture once for every local-space unit, (2,2) twice and so on.
  11. /// </summary>
  12. public Vector2 scale = Vector2.one;
  13. public override void Map(IList<Vector3> points, Vector3 planeNormal, out Vector4[] tangentsA, out Vector4[] tangentsB, out Vector2[] uvsA, out Vector2[] uvsB)
  14. {
  15. // Calculate texture direction vectors
  16. Vector3 u = Vector3.Cross(planeNormal, Vector3.up);
  17. if (u == Vector3.zero)
  18. {
  19. u = Vector3.Cross(planeNormal, Vector3.forward);
  20. }
  21. Vector3 v = Vector3.Cross(u, planeNormal);
  22. u.Normalize();
  23. v.Normalize();
  24. // Set tangents
  25. Vector4 tangentA = new Vector4(u.x, u.y, u.z, 1.0f);
  26. Vector4 tangentB = new Vector4(u.x, u.y, u.z, -1.0f);
  27. tangentsA = new Vector4[points.Count];
  28. tangentsB = new Vector4[points.Count];
  29. for (int i = 0; i < points.Count; i++)
  30. {
  31. tangentsA[i] = tangentA;
  32. tangentsB[i] = tangentB;
  33. }
  34. // Set uvs
  35. Vector2[] uvs = new Vector2[points.Count];
  36. Vector2 min = Vector2.zero;
  37. for (int i = 0; i < points.Count; i++)
  38. {
  39. Vector3 point = points[i];
  40. uvs[i].x = Vector3.Dot(point, u);
  41. uvs[i].y = Vector3.Dot(point, v);
  42. if (i == 0)
  43. {
  44. min = uvs[i];
  45. }
  46. else
  47. {
  48. min = Vector2.Min(uvs[i], min);
  49. }
  50. }
  51. for (int i = 0; i < points.Count; i++)
  52. {
  53. uvs[i] -= min;
  54. uvs[i].x *= scale.x;
  55. uvs[i].y *= scale.y;
  56. }
  57. uvsA = uvs;
  58. uvsB = uvs;
  59. }
  60. }
  61. }