No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RuleTileEditor.cs 56KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Linq;
  5. using UnityEditorInternal;
  6. using UnityEngine;
  7. using UnityEngine.Tilemaps;
  8. using Object = UnityEngine.Object;
  9. namespace UnityEditor
  10. {
  11. /// <summary>
  12. /// The Editor for a RuleTile.
  13. /// </summary>
  14. [CustomEditor(typeof(RuleTile), true)]
  15. [CanEditMultipleObjects]
  16. public class RuleTileEditor : Editor
  17. {
  18. private const string s_XIconString = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABoSURBVDhPnY3BDcAgDAOZhS14dP1O0x2C/LBEgiNSHvfwyZabmV0jZRUpq2zi6f0DJwdcQOEdwwDLypF0zHLMa9+NQRxkQ+ACOT2STVw/q8eY1346ZlE54sYAhVhSDrjwFymrSFnD2gTZpls2OvFUHAAAAABJRU5ErkJggg==";
  19. private const string s_Arrow0 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACYSURBVDhPzZExDoQwDATzE4oU4QXXcgUFj+YxtETwgpMwXuFcwMFSRMVKKwzZcWzhiMg91jtg34XIntkre5EaT7yjjhI9pOD5Mw5k2X/DdUwFr3cQ7Pu23E/BiwXyWSOxrNqx+ewnsayam5OLBtbOGPUM/r93YZL4/dhpR/amwByGFBz170gNChA6w5bQQMqramBTgJ+Z3A58WuWejPCaHQAAAABJRU5ErkJggg==";
  20. private const string s_Arrow1 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABqSURBVDhPxYzBDYAgEATpxYcd+PVr0fZ2siZrjmMhFz6STIiDs8XMlpEyi5RkO/d66TcgJUB43JfNBqRkSEYDnYjhbKD5GIUkDqRDwoH3+NgTAw+bL/aoOP4DOgH+iwECEt+IlFmkzGHlAYKAWF9R8zUnAAAAAElFTkSuQmCC";
  21. private const string s_Arrow2 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAC0SURBVDhPjVE5EsIwDMxPKFKYF9CagoJH8xhaMskLmEGsjOSRkBzYmU2s9a58TUQUmCH1BWEHweuKP+D8tphrWcAHuIGrjPnPNY8X2+DzEWE+FzrdrkNyg2YGNNfRGlyOaZDJOxBrDhgOowaYW8UW0Vau5ZkFmXbbDr+CzOHKmLinAXMEePyZ9dZkZR+s5QX2O8DY3zZ/sgYcdDqeEVp8516o0QQV1qeMwg6C91toYoLoo+kNt/tpKQEVvFQAAAAASUVORK5CYII=";
  22. private const string s_Arrow3 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAB2SURBVDhPzY1LCoAwEEPnLi48gW5d6p31bH5SMhp0Cq0g+CCLxrzRPqMZ2pRqKG4IqzJc7JepTlbRZXYpWTg4RZE1XAso8VHFKNhQuTjKtZvHUNCEMogO4K3BhvMn9wP4EzoPZ3n0AGTW5fiBVzLAAYTP32C2Ay3agtu9V/9PAAAAAElFTkSuQmCC";
  23. private const string s_Arrow5 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABqSURBVDhPnY3BCYBADASvFx924NevRdvbyoLBmNuDJQMDGjNxAFhK1DyUQ9fvobCdO+j7+sOKj/uSB+xYHZAxl7IR1wNTXJeVcaAVU+614uWfCT9mVUhknMlxDokd15BYsQrJFHeUQ0+MB5ErsPi/6hO1AAAAAElFTkSuQmCC";
  24. private const string s_Arrow6 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACaSURBVDhPxZExEkAwEEVzE4UiTqClUDi0w2hlOIEZsV82xCZmQuPPfFn8t1mirLWf7S5flQOXjd64vCuEKWTKVt+6AayH3tIa7yLg6Qh2FcKFB72jBgJeziA1CMHzeaNHjkfwnAK86f3KUafU2ClHIJSzs/8HHLv09M3SaMCxS7ljw/IYJWzQABOQZ66x4h614ahTCL/WT7BSO51b5Z5hSx88AAAAAElFTkSuQmCC";
  25. private const string s_Arrow7 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABQSURBVDhPYxh8QNle/T8U/4MKEQdAmsz2eICx6W530gygr2aQBmSMphkZYxqErAEXxusKfAYQ7XyyNMIAsgEkaYQBkAFkaYQBsjXSGDAwAAD193z4luKPrAAAAABJRU5ErkJggg==";
  26. private const string s_Arrow8 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACYSURBVDhPxZE9DoAwCIW9iUOHegJXHRw8tIdx1egJTMSHAeMPaHSR5KVQ+KCkCRF91mdz4VDEWVzXTBgg5U1N5wahjHzXS3iFFVRxAygNVaZxJ6VHGIl2D6oUXP0ijlJuTp724FnID1Lq7uw2QM5+thoKth0N+GGyA7IA3+yM77Ag1e2zkey5gCdAg/h8csy+/89v7E+YkgUntOWeVt2SfAAAAABJRU5ErkJggg==";
  27. private const string s_MirrorX = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAAG1JREFUOE+lj9ENwCAIRB2IFdyRfRiuDSaXAF4MrR9P5eRhHGb2Gxp2oaEjIovTXSrAnPNx6hlgyCZ7o6omOdYOldGIZhAziEmOTSfigLV0RYAB9y9f/7kO8L3WUaQyhCgz0dmCL9CwCw172HgBeyG6oloC8fAAAAAASUVORK5CYII=";
  28. private const string s_MirrorY = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAAG9JREFUOE+djckNACEMAykoLdAjHbPyw1IOJ0L7mAejjFlm9hspyd77Kk+kBAjPOXcakJIh6QaKyOE0EB5dSPJAiUmOiL8PMVGxugsP/0OOib8vsY8yYwy6gRyC8CB5QIWgCMKBLgRSkikEUr5h6wOPWfMoCYILdgAAAABJRU5ErkJggg==";
  29. private const string s_MirrorXY = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAHkSURBVDhPrVJLSwJRFJ4cdXwjPlrVJly1kB62cpEguElXKgYKIpaC+EIEEfGxLqI/UES1KaJlEdGmRY9ltCsIWrUJatGm0eZO3xkHIsJdH3zce+ec75z5zr3cf2MMmLdYLA/BYFA2mUyPOPvwnR+GR4PXaDQLLpfrKpVKSb1eT6bV6XTeocAS4sIw7S804BzEZ4IgsGq1ykhcr9dlj8czwPdbxJdBMyX/As/zLiz74Ar2J9lsVulcKpUYut5DnEbsHFwEx8AhtFqtGViD6BOc1ul0B5lMRhGXy2Wm1+ufkBOE/2fsL1FsQpXCiCAcQiAlk0kJRZjf7+9TRxI3Gg0WCoW+IpGISHHERBS5UKUch8n2K5WK3O125VqtpqydTkdZie12W261WjIVo73b7RZVKccZDIZ1q9XaT6fTLB6PD9BFKhQKjITFYpGFw+FBNBpVOgcCARH516pUGZYZXk5R4B3efLBxDM9f1CkWi/WR3ICtGVh6Rd4NPE+p0iEgmkSRLRoMEjYhHpA4kUiIOO8iZRU8AmnadK2/QOOfhnjPZrO95fN5Zdq5XE5yOBwvuKoNxGfBkQ8FzXkPprnj9Xrfm82mDI8fsLON3x5H/Od+RwHdLfDds9vtn0aj8QoF6QH9JzjuG3acpxmu1RgPAAAAAElFTkSuQmCC";
  30. private const string s_Rotated = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAAHdJREFUOE+djssNwCAMQxmIFdgx+2S4Vj4YxWlQgcOT8nuG5u5C732Sd3lfLlmPMR4QhXgrTQaimUlA3EtD+CJlBuQ7aUAUMjEAv9gWCQNEPhHJUkYfZ1kEpcxDzioRzGIlr0Qwi0r+Q5rTgM+AAVcygHgt7+HtBZs/2QVWP8ahAAAAAElFTkSuQmCC";
  31. private const string s_Fixed = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMjHxIGmVAAAA50lEQVQ4T51Ruw6CQBCkwBYKWkIgQAs9gfgCvgb4BML/qWBM9Bdo9QPIuVOQ3JIzosVkc7Mzty9NCPE3lORaKMm1YA/LsnTXdbdhGJ6iKHoVRTEi+r4/OI6zN01Tl/XM7HneLsuyW13XU9u2ous6gYh3kiR327YPsp6ZgyDom6aZYFqiqqqJ8mdZz8xoca64BHjkZT0zY0aVcQbysp6Z4zj+Vvkp65mZttxjOSozdkEzD7KemekcxzRNHxDOHSDiQ/DIy3pmpjtuSJBThStGKMtyRKSOLnSm3DCMz3f+FUpyLZTkOgjtDSWORSDbpbmNAAAAAElFTkSuQmCC";
  32. private static readonly string k_UndoName = L10n.Tr("Change RuleTile");
  33. private static Texture2D[] s_Arrows;
  34. /// <summary>
  35. /// Array of arrow textures used for marking positions for Rule matches
  36. /// </summary>
  37. public static Texture2D[] arrows
  38. {
  39. get
  40. {
  41. if (s_Arrows == null)
  42. {
  43. s_Arrows = new Texture2D[10];
  44. s_Arrows[0] = Base64ToTexture(s_Arrow0);
  45. s_Arrows[1] = Base64ToTexture(s_Arrow1);
  46. s_Arrows[2] = Base64ToTexture(s_Arrow2);
  47. s_Arrows[3] = Base64ToTexture(s_Arrow3);
  48. s_Arrows[5] = Base64ToTexture(s_Arrow5);
  49. s_Arrows[6] = Base64ToTexture(s_Arrow6);
  50. s_Arrows[7] = Base64ToTexture(s_Arrow7);
  51. s_Arrows[8] = Base64ToTexture(s_Arrow8);
  52. s_Arrows[9] = Base64ToTexture(s_XIconString);
  53. }
  54. return s_Arrows;
  55. }
  56. }
  57. private static Texture2D[] s_AutoTransforms;
  58. /// <summary>
  59. /// Arrays of textures used for marking transform Rule matches
  60. /// </summary>
  61. public static Texture2D[] autoTransforms
  62. {
  63. get
  64. {
  65. if (s_AutoTransforms == null)
  66. {
  67. s_AutoTransforms = new Texture2D[5];
  68. s_AutoTransforms[0] = Base64ToTexture(s_Rotated);
  69. s_AutoTransforms[1] = Base64ToTexture(s_MirrorX);
  70. s_AutoTransforms[2] = Base64ToTexture(s_MirrorY);
  71. s_AutoTransforms[3] = Base64ToTexture(s_Fixed);
  72. s_AutoTransforms[4] = Base64ToTexture(s_MirrorXY);
  73. }
  74. return s_AutoTransforms;
  75. }
  76. }
  77. private static class Styles
  78. {
  79. public static readonly GUIContent defaultSprite = EditorGUIUtility.TrTextContent("Default Sprite"
  80. , "The default Sprite set when creating a new Rule.");
  81. public static readonly GUIContent defaultGameObject = EditorGUIUtility.TrTextContent("Default GameObject"
  82. , "The default GameObject set when creating a new Rule.");
  83. public static readonly GUIContent defaultCollider = EditorGUIUtility.TrTextContent("Default Collider"
  84. , "The default Collider Type set when creating a new Rule.");
  85. public static readonly GUIContent emptyRuleTileInfo =
  86. EditorGUIUtility.TrTextContent(
  87. "Drag Sprite or Sprite Texture assets \n" +
  88. " to start creating a Rule Tile.");
  89. public static readonly GUIContent extendNeighbor = EditorGUIUtility.TrTextContent("Extend Neighbor"
  90. , "Enabling this allows you to increase the range of neighbors beyond the 3x3 box.");
  91. public static readonly GUIContent numberOfTilingRules = EditorGUIUtility.TrTextContent(
  92. "Number of Tiling Rules"
  93. , "Change this to adjust of the number of tiling rules.");
  94. public static readonly GUIContent tilingRules = EditorGUIUtility.TrTextContent("Tiling Rules");
  95. public static readonly GUIContent tilingRulesGameObject = EditorGUIUtility.TrTextContent("GameObject"
  96. , "The GameObject for the Tile which fits this Rule.");
  97. public static readonly GUIContent tilingRulesCollider = EditorGUIUtility.TrTextContent("Collider"
  98. , "The Collider Type for the Tile which fits this Rule");
  99. public static readonly GUIContent tilingRulesOutput = EditorGUIUtility.TrTextContent("Output"
  100. , "The Output for the Tile which fits this Rule. Each Output type has its own properties.");
  101. public static readonly GUIContent tilingRulesNoise = EditorGUIUtility.TrTextContent("Noise"
  102. , "The Perlin noise factor when placing the Tile.");
  103. public static readonly GUIContent tilingRulesShuffle = EditorGUIUtility.TrTextContent("Shuffle"
  104. , "The randomized transform given to the Tile when placing it.");
  105. public static readonly GUIContent tilingRulesRandomSize = EditorGUIUtility.TrTextContent("Size"
  106. , "The number of Sprites to randomize from.");
  107. public static readonly GUIContent tilingRulesMinSpeed = EditorGUIUtility.TrTextContent("Min Speed"
  108. , "The minimum speed at which the animation is played.");
  109. public static readonly GUIContent tilingRulesMaxSpeed = EditorGUIUtility.TrTextContent("Max Speed"
  110. , "The maximum speed at which the animation is played.");
  111. public static readonly GUIContent tilingRulesAnimationSize = EditorGUIUtility.TrTextContent("Size"
  112. , "The number of Sprites in the animation.");
  113. public static readonly GUIStyle extendNeighborsLightStyle = new GUIStyle()
  114. {
  115. alignment = TextAnchor.MiddleLeft,
  116. fontStyle = FontStyle.Bold,
  117. fontSize = 10,
  118. normal = new GUIStyleState()
  119. {
  120. textColor = Color.black
  121. }
  122. };
  123. public static readonly GUIStyle extendNeighborsDarkStyle = new GUIStyle()
  124. {
  125. alignment = TextAnchor.MiddleLeft,
  126. fontStyle = FontStyle.Bold,
  127. fontSize = 10,
  128. normal = new GUIStyleState()
  129. {
  130. textColor = Color.white
  131. }
  132. };
  133. }
  134. /// <summary>
  135. /// The RuleTile being edited
  136. /// </summary>
  137. public RuleTile tile => target as RuleTile;
  138. /// <summary>
  139. /// List of Sprites for Drag and Drop
  140. /// </summary>
  141. private List<Sprite> dragAndDropSprites;
  142. /// <summary>
  143. /// Reorderable list for Rules
  144. /// </summary>
  145. private ReorderableList m_ReorderableList;
  146. /// <summary>
  147. /// Whether the RuleTile can extend its neighbors beyond directly adjacent ones
  148. /// </summary>
  149. public bool extendNeighbor;
  150. /// <summary>
  151. /// Preview Utility for rendering previews
  152. /// </summary>
  153. public PreviewRenderUtility m_PreviewUtility;
  154. /// <summary>
  155. /// Grid for rendering previews
  156. /// </summary>
  157. public Grid m_PreviewGrid;
  158. /// <summary>
  159. /// List of Tilemaps for rendering previews
  160. /// </summary>
  161. public List<Tilemap> m_PreviewTilemaps;
  162. /// <summary>
  163. /// List of TilemapRenderers for rendering previews
  164. /// </summary>
  165. public List<TilemapRenderer> m_PreviewTilemapRenderers;
  166. /// <summary>
  167. /// Default height for a Rule Element
  168. /// </summary>
  169. public const float k_DefaultElementHeight = 48f;
  170. /// <summary>
  171. /// Padding between Rule Elements
  172. /// </summary>
  173. public const float k_PaddingBetweenRules = 8f;
  174. /// <summary>
  175. /// Single line height
  176. /// </summary>
  177. public const float k_SingleLineHeight = 18f;
  178. /// <summary>
  179. /// Width for labels
  180. /// </summary>
  181. public const float k_LabelWidth = 80f;
  182. private SerializedProperty m_TilingRules;
  183. private MethodInfo m_ClearCacheMethod;
  184. /// <summary>
  185. /// OnEnable for the RuleTileEditor
  186. /// </summary>
  187. public virtual void OnEnable()
  188. {
  189. m_ReorderableList = new ReorderableList(tile != null ? tile.m_TilingRules : null, typeof(RuleTile.TilingRule), true, true, true, true);
  190. m_ReorderableList.drawHeaderCallback = OnDrawHeader;
  191. m_ReorderableList.drawElementCallback = OnDrawElement;
  192. m_ReorderableList.elementHeightCallback = GetElementHeight;
  193. m_ReorderableList.onChangedCallback = ListUpdated;
  194. m_ReorderableList.onAddDropdownCallback = OnAddDropdownElement;
  195. // Required to adjust element height changes
  196. var rolType = GetType("UnityEditorInternal.ReorderableList");
  197. if (rolType != null)
  198. {
  199. // ClearCache was changed to InvalidateCache in newer versions of Unity.
  200. // To maintain backwards compatibility, we will attempt to retrieve each method in order
  201. m_ClearCacheMethod = rolType.GetMethod("InvalidateCache", BindingFlags.Instance | BindingFlags.NonPublic);
  202. if (m_ClearCacheMethod == null)
  203. m_ClearCacheMethod = rolType.GetMethod("ClearCache", BindingFlags.Instance | BindingFlags.NonPublic);
  204. }
  205. m_TilingRules = serializedObject.FindProperty("m_TilingRules");
  206. }
  207. /// <summary>
  208. /// OnDisable for the RuleTileEditor
  209. /// </summary>
  210. public virtual void OnDisable()
  211. {
  212. DestroyPreview();
  213. }
  214. private void UpdateTilingRuleIds()
  215. {
  216. var existingIdSet = new HashSet<int>();
  217. var usedIdSet = new HashSet<int>();
  218. foreach (var rule in tile.m_TilingRules)
  219. {
  220. existingIdSet.Add(rule.m_Id);
  221. }
  222. foreach (var rule in tile.m_TilingRules)
  223. {
  224. if (usedIdSet.Contains(rule.m_Id))
  225. {
  226. while (existingIdSet.Contains(rule.m_Id))
  227. rule.m_Id++;
  228. existingIdSet.Add(rule.m_Id);
  229. }
  230. usedIdSet.Add(rule.m_Id);
  231. }
  232. }
  233. /// <summary>
  234. /// Get the GUI bounds for a Rule.
  235. /// </summary>
  236. /// <param name="bounds">Cell bounds of the Rule.</param>
  237. /// <param name="rule">Rule to get GUI bounds for.</param>
  238. /// <returns>The GUI bounds for a rule.</returns>
  239. public virtual BoundsInt GetRuleGUIBounds(BoundsInt bounds, RuleTile.TilingRule rule)
  240. {
  241. if (extendNeighbor)
  242. {
  243. bounds.xMin--;
  244. bounds.yMin--;
  245. bounds.xMax++;
  246. bounds.yMax++;
  247. }
  248. bounds.xMin = Mathf.Min(bounds.xMin, -1);
  249. bounds.yMin = Mathf.Min(bounds.yMin, -1);
  250. bounds.xMax = Mathf.Max(bounds.xMax, 2);
  251. bounds.yMax = Mathf.Max(bounds.yMax, 2);
  252. return bounds;
  253. }
  254. /// <summary>
  255. /// Callback when the Rule list is updated
  256. /// </summary>
  257. /// <param name="list">Reorderable list for Rules</param>
  258. public void ListUpdated(ReorderableList list)
  259. {
  260. UpdateTilingRuleIds();
  261. }
  262. private float GetElementHeight(int index)
  263. {
  264. RuleTile.TilingRule rule = tile.m_TilingRules[index];
  265. return GetElementHeight(rule);
  266. }
  267. /// <summary>
  268. /// Gets the GUI element height for a TilingRule
  269. /// </summary>
  270. /// <param name="rule">Rule to get height for</param>
  271. /// <returns>GUI element height for a TilingRule</returns>
  272. public float GetElementHeight(RuleTile.TilingRule rule)
  273. {
  274. BoundsInt bounds = GetRuleGUIBounds(rule.GetBounds(), rule);
  275. float inspectorHeight = GetElementHeight(rule as RuleTile.TilingRuleOutput);
  276. float matrixHeight = GetMatrixSize(bounds).y + 10f;
  277. return Mathf.Max(inspectorHeight, matrixHeight);
  278. }
  279. /// <summary>
  280. /// Gets the GUI element height for a TilingRuleOutput
  281. /// </summary>
  282. /// <param name="rule">Rule to get height for</param>
  283. /// <returns>GUI element height for a TilingRuleOutput </returns>
  284. public float GetElementHeight(RuleTile.TilingRuleOutput rule)
  285. {
  286. float inspectorHeight = k_DefaultElementHeight + k_PaddingBetweenRules;
  287. switch (rule.m_Output)
  288. {
  289. case RuleTile.TilingRuleOutput.OutputSprite.Random:
  290. case RuleTile.TilingRuleOutput.OutputSprite.Animation:
  291. inspectorHeight = k_DefaultElementHeight + k_SingleLineHeight * (rule.m_Sprites.Length + 3) + k_PaddingBetweenRules;
  292. break;
  293. }
  294. return inspectorHeight;
  295. }
  296. /// <summary>
  297. /// Gets the GUI matrix size for a Rule of a RuleTile
  298. /// </summary>
  299. /// <param name="bounds">Cell bounds of the Rule.</param>
  300. /// <returns>Returns the GUI matrix size for a Rule of a RuleTile.</returns>
  301. public virtual Vector2 GetMatrixSize(BoundsInt bounds)
  302. {
  303. return new Vector2(bounds.size.x * k_SingleLineHeight, bounds.size.y * k_SingleLineHeight);
  304. }
  305. /// <summary>
  306. /// Draws the Rule element for the Rule list
  307. /// </summary>
  308. /// <param name="rect">Rect to draw the Rule Element in</param>
  309. /// <param name="index">Index of the Rule Element to draw</param>
  310. /// <param name="isactive">Whether the Rule Element is active</param>
  311. /// <param name="isfocused">Whether the Rule Element is focused</param>
  312. protected virtual void OnDrawElement(Rect rect, int index, bool isactive, bool isfocused)
  313. {
  314. RuleTile.TilingRule rule = tile.m_TilingRules[index];
  315. BoundsInt bounds = GetRuleGUIBounds(rule.GetBounds(), rule);
  316. float yPos = rect.yMin + 2f;
  317. float height = rect.height - k_PaddingBetweenRules;
  318. Vector2 matrixSize = GetMatrixSize(bounds);
  319. Rect spriteRect = new Rect(rect.xMax - k_DefaultElementHeight - 5f, yPos, k_DefaultElementHeight, k_DefaultElementHeight);
  320. Rect matrixRect = new Rect(rect.xMax - matrixSize.x - spriteRect.width - 10f, yPos, matrixSize.x, matrixSize.y);
  321. Rect inspectorRect = new Rect(rect.xMin, yPos, rect.width - matrixSize.x - spriteRect.width - 20f, height);
  322. RuleInspectorOnGUI(inspectorRect, rule);
  323. RuleMatrixOnGUI(tile, matrixRect, bounds, rule);
  324. SpriteOnGUI(spriteRect, rule);
  325. }
  326. private void OnAddElement(object obj)
  327. {
  328. var list = obj as ReorderableList;
  329. RuleTile.TilingRule rule = new RuleTile.TilingRule();
  330. rule.m_Output = RuleTile.TilingRuleOutput.OutputSprite.Single;
  331. rule.m_Sprites[0] = tile.m_DefaultSprite;
  332. rule.m_GameObject = tile.m_DefaultGameObject;
  333. rule.m_ColliderType = tile.m_DefaultColliderType;
  334. var count = m_TilingRules.arraySize;
  335. ResizeRuleTileList(count + 1);
  336. if (list.index == -1 || list.index >= list.count)
  337. tile.m_TilingRules[count] = rule;
  338. else
  339. {
  340. tile.m_TilingRules.Insert(list.index + 1, rule);
  341. tile.m_TilingRules.RemoveAt(count + 1);
  342. if (list.IsSelected(list.index))
  343. list.index += 1;
  344. }
  345. UpdateTilingRuleIds();
  346. }
  347. private void OnDuplicateElement(object obj)
  348. {
  349. var list = obj as ReorderableList;
  350. if (list.index < 0 || list.index >= tile.m_TilingRules.Count)
  351. return;
  352. var copyRule = tile.m_TilingRules[list.index];
  353. var rule = copyRule.Clone();
  354. var count = m_TilingRules.arraySize;
  355. ResizeRuleTileList(count + 1);
  356. tile.m_TilingRules.Insert(list.index + 1, rule);
  357. tile.m_TilingRules.RemoveAt(count + 1);
  358. if (list.IsSelected(list.index))
  359. list.index += 1;
  360. UpdateTilingRuleIds();
  361. }
  362. private void OnAddDropdownElement(Rect rect, ReorderableList list)
  363. {
  364. if (0 <= list.index && list.index < tile.m_TilingRules.Count && list.IsSelected(list.index))
  365. {
  366. GenericMenu menu = new GenericMenu();
  367. menu.AddItem(EditorGUIUtility.TrTextContent("Add"), false, OnAddElement, list);
  368. menu.AddItem(EditorGUIUtility.TrTextContent("Duplicate"), false, OnDuplicateElement, list);
  369. menu.DropDown(rect);
  370. }
  371. else
  372. {
  373. OnAddElement(list);
  374. }
  375. }
  376. /// <summary>
  377. /// Saves any changes to the RuleTile
  378. /// </summary>
  379. public void SaveTile()
  380. {
  381. serializedObject.ApplyModifiedProperties();
  382. EditorUtility.SetDirty(target);
  383. SceneView.RepaintAll();
  384. UpdateAffectedOverrideTiles(tile);
  385. }
  386. /// <summary>
  387. /// Updates all RuleOverrideTiles which override the given RUleTile
  388. /// </summary>
  389. /// <param name="target">RuleTile which has been updated</param>
  390. public static void UpdateAffectedOverrideTiles(RuleTile target)
  391. {
  392. List<RuleOverrideTile> overrideTiles = FindAffectedOverrideTiles(target);
  393. if (overrideTiles != null)
  394. {
  395. foreach (var overrideTile in overrideTiles)
  396. {
  397. Undo.RegisterCompleteObjectUndo(overrideTile, k_UndoName);
  398. Undo.RecordObject(overrideTile.m_InstanceTile, k_UndoName);
  399. overrideTile.Override();
  400. UpdateAffectedOverrideTiles(overrideTile.m_InstanceTile);
  401. EditorUtility.SetDirty(overrideTile);
  402. }
  403. }
  404. }
  405. /// <summary>
  406. /// Gets all RuleOverrideTiles which override the given RuleTile
  407. /// </summary>
  408. /// <param name="target">RuleTile which has been updated</param>
  409. /// <returns>A list of RuleOverrideTiles which override the given RuleTile</returns>
  410. public static List<RuleOverrideTile> FindAffectedOverrideTiles(RuleTile target)
  411. {
  412. List<RuleOverrideTile> overrideTiles = new List<RuleOverrideTile>();
  413. string[] overrideTileGuids = AssetDatabase.FindAssets("t:" + typeof(RuleOverrideTile).Name);
  414. foreach (string overrideTileGuid in overrideTileGuids)
  415. {
  416. string overrideTilePath = AssetDatabase.GUIDToAssetPath(overrideTileGuid);
  417. RuleOverrideTile overrideTile = AssetDatabase.LoadAssetAtPath<RuleOverrideTile>(overrideTilePath);
  418. if (overrideTile.m_Tile == target)
  419. {
  420. overrideTiles.Add(overrideTile);
  421. }
  422. }
  423. return overrideTiles;
  424. }
  425. /// <summary>
  426. /// Draws the header for the Rule list
  427. /// </summary>
  428. /// <param name="rect">GUI Rect to draw the header at</param>
  429. public void OnDrawHeader(Rect rect)
  430. {
  431. GUI.Label(rect, Styles.tilingRules);
  432. var toggleRect = new Rect(rect.xMax - rect.height, rect.y, rect.height, rect.height);
  433. var style = EditorGUIUtility.isProSkin ? Styles.extendNeighborsDarkStyle : Styles.extendNeighborsLightStyle;
  434. var extendSize = style.CalcSize(Styles.extendNeighbor);
  435. var toggleWidth = toggleRect.width + extendSize.x + 5f;
  436. var toggleLabelRect = new Rect(rect.x + rect.width - toggleWidth, rect.y, toggleWidth, rect.height);
  437. EditorGUI.BeginChangeCheck();
  438. extendNeighbor = EditorGUI.Toggle(toggleRect, extendNeighbor);
  439. EditorGUI.LabelField(toggleLabelRect, Styles.extendNeighbor, style);
  440. if (EditorGUI.EndChangeCheck())
  441. {
  442. if (m_ClearCacheMethod != null)
  443. m_ClearCacheMethod.Invoke(m_ReorderableList, null);
  444. }
  445. }
  446. /// <summary>
  447. /// Draws the Inspector GUI for the RuleTileEditor
  448. /// </summary>
  449. public override void OnInspectorGUI()
  450. {
  451. serializedObject.Update();
  452. Undo.RecordObject(target, k_UndoName);
  453. EditorGUI.BeginChangeCheck();
  454. tile.m_DefaultSprite = EditorGUILayout.ObjectField(Styles.defaultSprite, tile.m_DefaultSprite, typeof(Sprite), false) as Sprite;
  455. tile.m_DefaultGameObject = EditorGUILayout.ObjectField(Styles.defaultGameObject, tile.m_DefaultGameObject, typeof(GameObject), false) as GameObject;
  456. tile.m_DefaultColliderType = (Tile.ColliderType)EditorGUILayout.EnumPopup(Styles.defaultCollider, tile.m_DefaultColliderType);
  457. DrawCustomFields(false);
  458. EditorGUILayout.Space();
  459. EditorGUI.BeginChangeCheck();
  460. int count = EditorGUILayout.DelayedIntField(Styles.numberOfTilingRules, tile.m_TilingRules?.Count ?? 0);
  461. if (count < 0)
  462. count = 0;
  463. if (EditorGUI.EndChangeCheck())
  464. ResizeRuleTileList(count);
  465. if (count == 0)
  466. {
  467. Rect rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * 5);
  468. HandleDragAndDrop(rect);
  469. EditorGUI.DrawRect(rect, dragAndDropActive && rect.Contains(Event.current.mousePosition) ? Color.white : Color.black);
  470. var innerRect = new Rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
  471. EditorGUI.DrawRect(innerRect, EditorGUIUtility.isProSkin
  472. ? (Color) new Color32 (56, 56, 56, 255)
  473. : (Color) new Color32 (194, 194, 194, 255));
  474. DisplayClipboardText(Styles.emptyRuleTileInfo, rect);
  475. GUILayout.Space(rect.height);
  476. EditorGUILayout.Space();
  477. }
  478. if (m_ReorderableList != null)
  479. m_ReorderableList.DoLayoutList();
  480. if (EditorGUI.EndChangeCheck())
  481. SaveTile();
  482. GUILayout.Space(k_DefaultElementHeight);
  483. }
  484. private void ResizeRuleTileList(int count)
  485. {
  486. if (m_TilingRules.arraySize == count)
  487. return;
  488. var isEmpty = m_TilingRules.arraySize == 0;
  489. m_TilingRules.arraySize = count;
  490. serializedObject.ApplyModifiedProperties();
  491. if (isEmpty)
  492. {
  493. for (int i = 0; i < count; ++i)
  494. tile.m_TilingRules[i] = new RuleTile.TilingRule();
  495. }
  496. UpdateTilingRuleIds();
  497. }
  498. /// <summary>
  499. /// Draw editor fields for custom properties for the RuleTile
  500. /// </summary>
  501. /// <param name="isOverrideInstance">Whether override fields are drawn</param>
  502. public void DrawCustomFields(bool isOverrideInstance)
  503. {
  504. var customFields = tile.GetCustomFields(isOverrideInstance);
  505. serializedObject.Update();
  506. EditorGUI.BeginChangeCheck();
  507. foreach (var field in customFields)
  508. {
  509. var property = serializedObject.FindProperty(field.Name);
  510. if (property != null)
  511. EditorGUILayout.PropertyField(property, true);
  512. }
  513. if (EditorGUI.EndChangeCheck())
  514. {
  515. serializedObject.ApplyModifiedProperties();
  516. DestroyPreview();
  517. CreatePreview();
  518. }
  519. }
  520. /// <summary>
  521. /// Gets the index for a Rule with the RuleTile to display an arrow.
  522. /// </summary>
  523. /// <param name="position">The relative position of the arrow from the center.</param>
  524. /// <returns>Returns the index for a Rule with the RuleTile to display an arrow.</returns>
  525. public virtual int GetArrowIndex(Vector3Int position)
  526. {
  527. if (Mathf.Abs(position.x) == Mathf.Abs(position.y))
  528. {
  529. if (position.x < 0 && position.y > 0)
  530. return 0;
  531. else if (position.x > 0 && position.y > 0)
  532. return 2;
  533. else if (position.x < 0 && position.y < 0)
  534. return 6;
  535. else if (position.x > 0 && position.y < 0)
  536. return 8;
  537. }
  538. else if (Mathf.Abs(position.x) > Mathf.Abs(position.y))
  539. {
  540. if (position.x > 0)
  541. return 5;
  542. else
  543. return 3;
  544. }
  545. else
  546. {
  547. if (position.y > 0)
  548. return 1;
  549. else
  550. return 7;
  551. }
  552. return -1;
  553. }
  554. /// <summary>
  555. /// Draws a neighbor matching rule
  556. /// </summary>
  557. /// <param name="rect">Rect to draw on</param>
  558. /// <param name="position">The relative position of the arrow from the center</param>
  559. /// <param name="neighbor">The index to the neighbor matching criteria</param>
  560. public virtual void RuleOnGUI(Rect rect, Vector3Int position, int neighbor)
  561. {
  562. switch (neighbor)
  563. {
  564. case RuleTile.TilingRuleOutput.Neighbor.This:
  565. GUI.DrawTexture(rect, arrows[GetArrowIndex(position)]);
  566. break;
  567. case RuleTile.TilingRuleOutput.Neighbor.NotThis:
  568. GUI.DrawTexture(rect, arrows[9]);
  569. break;
  570. default:
  571. var style = new GUIStyle();
  572. style.alignment = TextAnchor.MiddleCenter;
  573. style.fontSize = 10;
  574. GUI.Label(rect, neighbor.ToString(), style);
  575. break;
  576. }
  577. }
  578. /// <summary>
  579. /// Draws a tooltip for the neighbor matching rule
  580. /// </summary>
  581. /// <param name="rect">Rect to draw on</param>
  582. /// <param name="neighbor">The index to the neighbor matching criteria</param>
  583. public void RuleTooltipOnGUI(Rect rect, int neighbor)
  584. {
  585. var allConsts = tile.m_NeighborType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
  586. foreach (var c in allConsts)
  587. {
  588. if ((int)c.GetValue(null) == neighbor)
  589. {
  590. GUI.Label(rect, new GUIContent("", c.Name));
  591. break;
  592. }
  593. }
  594. }
  595. /// <summary>
  596. /// Draws a transform matching rule
  597. /// </summary>
  598. /// <param name="rect">Rect to draw on</param>
  599. /// <param name="ruleTransform">The transform matching criteria</param>
  600. public virtual void RuleTransformOnGUI(Rect rect, RuleTile.TilingRuleOutput.Transform ruleTransform)
  601. {
  602. switch (ruleTransform)
  603. {
  604. case RuleTile.TilingRuleOutput.Transform.Rotated:
  605. GUI.DrawTexture(rect, autoTransforms[0]);
  606. break;
  607. case RuleTile.TilingRuleOutput.Transform.MirrorX:
  608. GUI.DrawTexture(rect, autoTransforms[1]);
  609. break;
  610. case RuleTile.TilingRuleOutput.Transform.MirrorY:
  611. GUI.DrawTexture(rect, autoTransforms[2]);
  612. break;
  613. case RuleTile.TilingRuleOutput.Transform.Fixed:
  614. GUI.DrawTexture(rect, autoTransforms[3]);
  615. break;
  616. case RuleTile.TilingRuleOutput.Transform.MirrorXY:
  617. GUI.DrawTexture(rect, autoTransforms[4]);
  618. break;
  619. }
  620. GUI.Label(rect, new GUIContent("", ruleTransform.ToString()));
  621. }
  622. /// <summary>
  623. /// Handles a neighbor matching Rule update from user mouse input
  624. /// </summary>
  625. /// <param name="rect">Rect containing neighbor matching Rule GUI</param>
  626. /// <param name="tilingRule">Tiling Rule to update neighbor matching rule</param>
  627. /// <param name="neighbors">A dictionary of neighbors</param>
  628. /// <param name="position">The relative position of the neighbor matching Rule</param>
  629. public void RuleNeighborUpdate(Rect rect, RuleTile.TilingRule tilingRule, Dictionary<Vector3Int, int> neighbors, Vector3Int position)
  630. {
  631. if (Event.current.type == EventType.MouseDown && ContainsMousePosition(rect))
  632. {
  633. var allConsts = tile.m_NeighborType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
  634. var neighborConsts = allConsts.Select(c => (int)c.GetValue(null)).ToList();
  635. neighborConsts.Sort();
  636. if (neighbors.ContainsKey(position))
  637. {
  638. int oldIndex = neighborConsts.IndexOf(neighbors[position]);
  639. int newIndex = oldIndex + GetMouseChange();
  640. if (newIndex >= 0 && newIndex < neighborConsts.Count)
  641. {
  642. newIndex = (int)Mathf.Repeat(newIndex, neighborConsts.Count);
  643. neighbors[position] = neighborConsts[newIndex];
  644. }
  645. else
  646. {
  647. neighbors.Remove(position);
  648. }
  649. }
  650. else
  651. {
  652. neighbors.Add(position, neighborConsts[GetMouseChange() == 1 ? 0 : (neighborConsts.Count - 1)]);
  653. }
  654. tilingRule.ApplyNeighbors(neighbors);
  655. GUI.changed = true;
  656. Event.current.Use();
  657. }
  658. }
  659. /// <summary>
  660. /// Handles a transform matching Rule update from user mouse input
  661. /// </summary>
  662. /// <param name="rect">Rect containing transform matching Rule GUI</param>
  663. /// <param name="tilingRule">Tiling Rule to update transform matching rule</param>
  664. public void RuleTransformUpdate(Rect rect, RuleTile.TilingRule tilingRule)
  665. {
  666. if (Event.current.type == EventType.MouseDown && ContainsMousePosition(rect))
  667. {
  668. tilingRule.m_RuleTransform = (RuleTile.TilingRuleOutput.Transform)(int)Mathf.Repeat((int)tilingRule.m_RuleTransform + GetMouseChange(), Enum.GetValues(typeof(RuleTile.TilingRule.Transform)).Length);
  669. GUI.changed = true;
  670. Event.current.Use();
  671. }
  672. }
  673. /// <summary>
  674. /// Determines the current mouse position is within the given Rect.
  675. /// </summary>
  676. /// <param name="rect">Rect to test mouse position for.</param>
  677. /// <returns>True if the current mouse position is within the given Rect. False otherwise.</returns>
  678. public virtual bool ContainsMousePosition(Rect rect)
  679. {
  680. return rect.Contains(Event.current.mousePosition);
  681. }
  682. /// <summary>
  683. /// Gets the offset change for a mouse click input
  684. /// </summary>
  685. /// <returns>The offset change for a mouse click input</returns>
  686. public static int GetMouseChange()
  687. {
  688. return Event.current.button == 1 ? -1 : 1;
  689. }
  690. /// <summary>
  691. /// Draws a Rule Matrix for the given Rule for a RuleTile.
  692. /// </summary>
  693. /// <param name="tile">Tile to draw rule for.</param>
  694. /// <param name="rect">GUI Rect to draw rule at.</param>
  695. /// <param name="bounds">Cell bounds of the Rule.</param>
  696. /// <param name="tilingRule">Rule to draw Rule Matrix for.</param>
  697. public virtual void RuleMatrixOnGUI(RuleTile tile, Rect rect, BoundsInt bounds, RuleTile.TilingRule tilingRule)
  698. {
  699. Handles.color = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.2f) : new Color(0f, 0f, 0f, 0.2f);
  700. float w = rect.width / bounds.size.x;
  701. float h = rect.height / bounds.size.y;
  702. for (int y = 0; y <= bounds.size.y; y++)
  703. {
  704. float top = rect.yMin + y * h;
  705. Handles.DrawLine(new Vector3(rect.xMin, top), new Vector3(rect.xMax, top));
  706. }
  707. for (int x = 0; x <= bounds.size.x; x++)
  708. {
  709. float left = rect.xMin + x * w;
  710. Handles.DrawLine(new Vector3(left, rect.yMin), new Vector3(left, rect.yMax));
  711. }
  712. Handles.color = Color.white;
  713. var neighbors = tilingRule.GetNeighbors();
  714. for (int y = bounds.yMin; y < bounds.yMax; y++)
  715. {
  716. for (int x = bounds.xMin; x < bounds.xMax; x++)
  717. {
  718. Vector3Int pos = new Vector3Int(x, y, 0);
  719. Rect r = new Rect(rect.xMin + (x - bounds.xMin) * w, rect.yMin + (-y + bounds.yMax - 1) * h, w - 1, h - 1);
  720. RuleMatrixIconOnGUI(tilingRule, neighbors, pos, r);
  721. }
  722. }
  723. }
  724. /// <summary>
  725. /// Draws a Rule Matrix Icon for the given matching Rule for a RuleTile with the given position
  726. /// </summary>
  727. /// <param name="tilingRule">Tile to draw rule for.</param>
  728. /// <param name="neighbors">A dictionary of neighbors</param>
  729. /// <param name="position">The relative position of the neighbor matching Rule</param>
  730. /// <param name="rect">GUI Rect to draw icon at</param>
  731. public void RuleMatrixIconOnGUI(RuleTile.TilingRule tilingRule, Dictionary<Vector3Int, int> neighbors, Vector3Int position, Rect rect)
  732. {
  733. using (var check = new EditorGUI.ChangeCheckScope())
  734. {
  735. if (position.x != 0 || position.y != 0)
  736. {
  737. if (neighbors.ContainsKey(position))
  738. {
  739. RuleOnGUI(rect, position, neighbors[position]);
  740. RuleTooltipOnGUI(rect, neighbors[position]);
  741. }
  742. RuleNeighborUpdate(rect, tilingRule, neighbors, position);
  743. }
  744. else
  745. {
  746. RuleTransformOnGUI(rect, tilingRule.m_RuleTransform);
  747. RuleTransformUpdate(rect, tilingRule);
  748. }
  749. if (check.changed)
  750. {
  751. tile.UpdateNeighborPositions();
  752. }
  753. }
  754. }
  755. /// <summary>
  756. /// Draws a Sprite field for the Rule
  757. /// </summary>
  758. /// <param name="rect">Rect to draw Sprite Inspector in</param>
  759. /// <param name="tilingRule">Rule to draw Sprite Inspector for</param>
  760. public virtual void SpriteOnGUI(Rect rect, RuleTile.TilingRuleOutput tilingRule)
  761. {
  762. tilingRule.m_Sprites[0] = EditorGUI.ObjectField(rect, tilingRule.m_Sprites[0], typeof(Sprite), false) as Sprite;
  763. }
  764. /// <summary>
  765. /// Draws an Inspector for the Rule
  766. /// </summary>
  767. /// <param name="rect">Rect to draw Inspector in</param>
  768. /// <param name="tilingRule">Rule to draw Inspector for</param>
  769. public void RuleInspectorOnGUI(Rect rect, RuleTile.TilingRuleOutput tilingRule)
  770. {
  771. float y = rect.yMin;
  772. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesGameObject);
  773. tilingRule.m_GameObject = (GameObject)EditorGUI.ObjectField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), "", tilingRule.m_GameObject, typeof(GameObject), false);
  774. y += k_SingleLineHeight;
  775. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesCollider);
  776. tilingRule.m_ColliderType = (Tile.ColliderType)EditorGUI.EnumPopup(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_ColliderType);
  777. y += k_SingleLineHeight;
  778. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesOutput);
  779. tilingRule.m_Output = (RuleTile.TilingRuleOutput.OutputSprite)EditorGUI.EnumPopup(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_Output);
  780. y += k_SingleLineHeight;
  781. if (tilingRule.m_Output == RuleTile.TilingRuleOutput.OutputSprite.Animation)
  782. {
  783. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesMinSpeed);
  784. tilingRule.m_MinAnimationSpeed = EditorGUI.FloatField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_MinAnimationSpeed);
  785. y += k_SingleLineHeight;
  786. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesMaxSpeed);
  787. tilingRule.m_MaxAnimationSpeed = EditorGUI.FloatField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_MaxAnimationSpeed);
  788. y += k_SingleLineHeight;
  789. }
  790. if (tilingRule.m_Output == RuleTile.TilingRuleOutput.OutputSprite.Random)
  791. {
  792. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesNoise);
  793. tilingRule.m_PerlinScale = EditorGUI.Slider(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_PerlinScale, 0.001f, 0.999f);
  794. y += k_SingleLineHeight;
  795. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesShuffle);
  796. tilingRule.m_RandomTransform = (RuleTile.TilingRuleOutput.Transform)EditorGUI.EnumPopup(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_RandomTransform);
  797. y += k_SingleLineHeight;
  798. }
  799. if (tilingRule.m_Output != RuleTile.TilingRuleOutput.OutputSprite.Single)
  800. {
  801. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight)
  802. , tilingRule.m_Output == RuleTile.TilingRuleOutput.OutputSprite.Animation ? Styles.tilingRulesAnimationSize : Styles.tilingRulesRandomSize);
  803. EditorGUI.BeginChangeCheck();
  804. int newLength = EditorGUI.DelayedIntField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_Sprites.Length);
  805. if (EditorGUI.EndChangeCheck())
  806. Array.Resize(ref tilingRule.m_Sprites, Math.Max(newLength, 1));
  807. y += k_SingleLineHeight;
  808. for (int i = 0; i < tilingRule.m_Sprites.Length; i++)
  809. {
  810. tilingRule.m_Sprites[i] = EditorGUI.ObjectField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_Sprites[i], typeof(Sprite), false) as Sprite;
  811. y += k_SingleLineHeight;
  812. }
  813. }
  814. }
  815. private void DisplayClipboardText(GUIContent clipboardText, Rect position)
  816. {
  817. Color old = GUI.color;
  818. GUI.color = Color.gray;
  819. var infoSize = GUI.skin.label.CalcSize(clipboardText);
  820. Rect rect = new Rect(position.center.x - infoSize.x * .5f
  821. , position.center.y - infoSize.y * .5f
  822. , infoSize.x
  823. , infoSize.y);
  824. GUI.Label(rect, clipboardText);
  825. GUI.color = old;
  826. }
  827. private bool dragAndDropActive
  828. {
  829. get
  830. {
  831. return dragAndDropSprites != null
  832. && dragAndDropSprites.Count > 0;
  833. }
  834. }
  835. private static List<Sprite> GetSpritesFromTexture(Texture2D texture)
  836. {
  837. string path = AssetDatabase.GetAssetPath(texture);
  838. Object[] assets = AssetDatabase.LoadAllAssetsAtPath(path);
  839. List<Sprite> sprites = new List<Sprite>();
  840. foreach (Object asset in assets)
  841. {
  842. if (asset is Sprite)
  843. {
  844. sprites.Add(asset as Sprite);
  845. }
  846. }
  847. return sprites;
  848. }
  849. private static List<Sprite> GetValidSingleSprites(Object[] objects)
  850. {
  851. List<Sprite> result = new List<Sprite>();
  852. foreach (Object obj in objects)
  853. {
  854. if (obj is Sprite sprite)
  855. {
  856. result.Add(sprite);
  857. }
  858. else if (obj is Texture2D texture2D)
  859. {
  860. List<Sprite> sprites = GetSpritesFromTexture(texture2D);
  861. if (sprites.Count > 0)
  862. {
  863. result.AddRange(sprites);
  864. }
  865. }
  866. }
  867. return result;
  868. }
  869. private void HandleDragAndDrop(Rect guiRect)
  870. {
  871. if (DragAndDrop.objectReferences.Length == 0 || !guiRect.Contains(Event.current.mousePosition))
  872. return;
  873. switch (Event.current.type)
  874. {
  875. case EventType.DragUpdated:
  876. {
  877. dragAndDropSprites = GetValidSingleSprites(DragAndDrop.objectReferences);
  878. if (dragAndDropActive)
  879. {
  880. DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
  881. Event.current.Use();
  882. GUI.changed = true;
  883. }
  884. }
  885. break;
  886. case EventType.DragPerform:
  887. {
  888. if (!dragAndDropActive)
  889. return;
  890. Undo.RegisterCompleteObjectUndo(tile, "Drag and Drop to Rule Tile");
  891. ResizeRuleTileList(dragAndDropSprites.Count);
  892. for (int i = 0; i < dragAndDropSprites.Count; ++i)
  893. {
  894. tile.m_TilingRules[i].m_Sprites[0] = dragAndDropSprites[i];
  895. }
  896. DragAndDropClear();
  897. GUI.changed = true;
  898. EditorUtility.SetDirty(tile);
  899. GUIUtility.ExitGUI();
  900. }
  901. break;
  902. case EventType.Repaint:
  903. // Handled in Render()
  904. break;
  905. }
  906. if (Event.current.type == EventType.DragExited ||
  907. Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
  908. {
  909. DragAndDropClear();
  910. }
  911. }
  912. private void DragAndDropClear()
  913. {
  914. dragAndDropSprites = null;
  915. DragAndDrop.visualMode = DragAndDropVisualMode.None;
  916. Event.current.Use();
  917. }
  918. /// <summary>
  919. /// Whether the RuleTile has a preview GUI
  920. /// </summary>
  921. /// <returns>True</returns>
  922. public override bool HasPreviewGUI()
  923. {
  924. return true;
  925. }
  926. /// <summary>
  927. /// Draws the preview GUI for the RuleTile
  928. /// </summary>
  929. /// <param name="rect">Rect to draw the preview GUI</param>
  930. /// <param name="background">The GUIStyle of the background for the preview</param>
  931. public override void OnPreviewGUI(Rect rect, GUIStyle background)
  932. {
  933. if (m_PreviewUtility == null)
  934. CreatePreview();
  935. if (Event.current.type != EventType.Repaint)
  936. return;
  937. m_PreviewUtility.BeginPreview(rect, background);
  938. m_PreviewUtility.camera.orthographicSize = 2;
  939. if (rect.height > rect.width)
  940. m_PreviewUtility.camera.orthographicSize *= rect.height / rect.width;
  941. m_PreviewUtility.camera.Render();
  942. m_PreviewUtility.EndAndDrawPreview(rect);
  943. }
  944. /// <summary>
  945. /// Creates a Preview for the RuleTile.
  946. /// </summary>
  947. protected virtual void CreatePreview()
  948. {
  949. m_PreviewUtility = new PreviewRenderUtility(true);
  950. m_PreviewUtility.camera.orthographic = true;
  951. m_PreviewUtility.camera.orthographicSize = 2;
  952. m_PreviewUtility.camera.transform.position = new Vector3(0, 0, -10);
  953. var previewInstance = new GameObject();
  954. m_PreviewGrid = previewInstance.AddComponent<Grid>();
  955. m_PreviewUtility.AddSingleGO(previewInstance);
  956. m_PreviewTilemaps = new List<Tilemap>();
  957. m_PreviewTilemapRenderers = new List<TilemapRenderer>();
  958. for (int i = 0; i < 4; i++)
  959. {
  960. var previewTilemapGo = new GameObject();
  961. m_PreviewTilemaps.Add(previewTilemapGo.AddComponent<Tilemap>());
  962. m_PreviewTilemapRenderers.Add(previewTilemapGo.AddComponent<TilemapRenderer>());
  963. previewTilemapGo.transform.SetParent(previewInstance.transform, false);
  964. }
  965. for (int x = -2; x <= 0; x++)
  966. for (int y = -1; y <= 1; y++)
  967. m_PreviewTilemaps[0].SetTile(new Vector3Int(x, y, 0), tile);
  968. for (int y = -1; y <= 1; y++)
  969. m_PreviewTilemaps[1].SetTile(new Vector3Int(1, y, 0), tile);
  970. for (int x = -2; x <= 0; x++)
  971. m_PreviewTilemaps[2].SetTile(new Vector3Int(x, -2, 0), tile);
  972. m_PreviewTilemaps[3].SetTile(new Vector3Int(1, -2, 0), tile);
  973. }
  974. /// <summary>
  975. /// Handles cleanup for the Preview GUI
  976. /// </summary>
  977. protected virtual void DestroyPreview()
  978. {
  979. if (m_PreviewUtility != null)
  980. {
  981. m_PreviewUtility.Cleanup();
  982. m_PreviewUtility = null;
  983. m_PreviewGrid = null;
  984. m_PreviewTilemaps = null;
  985. m_PreviewTilemapRenderers = null;
  986. }
  987. }
  988. /// <summary>
  989. /// Renders a static preview Texture2D for a RuleTile asset
  990. /// </summary>
  991. /// <param name="assetPath">Asset path of the RuleTile</param>
  992. /// <param name="subAssets">Arrays of assets from the given Asset path</param>
  993. /// <param name="width">Width of the static preview</param>
  994. /// <param name="height">Height of the static preview </param>
  995. /// <returns>Texture2D containing static preview for the RuleTile asset</returns>
  996. public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
  997. {
  998. if (tile.m_DefaultSprite != null)
  999. {
  1000. Type t = GetType("UnityEditor.SpriteUtility");
  1001. if (t != null)
  1002. {
  1003. MethodInfo method = t.GetMethod("RenderStaticPreview", new[] { typeof(Sprite), typeof(Color), typeof(int), typeof(int) });
  1004. if (method != null)
  1005. {
  1006. object ret = method.Invoke("RenderStaticPreview", new object[] { tile.m_DefaultSprite, Color.white, width, height });
  1007. if (ret is Texture2D)
  1008. return ret as Texture2D;
  1009. }
  1010. }
  1011. }
  1012. return base.RenderStaticPreview(assetPath, subAssets, width, height);
  1013. }
  1014. private static Type GetType(string typeName)
  1015. {
  1016. var type = Type.GetType(typeName);
  1017. if (type != null)
  1018. return type;
  1019. var currentAssembly = Assembly.GetExecutingAssembly();
  1020. var referencedAssemblies = currentAssembly.GetReferencedAssemblies();
  1021. foreach (var assemblyName in referencedAssemblies)
  1022. {
  1023. var assembly = Assembly.Load(assemblyName);
  1024. if (assembly != null)
  1025. {
  1026. type = assembly.GetType(typeName);
  1027. if (type != null)
  1028. return type;
  1029. }
  1030. }
  1031. return null;
  1032. }
  1033. /// <summary>
  1034. /// Converts a Base64 string to a Texture2D
  1035. /// </summary>
  1036. /// <param name="base64">Base64 string containing image data</param>
  1037. /// <returns>Texture2D containing an image from the given Base64 string</returns>
  1038. public static Texture2D Base64ToTexture(string base64)
  1039. {
  1040. Texture2D t = new Texture2D(1, 1);
  1041. t.hideFlags = HideFlags.HideAndDontSave;
  1042. t.LoadImage(Convert.FromBase64String(base64));
  1043. return t;
  1044. }
  1045. /// <summary>
  1046. /// Wrapper for serializing a list of Rules
  1047. /// </summary>
  1048. [Serializable]
  1049. class RuleTileRuleWrapper
  1050. {
  1051. /// <summary>
  1052. /// List of Rules to serialize
  1053. /// </summary>
  1054. [SerializeField]
  1055. public List<RuleTile.TilingRule> rules = new List<RuleTile.TilingRule>();
  1056. }
  1057. /// <summary>
  1058. /// Copies all Rules from a RuleTile to the clipboard
  1059. /// </summary>
  1060. /// <param name="item">MenuCommand storing the RuleTile to copy from</param>
  1061. [MenuItem("CONTEXT/RuleTile/Copy All Rules")]
  1062. public static void CopyAllRules(MenuCommand item)
  1063. {
  1064. RuleTile tile = item.context as RuleTile;
  1065. if (tile == null)
  1066. return;
  1067. RuleTileRuleWrapper rulesWrapper = new RuleTileRuleWrapper();
  1068. rulesWrapper.rules = tile.m_TilingRules;
  1069. var rulesJson = EditorJsonUtility.ToJson(rulesWrapper);
  1070. EditorGUIUtility.systemCopyBuffer = rulesJson;
  1071. }
  1072. /// <summary>
  1073. /// Pastes all Rules from the clipboard to a RuleTile
  1074. /// </summary>
  1075. /// <param name="item">MenuCommand storing the RuleTile to paste to</param>
  1076. [MenuItem("CONTEXT/RuleTile/Paste Rules")]
  1077. public static void PasteRules(MenuCommand item)
  1078. {
  1079. RuleTile tile = item.context as RuleTile;
  1080. if (tile == null)
  1081. return;
  1082. try
  1083. {
  1084. RuleTileRuleWrapper rulesWrapper = new RuleTileRuleWrapper();
  1085. EditorJsonUtility.FromJsonOverwrite(EditorGUIUtility.systemCopyBuffer, rulesWrapper);
  1086. tile.m_TilingRules.AddRange(rulesWrapper.rules);
  1087. }
  1088. catch (Exception)
  1089. {
  1090. Debug.LogError("Unable to paste rules from system copy buffer");
  1091. }
  1092. }
  1093. }
  1094. }