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.

ImportUtilites.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using PDNWrapper;
  7. using Unity.Collections;
  8. using UnityEngine;
  9. #if ENABLE_2D_ANIMATION
  10. using UnityEditor.U2D.Animation;
  11. #endif
  12. namespace UnityEditor.U2D.PSD
  13. {
  14. class UniqueNameGenerator
  15. {
  16. HashSet<int> m_NameHash = new HashSet<int>();
  17. public bool ContainHash(int i)
  18. {
  19. return m_NameHash.Contains(i);
  20. }
  21. public void AddHash(int i)
  22. {
  23. m_NameHash.Add(i);
  24. }
  25. public void AddHash(string name)
  26. {
  27. m_NameHash.Add(GetStringHash(name));
  28. }
  29. public string GetUniqueName(string name, bool logNewNameGenerated = false, UnityEngine.Object context = null)
  30. {
  31. return GetUniqueName(name, m_NameHash);
  32. }
  33. static string GetUniqueName(string name, HashSet<int> stringHash, bool logNewNameGenerated = false, UnityEngine.Object context = null)
  34. {
  35. var sanitizedName = string.Copy(SanitizeName(name));
  36. var uniqueName = sanitizedName;
  37. var index = 1;
  38. while (true)
  39. {
  40. var hash = GetStringHash(uniqueName);
  41. if (!stringHash.Contains(hash))
  42. {
  43. stringHash.Add(hash);
  44. if (logNewNameGenerated && sanitizedName != uniqueName)
  45. Debug.Log($"Asset name {name} is changed to {uniqueName} to ensure uniqueness", context);
  46. return uniqueName;
  47. }
  48. uniqueName = $"{sanitizedName}_{index}";
  49. ++index;
  50. }
  51. }
  52. static int GetStringHash(string str)
  53. {
  54. var md5Hasher = MD5.Create();
  55. var hashed = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(str));
  56. return BitConverter.ToInt32(hashed, 0);
  57. }
  58. public static string SanitizeName(string name)
  59. {
  60. name = name.Replace('\0', ' ');
  61. string newName = null;
  62. // We can't create asset name with these name.
  63. if ((name.Length == 2 && name[0] == '.' && name[1] == '.')
  64. || (name.Length == 1 && name[0] == '.')
  65. || (name.Length == 1 && name[0] == '/'))
  66. newName += name + "_";
  67. if (!string.IsNullOrEmpty(newName))
  68. {
  69. Debug.LogWarning($"File contains layer with invalid name for generating asset. {name} is renamed to {newName}");
  70. return newName;
  71. }
  72. return name;
  73. }
  74. }
  75. class GameObjectCreationFactory : UniqueNameGenerator
  76. {
  77. public GameObjectCreationFactory(IList<string> names)
  78. {
  79. if (names != null)
  80. {
  81. foreach (var name in names)
  82. GetUniqueName(name);
  83. }
  84. }
  85. public GameObject CreateGameObject(string name, params System.Type[] components)
  86. {
  87. var newName = GetUniqueName(name);
  88. return new GameObject(newName, components);
  89. }
  90. }
  91. internal static class ImportUtilities
  92. {
  93. public static string SaveToPng(NativeArray<Color32> buffer, int width, int height)
  94. {
  95. if (!buffer.IsCreated ||
  96. buffer.Length == 0 ||
  97. width == 0 ||
  98. height == 0)
  99. return "No .png generated.";
  100. var texture2D = new Texture2D(width, height);
  101. texture2D.SetPixels32(buffer.ToArray());
  102. var png = texture2D.EncodeToPNG();
  103. var path = Application.dataPath + $"/tex_{System.Guid.NewGuid().ToString()}.png";
  104. var fileStream = System.IO.File.Create(path);
  105. fileStream.Write(png);
  106. fileStream.Close();
  107. UnityEngine.Object.DestroyImmediate(texture2D);
  108. return path;
  109. }
  110. public static void ValidatePSDLayerId(IEnumerable<PSDLayer> oldPsdLayer, IEnumerable<BitmapLayer> layers, UniqueNameGenerator uniqueNameGenerator)
  111. {
  112. // first check if all layers are unique. If not, we use back the previous layer id based on name match
  113. var uniqueIdSet = new HashSet<int>();
  114. var useOldID = false;
  115. foreach(var layer in layers)
  116. {
  117. if (uniqueIdSet.Contains(layer.LayerID))
  118. {
  119. useOldID = true;
  120. break;
  121. }
  122. uniqueIdSet.Add(layer.LayerID);
  123. }
  124. for (var i = 0; i < layers.Count(); ++i)
  125. {
  126. var childBitmapLayer = layers.ElementAt(i);
  127. // fix case 1291323
  128. if (useOldID)
  129. {
  130. var oldLayers = oldPsdLayer.Where(x => x.name == childBitmapLayer.Name);
  131. if (oldLayers.Count() == 0)
  132. oldLayers = oldPsdLayer.Where(x => x.layerID == childBitmapLayer.Name.GetHashCode());
  133. // pick one that is not already on the list
  134. foreach (var ol in oldLayers)
  135. {
  136. if (!uniqueNameGenerator.ContainHash(ol.layerID))
  137. {
  138. childBitmapLayer.LayerID = ol.layerID;
  139. break;
  140. }
  141. }
  142. }
  143. if (uniqueNameGenerator.ContainHash(childBitmapLayer.LayerID))
  144. {
  145. var layerName = UniqueNameGenerator.SanitizeName(childBitmapLayer.Name);
  146. var importWarning = $"Layer {layerName}: LayerId is not unique. Mapping will be done by Layer's name.";
  147. layerName = uniqueNameGenerator.GetUniqueName(layerName);
  148. if (layerName != childBitmapLayer.Name)
  149. importWarning += "\nLayer names are not unique. Please ensure they are unique to for SpriteRect to be mapped back correctly.";
  150. childBitmapLayer.LayerID = layerName.GetHashCode();
  151. Debug.LogWarning(importWarning);
  152. }
  153. else
  154. uniqueNameGenerator.AddHash(childBitmapLayer.LayerID);
  155. if (childBitmapLayer.ChildLayer != null)
  156. {
  157. ValidatePSDLayerId(oldPsdLayer, childBitmapLayer.ChildLayer, uniqueNameGenerator);
  158. }
  159. }
  160. }
  161. public static void TranslatePivotPoint(Vector2 pivot, Rect rect, out SpriteAlignment alignment, out Vector2 customPivot)
  162. {
  163. customPivot = pivot;
  164. if (new Vector2(rect.xMin, rect.yMax) == pivot)
  165. alignment = SpriteAlignment.TopLeft;
  166. else if(new Vector2(rect.center.x, rect.yMax) == pivot)
  167. alignment = SpriteAlignment.TopCenter;
  168. else if(new Vector2(rect.xMax, rect.yMax) == pivot)
  169. alignment = SpriteAlignment.TopRight;
  170. else if(new Vector2(rect.xMin, rect.center.y) == pivot)
  171. alignment = SpriteAlignment.LeftCenter;
  172. else if(new Vector2(rect.center.x, rect.center.y) == pivot)
  173. alignment = SpriteAlignment.Center;
  174. else if(new Vector2(rect.xMax, rect.center.y) == pivot)
  175. alignment = SpriteAlignment.RightCenter;
  176. else if(new Vector2(rect.xMin, rect.yMin) == pivot)
  177. alignment = SpriteAlignment.BottomLeft;
  178. else if(new Vector2(rect.center.x, rect.yMin) == pivot)
  179. alignment = SpriteAlignment.BottomCenter;
  180. else if(new Vector2(rect.xMax, rect.yMin) == pivot)
  181. alignment = SpriteAlignment.BottomRight;
  182. else
  183. alignment = SpriteAlignment.Custom;
  184. }
  185. public static Vector2 GetPivotPoint(Rect rect, SpriteAlignment alignment, Vector2 customPivot)
  186. {
  187. switch (alignment)
  188. {
  189. case SpriteAlignment.TopLeft:
  190. return new Vector2(rect.xMin, rect.yMax);
  191. case SpriteAlignment.TopCenter:
  192. return new Vector2(rect.center.x, rect.yMax);
  193. case SpriteAlignment.TopRight:
  194. return new Vector2(rect.xMax, rect.yMax);
  195. case SpriteAlignment.LeftCenter:
  196. return new Vector2(rect.xMin, rect.center.y);
  197. case SpriteAlignment.Center:
  198. return new Vector2(rect.center.x, rect.center.y);
  199. case SpriteAlignment.RightCenter:
  200. return new Vector2(rect.xMax, rect.center.y);
  201. case SpriteAlignment.BottomLeft:
  202. return new Vector2(rect.xMin, rect.yMin);
  203. case SpriteAlignment.BottomCenter:
  204. return new Vector2(rect.center.x, rect.yMin);
  205. case SpriteAlignment.BottomRight:
  206. return new Vector2(rect.xMax, rect.yMin);
  207. case SpriteAlignment.Custom:
  208. return new Vector2(customPivot.x * rect.width, customPivot.y * rect.height);
  209. }
  210. return Vector2.zero;
  211. }
  212. public static string GetUniqueSpriteName(string name, UniqueNameGenerator generator, bool keepDupilcateSpriteName)
  213. {
  214. if (keepDupilcateSpriteName)
  215. return name;
  216. return generator.GetUniqueName(name);
  217. }
  218. public static bool VisibleInHierarchy(List<PSDLayer> psdGroup, int index)
  219. {
  220. var psdLayer = psdGroup[index];
  221. var parentVisible = true;
  222. if (psdLayer.parentIndex >= 0)
  223. parentVisible = VisibleInHierarchy(psdGroup, psdLayer.parentIndex);
  224. return parentVisible && psdLayer.isVisible;
  225. }
  226. public static bool IsSpriteMetaDataDefault(SpriteMetaData metaData)
  227. {
  228. return metaData.spriteID == default ||
  229. metaData.rect == Rect.zero;
  230. }
  231. #if ENABLE_2D_ANIMATION
  232. public static bool SpriteIsMainFromSpriteLib(List<SpriteCategory> categories, string spriteId, out string categoryName)
  233. {
  234. categoryName = "";
  235. if (categories != null)
  236. {
  237. foreach (var category in categories)
  238. {
  239. var index = category.labels.FindIndex(x => x.spriteId == spriteId);
  240. if (index == 0)
  241. {
  242. categoryName = category.name;
  243. return true;
  244. }
  245. if (index > 0)
  246. return false;
  247. }
  248. }
  249. return true;
  250. }
  251. #endif
  252. }
  253. }