SpriteFrameModuleBase.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using UnityEngine;
  6. using UnityEditorInternal;
  7. namespace UnityEditor.U2D.Sprites
  8. {
  9. internal class SpriteRectModel : ScriptableObject, ISerializationCallbackReceiver
  10. {
  11. [SerializeField]
  12. private List<SpriteRect> m_SpriteRects;
  13. private HashSet<string> m_Names;
  14. private HashSet<long> m_InternalIds;
  15. private IReadOnlyList<SpriteRect> m_SpriteReadOnlyList;
  16. public IReadOnlyList<SpriteRect> spriteRects
  17. {
  18. get { return m_SpriteReadOnlyList; }
  19. }
  20. private SpriteRectModel()
  21. {
  22. m_Names = new HashSet<string>();
  23. m_InternalIds = new HashSet<long>();
  24. }
  25. public void SetSpriteRects(List<SpriteRect> newSpriteRects)
  26. {
  27. m_SpriteRects = newSpriteRects;
  28. foreach (var spriteRect in m_SpriteRects)
  29. {
  30. m_Names.Add(spriteRect.name);
  31. m_InternalIds.Add(spriteRect.internalID);
  32. }
  33. m_SpriteReadOnlyList = m_SpriteRects.AsReadOnly();
  34. }
  35. public int FindIndex(Predicate<SpriteRect> match)
  36. {
  37. int i = 0;
  38. foreach (var spriteRect in m_SpriteRects)
  39. {
  40. if (match.Invoke(spriteRect))
  41. return i;
  42. i++;
  43. }
  44. return -1;
  45. }
  46. public void Clear()
  47. {
  48. m_SpriteRects = new List<SpriteRect>();
  49. m_InternalIds.Clear();
  50. m_Names.Clear();
  51. m_SpriteReadOnlyList = m_SpriteRects.AsReadOnly();
  52. }
  53. public bool Add(SpriteRect spriteRect)
  54. {
  55. if (m_Names.Contains(spriteRect.name))
  56. return false;
  57. if (spriteRect.internalID != 0 && m_InternalIds.Contains(spriteRect.internalID))
  58. return false;
  59. m_Names.Add(spriteRect.name);
  60. if (spriteRect.internalID != 0)
  61. m_InternalIds.Add(spriteRect.internalID);
  62. m_SpriteRects.Add(spriteRect);
  63. m_SpriteReadOnlyList = m_SpriteRects.AsReadOnly();
  64. return true;
  65. }
  66. public void Remove(SpriteRect spriteRect)
  67. {
  68. m_Names.Remove(spriteRect.name);
  69. if (spriteRect.internalID != 0)
  70. m_InternalIds.Remove(spriteRect.internalID);
  71. m_SpriteRects.Remove(spriteRect);
  72. m_SpriteReadOnlyList = m_SpriteRects.AsReadOnly();
  73. }
  74. public bool HasName(string rectName)
  75. {
  76. return m_Names.Contains(rectName);
  77. }
  78. public bool HasInternalID(long internalID)
  79. {
  80. return m_InternalIds.Contains(internalID);
  81. }
  82. public List<SpriteRect> GetSpriteRects()
  83. {
  84. return m_SpriteRects;
  85. }
  86. public void Rename(string oldName, string newName)
  87. {
  88. m_Names.Remove(oldName);
  89. m_Names.Add(newName);
  90. m_SpriteReadOnlyList = m_SpriteRects.AsReadOnly();
  91. }
  92. void ISerializationCallbackReceiver.OnBeforeSerialize()
  93. {}
  94. void ISerializationCallbackReceiver.OnAfterDeserialize()
  95. {
  96. m_SpriteReadOnlyList = m_SpriteRects.AsReadOnly();
  97. m_Names.Clear();
  98. m_InternalIds.Clear();
  99. foreach (var sprite in m_SpriteReadOnlyList)
  100. {
  101. m_Names.Add(sprite.name);
  102. m_InternalIds.Add(sprite.internalID);
  103. }
  104. }
  105. }
  106. internal abstract partial class SpriteFrameModuleBase : SpriteEditorModuleBase
  107. {
  108. protected static UnityType spriteType = UnityType.FindTypeByName("Sprite");
  109. protected SpriteRectModel m_RectsCache;
  110. protected ITextureDataProvider m_TextureDataProvider;
  111. protected ISpriteEditorDataProvider m_SpriteDataProvider;
  112. string m_ModuleName;
  113. internal enum PivotUnitMode
  114. {
  115. Normalized,
  116. Pixels
  117. }
  118. private PivotUnitMode m_PivotUnitMode = PivotUnitMode.Normalized;
  119. protected SpriteFrameModuleBase(string name, ISpriteEditor sw, IEventSystem es, IUndoSystem us, IAssetDatabase ad)
  120. {
  121. spriteEditor = sw;
  122. eventSystem = es;
  123. undoSystem = us;
  124. assetDatabase = ad;
  125. m_ModuleName = name;
  126. }
  127. // implements ISpriteEditorModule
  128. public override void OnModuleActivate()
  129. {
  130. spriteImportMode = SpriteFrameModule.GetSpriteImportMode(spriteEditor.GetDataProvider<ISpriteEditorDataProvider>());
  131. m_TextureDataProvider = spriteEditor.GetDataProvider<ITextureDataProvider>();
  132. m_SpriteDataProvider = spriteEditor.GetDataProvider<ISpriteEditorDataProvider>();
  133. int width, height;
  134. m_TextureDataProvider.GetTextureActualWidthAndHeight(out width, out height);
  135. textureActualWidth = width;
  136. textureActualHeight = height;
  137. m_RectsCache = ScriptableObject.CreateInstance<SpriteRectModel>();
  138. m_RectsCache.hideFlags = HideFlags.HideAndDontSave;
  139. var spriteList = m_SpriteDataProvider.GetSpriteRects().ToList();
  140. m_RectsCache.SetSpriteRects(spriteList);
  141. spriteEditor.spriteRects = spriteList;
  142. if (spriteEditor.selectedSpriteRect != null)
  143. spriteEditor.selectedSpriteRect = m_RectsCache.spriteRects.FirstOrDefault(x => x.spriteID == spriteEditor.selectedSpriteRect.spriteID);
  144. AddMainUI(spriteEditor.GetMainVisualContainer());
  145. undoSystem.RegisterUndoCallback(UndoCallback);
  146. }
  147. public override void OnModuleDeactivate()
  148. {
  149. if (m_RectsCache != null)
  150. {
  151. undoSystem.ClearUndo(m_RectsCache);
  152. ScriptableObject.DestroyImmediate(m_RectsCache);
  153. m_RectsCache = null;
  154. }
  155. undoSystem.UnregisterUndoCallback(UndoCallback);
  156. RemoveMainUI(spriteEditor.GetMainVisualContainer());
  157. }
  158. public override bool ApplyRevert(bool apply)
  159. {
  160. if (apply)
  161. {
  162. if (containsMultipleSprites)
  163. {
  164. var oldNames = new List<string>();
  165. var newNames = new List<string>();
  166. var ids = new List<long>();
  167. var names = new List<string>();
  168. foreach (var spriteRect in m_RectsCache.spriteRects)
  169. {
  170. if (string.IsNullOrEmpty(spriteRect.name))
  171. spriteRect.name = "Empty";
  172. if (!string.IsNullOrEmpty(spriteRect.originalName))
  173. {
  174. oldNames.Add(spriteRect.originalName);
  175. newNames.Add(spriteRect.name);
  176. }
  177. if (spriteRect.m_RegisterInternalID)
  178. {
  179. ids.Add(spriteRect.internalID);
  180. names.Add(spriteRect.name);
  181. }
  182. spriteRect.m_RegisterInternalID = false;
  183. }
  184. var so = new SerializedObject(m_SpriteDataProvider.targetObject);
  185. if (so.isValid && ids.Count > 0)
  186. {
  187. ImportSettingInternalID.RegisterInternalID(so, spriteType, ids, names);
  188. so.ApplyModifiedPropertiesWithoutUndo();
  189. }
  190. AssetImporter assetImporter = m_SpriteDataProvider.targetObject as AssetImporter;
  191. if (oldNames.Count > 0 && assetImporter != null)
  192. {
  193. assetImporter.RenameSubAssets(spriteType.persistentTypeID, oldNames.ToArray(), newNames.ToArray());
  194. so.ApplyModifiedPropertiesWithoutUndo();
  195. }
  196. }
  197. var array = m_RectsCache != null ? m_RectsCache.spriteRects.ToArray() : null;
  198. m_SpriteDataProvider.SetSpriteRects(array);
  199. if (m_RectsCache != null)
  200. undoSystem.ClearUndo(m_RectsCache);
  201. }
  202. else
  203. {
  204. if (m_RectsCache != null)
  205. {
  206. undoSystem.ClearUndo(m_RectsCache);
  207. var spriteList = m_SpriteDataProvider.GetSpriteRects().ToList();
  208. m_RectsCache.SetSpriteRects(spriteList);
  209. spriteEditor.spriteRects = spriteList;
  210. if (spriteEditor.selectedSpriteRect != null)
  211. spriteEditor.selectedSpriteRect = m_RectsCache.spriteRects.FirstOrDefault(x => x.spriteID == spriteEditor.selectedSpriteRect.spriteID);
  212. }
  213. }
  214. return true;
  215. }
  216. public override string moduleName
  217. {
  218. get { return m_ModuleName; }
  219. }
  220. // injected interfaces
  221. protected IEventSystem eventSystem
  222. {
  223. get;
  224. private set;
  225. }
  226. protected IUndoSystem undoSystem
  227. {
  228. get;
  229. private set;
  230. }
  231. protected IAssetDatabase assetDatabase
  232. {
  233. get;
  234. private set;
  235. }
  236. protected SpriteRect selected
  237. {
  238. get { return spriteEditor.selectedSpriteRect; }
  239. set { spriteEditor.selectedSpriteRect = value; }
  240. }
  241. protected SpriteImportMode spriteImportMode
  242. {
  243. get; private set;
  244. }
  245. protected string spriteAssetPath
  246. {
  247. get { return assetDatabase.GetAssetPath(m_TextureDataProvider.texture); }
  248. }
  249. public bool hasSelected
  250. {
  251. get { return spriteEditor.selectedSpriteRect != null; }
  252. }
  253. public SpriteAlignment selectedSpriteAlignment
  254. {
  255. get { return selected.alignment; }
  256. }
  257. public Vector2 selectedSpritePivot
  258. {
  259. get { return selected.pivot; }
  260. }
  261. private Vector2 selectedSpritePivotInCurUnitMode
  262. {
  263. get
  264. {
  265. return m_PivotUnitMode == PivotUnitMode.Pixels
  266. ? ConvertFromNormalizedToRectSpace(selectedSpritePivot, selectedSpriteRect)
  267. : selectedSpritePivot;
  268. }
  269. }
  270. public int CurrentSelectedSpriteIndex()
  271. {
  272. if (m_RectsCache != null && selected != null)
  273. return m_RectsCache.FindIndex(x => x.spriteID == selected.spriteID);
  274. return -1;
  275. }
  276. public Vector4 selectedSpriteBorder
  277. {
  278. get { return ClampSpriteBorderToRect(selected.border, selected.rect); }
  279. set
  280. {
  281. undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Change Sprite Border");
  282. spriteEditor.SetDataModified();
  283. selected.border = ClampSpriteBorderToRect(value, selected.rect);
  284. }
  285. }
  286. public Rect selectedSpriteRect
  287. {
  288. get { return selected.rect; }
  289. set
  290. {
  291. undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Change Sprite rect");
  292. spriteEditor.SetDataModified();
  293. selected.rect = ClampSpriteRect(value, textureActualWidth, textureActualHeight);
  294. }
  295. }
  296. public string selectedSpriteName
  297. {
  298. get { return selected.name; }
  299. set
  300. {
  301. if (selected.name == value)
  302. return;
  303. if (m_RectsCache.HasName(value))
  304. return;
  305. undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Change Sprite Name");
  306. spriteEditor.SetDataModified();
  307. string oldName = selected.name;
  308. string newName = InternalEditorUtility.RemoveInvalidCharsFromFileName(value, true);
  309. // These can only be changed in sprite multiple mode
  310. if (string.IsNullOrEmpty(selected.originalName) && (newName != oldName))
  311. selected.originalName = oldName;
  312. // Is the name empty?
  313. if (string.IsNullOrEmpty(newName))
  314. newName = oldName;
  315. m_RectsCache.Rename(oldName, newName);
  316. selected.name = newName;
  317. }
  318. }
  319. public int spriteCount
  320. {
  321. get { return m_RectsCache.spriteRects.Count; }
  322. }
  323. public Vector4 GetSpriteBorderAt(int i)
  324. {
  325. return m_RectsCache.spriteRects[i].border;
  326. }
  327. public Rect GetSpriteRectAt(int i)
  328. {
  329. return m_RectsCache.spriteRects[i].rect;
  330. }
  331. public int textureActualWidth { get; private set; }
  332. public int textureActualHeight { get; private set; }
  333. public void SetSpritePivotAndAlignment(Vector2 pivot, SpriteAlignment alignment)
  334. {
  335. undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Change Sprite Pivot");
  336. spriteEditor.SetDataModified();
  337. selected.alignment = alignment;
  338. selected.pivot = SpriteEditorUtility.GetPivotValue(alignment, pivot);
  339. }
  340. public bool containsMultipleSprites
  341. {
  342. get { return spriteImportMode == SpriteImportMode.Multiple; }
  343. }
  344. protected void SnapPivotToSnapPoints(Vector2 pivot, out Vector2 outPivot, out SpriteAlignment outAlignment)
  345. {
  346. Rect rect = selectedSpriteRect;
  347. // Convert from normalized space to texture space
  348. Vector2 texturePos = new Vector2(rect.xMin + rect.width * pivot.x, rect.yMin + rect.height * pivot.y);
  349. Vector2[] snapPoints = GetSnapPointsArray(rect);
  350. // Snapping is now a firm action, it will always snap to one of the snapping points.
  351. SpriteAlignment snappedAlignment = SpriteAlignment.Custom;
  352. float nearestDistance = float.MaxValue;
  353. for (int alignment = 0; alignment < snapPoints.Length; alignment++)
  354. {
  355. float distance = (texturePos - snapPoints[alignment]).magnitude * m_Zoom;
  356. if (distance < nearestDistance)
  357. {
  358. snappedAlignment = (SpriteAlignment)alignment;
  359. nearestDistance = distance;
  360. }
  361. }
  362. outAlignment = snappedAlignment;
  363. outPivot = ConvertFromTextureToNormalizedSpace(snapPoints[(int)snappedAlignment], rect);
  364. }
  365. protected void SnapPivotToPixels(Vector2 pivot, out Vector2 outPivot, out SpriteAlignment outAlignment)
  366. {
  367. outAlignment = SpriteAlignment.Custom;
  368. Rect rect = selectedSpriteRect;
  369. float unitsPerPixelX = 1.0f / rect.width;
  370. float unitsPerPixelY = 1.0f / rect.height;
  371. outPivot.x = Mathf.Round(pivot.x / unitsPerPixelX) * unitsPerPixelX;
  372. outPivot.y = Mathf.Round(pivot.y / unitsPerPixelY) * unitsPerPixelY;
  373. }
  374. private void UndoCallback()
  375. {
  376. UIUndoCallback();
  377. }
  378. protected static Rect ClampSpriteRect(Rect rect, float maxX, float maxY)
  379. {
  380. // Clamp rect to width height
  381. rect = FlipNegativeRect(rect);
  382. Rect newRect = new Rect();
  383. newRect.xMin = Mathf.Clamp(rect.xMin, 0, maxX - 1);
  384. newRect.yMin = Mathf.Clamp(rect.yMin, 0, maxY - 1);
  385. newRect.xMax = Mathf.Clamp(rect.xMax, 1, maxX);
  386. newRect.yMax = Mathf.Clamp(rect.yMax, 1, maxY);
  387. // Prevent width and height to be 0 value after clamping.
  388. if (Mathf.RoundToInt(newRect.width) == 0)
  389. newRect.width = 1;
  390. if (Mathf.RoundToInt(newRect.height) == 0)
  391. newRect.height = 1;
  392. return SpriteEditorUtility.RoundedRect(newRect);
  393. }
  394. protected static Rect FlipNegativeRect(Rect rect)
  395. {
  396. Rect newRect = new Rect();
  397. newRect.xMin = Mathf.Min(rect.xMin, rect.xMax);
  398. newRect.yMin = Mathf.Min(rect.yMin, rect.yMax);
  399. newRect.xMax = Mathf.Max(rect.xMin, rect.xMax);
  400. newRect.yMax = Mathf.Max(rect.yMin, rect.yMax);
  401. return newRect;
  402. }
  403. protected static Vector4 ClampSpriteBorderToRect(Vector4 border, Rect rect)
  404. {
  405. Rect flipRect = FlipNegativeRect(rect);
  406. float w = flipRect.width;
  407. float h = flipRect.height;
  408. Vector4 newBorder = new Vector4();
  409. // Make sure borders are within the width/height and left < right and top < bottom
  410. newBorder.x = Mathf.RoundToInt(Mathf.Clamp(border.x, 0, Mathf.Min(Mathf.Abs(w - border.z), w))); // Left
  411. newBorder.z = Mathf.RoundToInt(Mathf.Clamp(border.z, 0, Mathf.Min(Mathf.Abs(w - newBorder.x), w))); // Right
  412. newBorder.y = Mathf.RoundToInt(Mathf.Clamp(border.y, 0, Mathf.Min(Mathf.Abs(h - border.w), h))); // Bottom
  413. newBorder.w = Mathf.RoundToInt(Mathf.Clamp(border.w, 0, Mathf.Min(Mathf.Abs(h - newBorder.y), h))); // Top
  414. return newBorder;
  415. }
  416. }
  417. }