CurvedUIVertexEffect.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. #if UNITY_EDITOR
  6. using UnityEditor;
  7. #endif
  8. #if CURVEDUI_TMP || TMP_PRESENT
  9. using TMPro;
  10. #endif
  11. [assembly: CurvedUI.OptionalDependency("TMPro.TextMeshProUGUI", "CURVEDUI_TMP")]
  12. namespace CurvedUI
  13. {
  14. //Added to every UI object by CurvedUISettings.
  15. //This is the script that subdivides and modifies the shape of the canvas object it is attached to.
  16. //
  17. //Requires Unity 5.3 or later
  18. public partial class CurvedUIVertexEffect : BaseMeshEffect
  19. {
  20. #region VARIABLES
  21. //public settings
  22. [Tooltip("Check to skip tesselation pass on this object. CurvedUI will not create additional vertices to make this object have a smoother curve. Checking this can solve some issues if you create your own procedural mesh for this object. Default false.")]
  23. public bool DoNotTesselate = false;
  24. //stored references
  25. Canvas myCanvas;
  26. CurvedUISettings mySettings;
  27. Graphic myGraphic;
  28. Text myText;
  29. #if CURVEDUI_TMP || TMP_PRESENT
  30. TextMeshProUGUI myTMP;
  31. CurvedUITMPSubmesh myTMPSubMesh;
  32. #endif
  33. //variables we operate on
  34. bool m_tesselationRequired = true;
  35. bool tesselationRequired {
  36. get { return m_tesselationRequired; }
  37. set { m_tesselationRequired = value;
  38. //Debug.Log(this.gameObject.name + " settting tess to " + value, this.gameObject);
  39. }
  40. }
  41. bool curvingRequired = true;
  42. bool TransformMisaligned = false;
  43. Matrix4x4 CanvasToWorld;
  44. Matrix4x4 CanvasToLocal;
  45. Matrix4x4 MyToWorld;
  46. Matrix4x4 MyToLocal;
  47. List<UIVertex> m_tesselatedVerts = new List<UIVertex>();
  48. List<UIVertex> m_curvedVerts = new List<UIVertex>();
  49. List<UIVertex> m_vertsInQuads = new List<UIVertex>();
  50. UIVertex m_ret;
  51. UIVertex[] m_quad = new UIVertex[4];
  52. float[] m_weights = new float[4];
  53. [SerializeField] [HideInInspector] Vector3 savedPos;
  54. [SerializeField] [HideInInspector] Vector3 savedUp;
  55. [SerializeField] [HideInInspector] Vector2 savedRectSize;
  56. [SerializeField] [HideInInspector] Color savedColor;
  57. [SerializeField] [HideInInspector] Vector2 savedTextUV0;
  58. [SerializeField] [HideInInspector] float savedFill;
  59. #endregion
  60. #region LIFECYCLE
  61. protected override void Awake()
  62. {
  63. base.Awake();
  64. myGraphic = GetComponent<Graphic>();
  65. myText = GetComponent<Text>();
  66. #if CURVEDUI_TMP || TMP_PRESENT
  67. myTMP = GetComponent<TextMeshProUGUI>();
  68. myTMPSubMesh = GetComponent<CurvedUITMPSubmesh>();
  69. #endif
  70. }
  71. protected override void OnEnable()
  72. {
  73. //find the settings object and its canvas.
  74. FindParentSettings();
  75. //If there is an update to the graphic, we cant reuse old vertices, so new tesselation will be required
  76. if (myGraphic)
  77. {
  78. myGraphic.RegisterDirtyMaterialCallback(TesselationRequiredCallback);
  79. myGraphic.SetVerticesDirty();
  80. }
  81. //add text events and callbacks
  82. if (myText)
  83. {
  84. myText.RegisterDirtyVerticesCallback(TesselationRequiredCallback);
  85. Font.textureRebuilt += FontTextureRebuiltCallback;
  86. }
  87. }
  88. /// <summary>
  89. /// Start is executed after OnEnable
  90. /// </summary>
  91. protected override void Start()
  92. {
  93. base.Start();
  94. //if we have an interactable component, make sure its inside the canvas and it's Z position is 0 in relation to the canvas.
  95. //Otherwise the interactions on it will not be accurate, or it may not work at all!
  96. //This is because, in order to save performance, CurvedUI creates a collider only for the space inside the Canvas rectangle.
  97. if (myCanvas && GetComponent<Selectable>())
  98. {
  99. Vector3 myPosOnCanvas = myCanvas.transform.worldToLocalMatrix.MultiplyPoint3x4(this.transform.position);
  100. RectTransform canvasRect = (myCanvas.transform as RectTransform);
  101. if (myPosOnCanvas.x.Abs() > canvasRect.rect.width / 2.0f || myPosOnCanvas.y.Abs() > canvasRect.rect.height / 2.0f)
  102. {
  103. Debug.LogWarning("CurvedUI: " + GetComponent<Selectable>().GetType().Name + " \"" + this.gameObject.name + "\" is outside of the canvas. It will not be interactable. Move it inside the canvas rectangle (white border in scene view) for it to work.", this.gameObject);
  104. }
  105. if (myPosOnCanvas.z.Abs() > 0.1f)
  106. {
  107. Debug.LogWarning("CurvedUI: The Z position of \"" + this.gameObject.name + "\" " + GetComponent<Selectable>().GetType().Name + ", or one of its parents is not 0 in relation to the canvas. The interactions may not be accurate.", this.gameObject);
  108. }
  109. }
  110. }
  111. protected override void OnDisable()
  112. {
  113. //If there is an update to the graphic, we cant reuse old vertices, so new tesselation will be required
  114. if (myGraphic)
  115. myGraphic.UnregisterDirtyMaterialCallback(TesselationRequiredCallback);
  116. if (myText)
  117. {
  118. myText.UnregisterDirtyVerticesCallback(TesselationRequiredCallback);
  119. Font.textureRebuilt -= FontTextureRebuiltCallback;
  120. }
  121. }
  122. /// <summary>
  123. /// Subscribed to graphic componenet to find out when vertex information changes and we need to create new geometry based on that.
  124. /// </summary>
  125. void TesselationRequiredCallback()
  126. {
  127. tesselationRequired = true;
  128. }
  129. /// <summary>
  130. /// Called by Font class to let us know font atlas has ben rebuilt and we need to update our vertices.
  131. /// </summary>
  132. void FontTextureRebuiltCallback(Font fontie)
  133. {
  134. if (myText.font == fontie)
  135. tesselationRequired = true;
  136. }
  137. void LateUpdate()
  138. {
  139. #if CURVEDUI_TMP || TMP_PRESENT // CurvedUITMP handles updates for TextMeshPro objects.
  140. if (myTMP || myTMPSubMesh) return;
  141. #endif
  142. //Find if the change in transform requires us to retesselate the UI
  143. // do not perform the check it it will happen anyway
  144. if (!tesselationRequired)
  145. {
  146. if ((transform as RectTransform).rect.size != savedRectSize)
  147. {
  148. //the size of this RectTransform has changed, we have to tesselate again!
  149. tesselationRequired = true;
  150. }
  151. else if (myGraphic != null)//test for color changes if it has a graphic component
  152. {
  153. if (myGraphic.color != savedColor)
  154. {
  155. tesselationRequired = true;
  156. savedColor = myGraphic.color;
  157. }
  158. else if (myGraphic is Image)
  159. {
  160. if ((myGraphic as Image).fillAmount != savedFill)
  161. {
  162. tesselationRequired = true;
  163. savedFill = (myGraphic as Image).fillAmount;
  164. }
  165. }
  166. }
  167. }
  168. if (!tesselationRequired && !curvingRequired) // do not perform a check if we're already tesselating or curving. Tesselation includes curving.
  169. {
  170. //test if position in canvas's local space has been changed. We would need to recalculate vertices again
  171. Vector3 testedPos = mySettings.transform.worldToLocalMatrix.MultiplyPoint3x4(this.transform.position);
  172. if (!testedPos.AlmostEqual(savedPos))
  173. {
  174. //we dont have to curve vertices if we only moved the object vertically in a cylinder.
  175. if (mySettings.Shape != CurvedUISettings.CurvedUIShape.CYLINDER || Mathf.Pow(testedPos.x - savedPos.x, 2) > 0.00001 || Mathf.Pow(testedPos.z - savedPos.z, 2) > 0.00001)
  176. {
  177. savedPos = testedPos;
  178. curvingRequired = true;
  179. //Debug.Log("crv req - tested pos: " + testedPos, this.gameObject);
  180. }
  181. }
  182. //test this object's rotation in relation to canvas.
  183. Vector3 testedUp = mySettings.transform.worldToLocalMatrix.MultiplyVector(this.transform.up).normalized;
  184. if (!savedUp.AlmostEqual(testedUp, 0.0001))
  185. {
  186. bool testedEqual = testedUp.AlmostEqual(Vector3.up.normalized);
  187. bool savedEqual = savedUp.AlmostEqual(Vector3.up.normalized);
  188. //special case - if we change the z angle from or to 0, we need to retesselate to properly display geometry in cyllinder
  189. if ((!testedEqual && savedEqual) || (testedEqual && !savedEqual))
  190. tesselationRequired = true;
  191. savedUp = testedUp;
  192. curvingRequired = true;
  193. //Debug.Log("crv req - tested up: " + testedUp);
  194. }
  195. }
  196. ////if we find we need to make a change in the mesh, set vertices dirty to trigger BaseMeshEffect firing.
  197. if (myGraphic && (tesselationRequired || curvingRequired)) myGraphic.SetVerticesDirty();
  198. }
  199. #endregion
  200. #region MESH EFFECT
  201. //This is called by canvas after UI object's mesh is generated, but before it is rendered.
  202. //Best place to modify the vertices of the object.
  203. public override void ModifyMesh(VertexHelper vh)
  204. {
  205. if (!ShouldModify()) return;
  206. //check for changes in text font material that would mean a retesselation in required to get fresh UV's
  207. CheckTextFontMaterial();
  208. //TESSELATING VERTICES--------------------------------------------------------//
  209. //tesselate (subdivide) the vertices of the UI object if we need more of them
  210. //to display nice curvature. Save them to a list, so we don't have to retesselate
  211. //if RectTransform's size has not changed.
  212. if (tesselationRequired || !Application.isPlaying)
  213. {
  214. //Prepare a list and get vertices from the vertex stream. These come as triangles.
  215. if (m_tesselatedVerts == null)
  216. m_tesselatedVerts = new List<UIVertex>();
  217. else
  218. m_tesselatedVerts.Clear();
  219. vh.GetUIVertexStream(m_tesselatedVerts);
  220. //subdivide them
  221. TesselateGeometry(m_tesselatedVerts);
  222. //save the transform properties we last tesselated for.
  223. savedRectSize = (transform as RectTransform).rect.size;
  224. //set flag
  225. tesselationRequired = false;
  226. curvingRequired = true;
  227. }
  228. //CURVING VERTICES ---------------------------------------------------------//
  229. if (curvingRequired)
  230. {
  231. //update transformation matrices we're going to use in curving the verts.
  232. CanvasToWorld = myCanvas.transform.localToWorldMatrix;
  233. CanvasToLocal = myCanvas.transform.worldToLocalMatrix;
  234. MyToWorld = transform.localToWorldMatrix;
  235. MyToLocal = transform.worldToLocalMatrix;
  236. //prepare list
  237. if (m_curvedVerts == null)
  238. m_curvedVerts = new List<UIVertex>();
  239. //Debug.Log("verts:" + m_curvedVerts.Count + " tess'd:" + m_tesselatedVerts.Count);
  240. if (m_curvedVerts.Count == m_tesselatedVerts.Count)
  241. {
  242. //Debug.Log("count equal");
  243. for (int i = 0; i < m_curvedVerts.Count; i++)
  244. m_curvedVerts[i] = CurveVertex(m_tesselatedVerts[i], mySettings.Angle, mySettings.GetCyllinderRadiusInCanvasSpace(), (myCanvas.transform as RectTransform).rect.size);
  245. }
  246. else
  247. {
  248. m_curvedVerts.Clear();
  249. for (int i = 0; i < m_tesselatedVerts.Count; i++)
  250. m_curvedVerts.Add(CurveVertex(m_tesselatedVerts[i], mySettings.Angle, mySettings.GetCyllinderRadiusInCanvasSpace(), (myCanvas.transform as RectTransform).rect.size));
  251. }
  252. //set flags
  253. curvingRequired = false;
  254. }
  255. //SAVE CURVED VERTICES TO THE VERTEX HELPER------------------------//
  256. //They can come as quads or as triangles.
  257. vh.Clear();
  258. if (m_curvedVerts.Count % 4 == 0)
  259. {
  260. for (int i = 0; i < m_curvedVerts.Count; i += 4)
  261. {
  262. for (int v = 0; v < 4; v++)//create a quad
  263. m_quad[v] = m_curvedVerts[i + v];
  264. vh.AddUIVertexQuad(m_quad); // add it to the list
  265. }
  266. }
  267. else vh.AddUIVertexTriangleStream(m_curvedVerts);
  268. }
  269. //This is called by canvas after UI object's mesh is generated, but before it is rendered.
  270. //Best place to modify the vertices of the object.
  271. public void ModifyTMPMesh(ref List<UIVertex> vertexList)
  272. {
  273. if (!ShouldModify()) return;
  274. //check for changes in text font material that would mean a retesselation in required to get fresh UV's
  275. CheckTextFontMaterial();
  276. //TESSELATING VERTICES--------------------------------------------------------//
  277. //not needed in TMP object, skip to curving
  278. tesselationRequired = false;
  279. curvingRequired = true;
  280. //CURVING VERTICES ---------------------------------------------------------//
  281. if (curvingRequired)
  282. {
  283. //update transformation matrices we're going to use in curving the verts.
  284. CanvasToWorld = myCanvas.transform.localToWorldMatrix;
  285. CanvasToLocal = myCanvas.transform.worldToLocalMatrix;
  286. MyToWorld = transform.localToWorldMatrix;
  287. MyToLocal = transform.worldToLocalMatrix;
  288. //Debug.Log("verts:" + m_curvedVerts.Count + " tess'd:" + m_tesselatedVerts.Count);
  289. for (int i = 0; i < vertexList.Count; i++)
  290. vertexList[i] = CurveVertex(vertexList[i], mySettings.Angle, mySettings.GetCyllinderRadiusInCanvasSpace(), (myCanvas.transform as RectTransform).rect.size);
  291. //set flags
  292. curvingRequired = false;
  293. }
  294. }
  295. #endregion
  296. #region HELPERS
  297. bool ShouldModify()
  298. {
  299. if (!this.IsActive()) return false;
  300. if (mySettings == null) FindParentSettings();
  301. if (mySettings == null || !mySettings.enabled || mySettings.Angle == 1) return false;
  302. return true;
  303. }
  304. void CheckTextFontMaterial()
  305. {
  306. //we check for a sudden change in text's fontMaterialTexture. This is a very hacky way, but the only one working reliably for now.
  307. if (myText)
  308. {
  309. if (myText.cachedTextGenerator.verts.Count > 0 && (myText.cachedTextGenerator.verts[0].uv0.x != savedTextUV0.x && myText.cachedTextGenerator.verts[0].uv0.y != savedTextUV0.y))
  310. {
  311. //Debug.Log("tess req - texture");
  312. savedTextUV0 = myText.cachedTextGenerator.verts[0].uv0;
  313. tesselationRequired = true;
  314. }
  315. }
  316. }
  317. public CurvedUISettings FindParentSettings(bool forceNew = false)
  318. {
  319. if (mySettings == null || forceNew)
  320. {
  321. mySettings = GetComponentInParent<CurvedUISettings>();
  322. if (mySettings == null) return null;
  323. else
  324. {
  325. myCanvas = mySettings.GetComponent<Canvas>();
  326. }
  327. }
  328. return mySettings;
  329. }
  330. #endregion
  331. #region CURVING
  332. /// <summary>
  333. /// Map position of a vertex to a section of a circle. calculated in canvas's local space
  334. /// </summary>
  335. UIVertex CurveVertex(UIVertex input, float cylinder_angle, float radius, Vector2 canvasSize)
  336. {
  337. Vector3 pos = input.position;
  338. //calculated in canvas local space version:
  339. pos = CanvasToLocal.MultiplyPoint3x4(MyToWorld.MultiplyPoint3x4(pos));
  340. // pos = mySettings.VertexPositionToCurvedCanvas(pos);
  341. if (mySettings.Shape == CurvedUISettings.CurvedUIShape.CYLINDER && mySettings.Angle != 0)
  342. {
  343. float theta = (pos.x / canvasSize.x) * cylinder_angle * Mathf.Deg2Rad;
  344. radius += pos.z; // change the radius depending on how far the element is moved in z direction from canvas plane
  345. pos.x = Mathf.Sin(theta) * radius;
  346. pos.z += Mathf.Cos(theta) * radius - radius;
  347. }
  348. else if (mySettings.Shape == CurvedUISettings.CurvedUIShape.CYLINDER_VERTICAL && mySettings.Angle != 0)
  349. {
  350. float theta = (pos.y / canvasSize.y) * cylinder_angle * Mathf.Deg2Rad;
  351. radius += pos.z; // change the radius depending on how far the element is moved in z direction from canvas plane
  352. pos.y = Mathf.Sin(theta) * radius;
  353. pos.z += Mathf.Cos(theta) * radius - radius;
  354. }
  355. else if (mySettings.Shape == CurvedUISettings.CurvedUIShape.RING)
  356. {
  357. float angleOffset = 0;
  358. float r = pos.y.Remap(canvasSize.y * 0.5f * (mySettings.RingFlipVertical ? 1 : -1), -canvasSize.y * 0.5f * (mySettings.RingFlipVertical ? 1 : -1), mySettings.RingExternalDiameter * (1 - mySettings.RingFill) * 0.5f, mySettings.RingExternalDiameter * 0.5f);
  359. float theta = (pos.x / canvasSize.x).Remap(-0.5f, 0.5f, Mathf.PI / 2.0f, cylinder_angle * Mathf.Deg2Rad + Mathf.PI / 2.0f) - angleOffset;
  360. pos.x = r * Mathf.Cos(theta);
  361. pos.y = r * Mathf.Sin(theta);
  362. }
  363. else if (mySettings.Shape == CurvedUISettings.CurvedUIShape.SPHERE && mySettings.Angle != 0)
  364. {
  365. float vangle = mySettings.VerticalAngle;
  366. float savedZ = -pos.z;
  367. if (mySettings.PreserveAspect)
  368. {
  369. vangle = cylinder_angle * (canvasSize.y / canvasSize.x);
  370. }
  371. else
  372. {
  373. radius = canvasSize.x / 2.0f;
  374. if (vangle == 0) return input;
  375. }
  376. //convert planar coordinates to spherical coordinates
  377. float theta = (pos.x / canvasSize.x).Remap(-0.5f, 0.5f, (180 - cylinder_angle) / 2.0f - 90, 180 - (180 - cylinder_angle) / 2.0f - 90);
  378. theta *= Mathf.Deg2Rad;
  379. float gamma = (pos.y / canvasSize.y).Remap(-0.5f, 0.5f, (180 - vangle) / 2.0f, 180 - (180 - vangle) / 2.0f);
  380. gamma *= Mathf.Deg2Rad;
  381. pos.z = Mathf.Sin(gamma) * Mathf.Cos(theta) * (radius + savedZ);
  382. pos.y = -(radius + savedZ) * Mathf.Cos(gamma);
  383. pos.x = Mathf.Sin(gamma) * Mathf.Sin(theta) * (radius + savedZ);
  384. if (mySettings.PreserveAspect)
  385. pos.z -= radius;
  386. }
  387. //4. write output
  388. input.position = MyToLocal.MultiplyPoint3x4(CanvasToWorld.MultiplyPoint3x4(pos));
  389. return input;
  390. }
  391. #endregion
  392. #region TESSELATION
  393. void TesselateGeometry(List<UIVertex> verts)
  394. {
  395. Vector2 tessellatedSize = mySettings.GetTesslationSize();
  396. //find if we are aligned with canvas main axis
  397. TransformMisaligned = !(savedUp.AlmostEqual(Vector3.up.normalized));
  398. // Convert the list from triangles to quads to be used by the tesselation
  399. TrisToQuads(verts);
  400. //do not tesselate text verts. Text usually is small and has plenty of verts already.
  401. #if CURVEDUI_TMP || TMP_PRESENT
  402. if (myText == null && myTMP == null && !DoNotTesselate)
  403. {
  404. #else
  405. if (myText == null && !DoNotTesselate)
  406. {
  407. #endif
  408. // Tesselate quads and apply transformation
  409. int startingVertexCount = verts.Count;
  410. for (int i = 0; i < startingVertexCount; i += 4)
  411. ModifyQuad(verts, i, tessellatedSize);
  412. // Remove old quads
  413. verts.RemoveRange(0, startingVertexCount);
  414. }
  415. }
  416. void ModifyQuad(List<UIVertex> verts, int vertexIndex, Vector2 requiredSize)
  417. {
  418. // Read the existing quad vertices
  419. for (int i = 0; i < 4; i++)
  420. m_quad[i] = verts[vertexIndex + i];
  421. // horizotal and vertical directions of a quad. We're going to tesselate parallel to these.
  422. Vector3 horizontalDir = m_quad[2].position - m_quad[1].position;
  423. Vector3 verticalDir = m_quad[1].position - m_quad[0].position;
  424. //To make sure filled image is properly tesselated, were going to find the bigger side of the quad.
  425. if (myGraphic != null && (myGraphic is Image) && (myGraphic as Image).type == Image.Type.Filled)
  426. {
  427. horizontalDir = (horizontalDir).x > (m_quad[3].position - m_quad[0].position).x ? horizontalDir : m_quad[3].position - m_quad[0].position;
  428. verticalDir = (verticalDir).y > (m_quad[2].position - m_quad[3].position).y ? verticalDir : m_quad[2].position - m_quad[3].position;
  429. }
  430. // Find how many quads we need to create
  431. int horizontalQuads = 1;
  432. int verticalQuads = 1;
  433. // Tesselate vertically only if the recttransform (or parent) is rotated
  434. // This cuts down the time needed to tesselate by 90% in some cases.
  435. if (TransformMisaligned || mySettings.Shape == CurvedUISettings.CurvedUIShape.SPHERE || mySettings.Shape == CurvedUISettings.CurvedUIShape.CYLINDER_VERTICAL)
  436. verticalQuads = Mathf.CeilToInt(verticalDir.magnitude * (1.0f / Mathf.Max(0.0001f, requiredSize.y)));
  437. if (TransformMisaligned || mySettings.Shape != CurvedUISettings.CurvedUIShape.CYLINDER_VERTICAL)
  438. {
  439. horizontalQuads = Mathf.CeilToInt(horizontalDir.magnitude * (1.0f / Mathf.Max(0.0001f, requiredSize.x)));
  440. }
  441. //Debug.Log(this.transform.root.name + "'s panel: hori size:" + horizontalDir.magnitude + " req:" + requiredSize.x + " divs:"+horizontalQuads);
  442. bool oneVert = false;
  443. bool oneHori = false;
  444. // Create the quads!
  445. float yStart = 0.0f;
  446. for (int y = 0; y < verticalQuads || !oneVert; ++y)
  447. {
  448. oneVert = true;
  449. float yEnd = (y + 1.0f) / verticalQuads;
  450. float xStart = 0.0f;
  451. for (int x = 0; x < horizontalQuads || !oneHori; ++x)
  452. {
  453. oneHori = true;
  454. float xEnd = (x + 1.0f) / horizontalQuads;
  455. //Add new quads to list
  456. verts.Add(TesselateQuad(xStart, yStart));
  457. verts.Add(TesselateQuad(xStart, yEnd));
  458. verts.Add(TesselateQuad(xEnd, yEnd));
  459. verts.Add(TesselateQuad(xEnd, yStart));
  460. //begin the next quad where we ened this one
  461. xStart = xEnd;
  462. }
  463. //begin the next row where we ended this one
  464. yStart = yEnd;
  465. }
  466. }
  467. /// <summary>
  468. /// Converts a List of triangle mesh vertices to a list of quad mesh vertices
  469. /// </summary>
  470. void TrisToQuads(List<UIVertex> verts)
  471. {
  472. int vertsInTrisCount = verts.Count;
  473. m_vertsInQuads.Clear();
  474. for (int i = 0; i < vertsInTrisCount; i += 6)
  475. {
  476. // Get four corners from two triangles. Basic UI always comes in quads anyway.
  477. m_vertsInQuads.Add(verts[i + 0]);
  478. m_vertsInQuads.Add(verts[i + 1]);
  479. m_vertsInQuads.Add(verts[i + 2]);
  480. m_vertsInQuads.Add(verts[i + 4]);
  481. }
  482. //add quads to the list and remove the triangles
  483. verts.AddRange(m_vertsInQuads);
  484. verts.RemoveRange(0, vertsInTrisCount);
  485. }
  486. /// <summary>
  487. /// Subdivides a quad into 4 quads.
  488. /// </summary>
  489. /// <returns>The quad.</returns>
  490. /// <param name="quad">Quad.</param>
  491. /// <param name="x">The x coordinate.</param>
  492. /// <param name="y">The y coordinate.</param>
  493. private Vector2 _uv0;
  494. private Vector2 _uv1;
  495. private Vector3 _pos;
  496. UIVertex TesselateQuad(float x, float y)
  497. {
  498. //1. calculate weighting factors
  499. m_weights[0] = (1 - x) * (1 - y);
  500. m_weights[1] = (1 - x) * y;
  501. m_weights[2] = x * y;
  502. m_weights[3] = x * (1 - y);
  503. //2. interpolate all the vertex properties using weighting factors
  504. _uv0 = _uv1 = Vector2.zero;
  505. _pos = Vector3.zero;
  506. for (int i = 0; i < 4; i++)
  507. {
  508. _uv0 += (Vector2)(m_quad[i].uv0 * m_weights[i]);
  509. _uv1 += (Vector2)(m_quad[i].uv1 * m_weights[i]);
  510. _pos += m_quad[i].position * m_weights[i];
  511. //normal += quad[i].normal * weights[i]; // normals should be recalculated to take the curve into account. Skipped to save performance.
  512. //tan += quad[i].tangent * weights[i]; // tangents should be recalculated to take the curve into account. Skipped to save performance.
  513. }
  514. //4. return output
  515. m_ret.position = _pos;
  516. //ret.color = Color32.Lerp(Color32.Lerp(quad[3].color, quad[1].color, y), Color32.Lerp(quad[0].color, quad[2].color, y), x);
  517. m_ret.color = m_quad[0].color; //used instead to save performance. Color lerps are expensive.
  518. m_ret.uv0 = _uv0;
  519. m_ret.uv1 = _uv1;
  520. m_ret.normal = m_quad[0].normal;
  521. m_ret.tangent = m_quad[0].tangent;
  522. return m_ret;
  523. }
  524. #endregion
  525. #region PUBLIC
  526. /// <summary>
  527. /// Force Mesh to be rebuild during canvas' next update loop.
  528. /// </summary>
  529. public void SetDirty()
  530. {
  531. TesselationRequired = true;
  532. }
  533. /// <summary>
  534. /// Force vertices to be tesselated again from original vertices.
  535. /// Set by CurvedUIVertexEffect when updating object's visual property.
  536. /// </summary>
  537. public bool TesselationRequired
  538. {
  539. get { return tesselationRequired; }
  540. set { tesselationRequired = value; }
  541. }
  542. /// <summary>
  543. /// Force vertices to be repositioned on the curved canvas.
  544. /// set by CurvedUIVertexEffect when moving UI objects on canvas.
  545. /// </summary>
  546. public bool CurvingRequired
  547. {
  548. get { return curvingRequired; }
  549. set { curvingRequired = value; }
  550. }
  551. #endregion
  552. }// end of class
  553. } //end of namespace