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.

SpriteOutlineModule.cs 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System;
  4. using System.Linq;
  5. namespace UnityEditor.U2D.Sprites
  6. {
  7. // We need this so that undo/redo works
  8. [Serializable]
  9. internal class SpriteOutline
  10. {
  11. [SerializeField]
  12. public List<Vector2> m_Path = new List<Vector2>();
  13. public void Add(Vector2 point)
  14. {
  15. m_Path.Add(point);
  16. }
  17. public void Insert(int index, Vector2 point)
  18. {
  19. m_Path.Insert(index, point);
  20. }
  21. public void RemoveAt(int index)
  22. {
  23. m_Path.RemoveAt(index);
  24. }
  25. public Vector2 this[int index]
  26. {
  27. get { return m_Path[index]; }
  28. set { m_Path[index] = value; }
  29. }
  30. public int Count
  31. {
  32. get { return m_Path.Count; }
  33. }
  34. public void AddRange(IEnumerable<Vector2> addRange)
  35. {
  36. m_Path.AddRange(addRange);
  37. }
  38. }
  39. // Collection of outlines for a single Sprite
  40. [Serializable]
  41. internal class SpriteOutlineList
  42. {
  43. [SerializeField]
  44. List<SpriteOutline> m_SpriteOutlines = new List<SpriteOutline>();
  45. [SerializeField]
  46. float m_TessellationDetail = 0;
  47. public List<SpriteOutline> spriteOutlines { get { return m_SpriteOutlines; } set { m_SpriteOutlines = value; } }
  48. public GUID spriteID { get; private set; }
  49. public float tessellationDetail
  50. {
  51. get { return m_TessellationDetail; }
  52. set
  53. {
  54. m_TessellationDetail = value;
  55. m_TessellationDetail = Mathf.Min(1, m_TessellationDetail);
  56. m_TessellationDetail = Mathf.Max(0, m_TessellationDetail);
  57. }
  58. }
  59. public SpriteOutlineList(GUID guid)
  60. {
  61. this.spriteID = guid;
  62. m_SpriteOutlines = new List<SpriteOutline>();
  63. }
  64. public SpriteOutlineList(GUID guid, List<Vector2[]> list)
  65. {
  66. this.spriteID = guid;
  67. m_SpriteOutlines = new List<SpriteOutline>(list.Count);
  68. for (int i = 0; i < list.Count; ++i)
  69. {
  70. var newList = new SpriteOutline();
  71. newList.m_Path.AddRange(list[i]);
  72. m_SpriteOutlines.Add(newList);
  73. }
  74. }
  75. public SpriteOutlineList(GUID guid, List<SpriteOutline> list)
  76. {
  77. this.spriteID = guid;
  78. m_SpriteOutlines = list;
  79. }
  80. public List<Vector2[]> ToListVector()
  81. {
  82. var value = new List<Vector2[]>(m_SpriteOutlines.Count);
  83. foreach (var s in m_SpriteOutlines)
  84. {
  85. value.Add(s.m_Path.ToArray());
  86. }
  87. return value;
  88. }
  89. public List<Vector2[]> ToListVectorCapped(Rect rect)
  90. {
  91. var value = ToListVector();
  92. rect.center = Vector2.zero;
  93. foreach (var path in value)
  94. {
  95. for (int i = 0; i < path.Length; ++i)
  96. {
  97. var point = path[i];
  98. path[i] = SpriteOutlineModule.CapPointToRect(point, rect);;
  99. }
  100. }
  101. return value;
  102. }
  103. public SpriteOutline this[int index]
  104. {
  105. get { return IsValidIndex(index) ? m_SpriteOutlines[index] : null; }
  106. set
  107. {
  108. if (IsValidIndex(index))
  109. m_SpriteOutlines[index] = value;
  110. }
  111. }
  112. public static implicit operator List<SpriteOutline>(SpriteOutlineList list)
  113. {
  114. return list != null ? list.m_SpriteOutlines : null;
  115. }
  116. public int Count { get { return m_SpriteOutlines.Count; } }
  117. bool IsValidIndex(int index)
  118. {
  119. return index >= 0 && index < Count;
  120. }
  121. }
  122. // Collection of Sprites' outlines
  123. internal class SpriteOutlineModel : ScriptableObject
  124. {
  125. [SerializeField]
  126. List<SpriteOutlineList> m_SpriteOutlineList = new List<SpriteOutlineList>();
  127. private SpriteOutlineModel()
  128. {}
  129. public SpriteOutlineList this[int index]
  130. {
  131. get { return IsValidIndex(index) ? m_SpriteOutlineList[index] : null; }
  132. set
  133. {
  134. if (IsValidIndex(index))
  135. m_SpriteOutlineList[index] = value;
  136. }
  137. }
  138. public SpriteOutlineList this[GUID guid]
  139. {
  140. get { return m_SpriteOutlineList.FirstOrDefault(x => x.spriteID == guid); }
  141. set
  142. {
  143. var index = m_SpriteOutlineList.FindIndex(x => x.spriteID == guid);
  144. if (index != -1)
  145. m_SpriteOutlineList[index] = value;
  146. }
  147. }
  148. public void AddListVector2(GUID guid, List<Vector2[]> outline)
  149. {
  150. m_SpriteOutlineList.Add(new SpriteOutlineList(guid, outline));
  151. }
  152. public int Count { get { return m_SpriteOutlineList.Count; } }
  153. bool IsValidIndex(int index)
  154. {
  155. return index >= 0 && index < Count;
  156. }
  157. }
  158. [RequireSpriteDataProvider(typeof(ISpriteOutlineDataProvider), typeof(ITextureDataProvider))]
  159. internal class SpriteOutlineModule : SpriteEditorModuleBase
  160. {
  161. class Styles
  162. {
  163. public GUIContent generateOutlineLabel = EditorGUIUtility.TrTextContent("Generate", "Generate new outline based on mesh detail value.");
  164. public GUIContent outlineTolerance = EditorGUIUtility.TrTextContent("Outline Tolerance", "Sets how tight the outline should be from the sprite.");
  165. public GUIContent snapButtonLabel = EditorGUIUtility.TrTextContent("Snap", "Snap points to nearest pixel");
  166. public GUIContent copyButtonLabel = EditorGUIUtility.TrTextContent("Copy", "Copy outline from Sprite");
  167. public GUIContent pasteButtonLabel = EditorGUIUtility.TrTextContent("Paste", "Paste outline to Sprite");
  168. public GUIContent pasteAllButtonLabel = EditorGUIUtility.TrTextContent("Paste All", "Paste outline to all Sprites");
  169. public GUIContent generatingOutlineDialogTitle = EditorGUIUtility.TrTextContent("Outline");
  170. public GUIContent generatingOutlineDialogContent = EditorGUIUtility.TrTextContent("Generating outline {0}/{1}");
  171. public Color spriteBorderColor = new Color(0.25f, 0.5f, 1f, 0.75f);
  172. }
  173. protected SpriteRect m_Selected;
  174. private const float k_HandleSize = 5f;
  175. private readonly string k_DeleteCommandName = EventCommandNames.Delete;
  176. private readonly string k_SoftDeleteCommandName = EventCommandNames.SoftDelete;
  177. private ShapeEditor[] m_ShapeEditors;
  178. private bool m_RequestRepaint;
  179. private Matrix4x4 m_HandleMatrix;
  180. private Vector2 m_MousePosition;
  181. private bool m_Snap = true;
  182. private ShapeEditorRectSelectionTool m_ShapeSelectionUI;
  183. private bool m_WasRectSelecting = false;
  184. private Rect? m_SelectionRect;
  185. private ITexture2D m_OutlineTexture;
  186. private Styles m_Styles;
  187. protected SpriteOutlineModel m_Outline;
  188. private SpriteOutlineList m_CopyOutline = null;
  189. protected ITextureDataProvider m_TextureDataProvider;
  190. public SpriteOutlineModule(ISpriteEditor sem, IEventSystem es, IUndoSystem us, IAssetDatabase ad, IGUIUtility gu, IShapeEditorFactory sef, ITexture2D outlineTexture)
  191. {
  192. spriteEditorWindow = sem;
  193. undoSystem = us;
  194. eventSystem = es;
  195. assetDatabase = ad;
  196. guiUtility = gu;
  197. shapeEditorFactory = sef;
  198. m_OutlineTexture = outlineTexture;
  199. m_ShapeSelectionUI = new ShapeEditorRectSelectionTool(gu);
  200. m_ShapeSelectionUI.RectSelect += RectSelect;
  201. m_ShapeSelectionUI.ClearSelection += ClearSelection;
  202. }
  203. public override string moduleName
  204. {
  205. get { return "Custom Outline"; }
  206. }
  207. public override bool ApplyRevert(bool apply)
  208. {
  209. if (m_Outline != null)
  210. {
  211. if (apply)
  212. {
  213. var outlineDataProvider = spriteEditorWindow.GetDataProvider<ISpriteOutlineDataProvider>();
  214. for (int i = 0; i < m_Outline.Count; ++i)
  215. {
  216. outlineDataProvider.SetOutlines(m_Outline[i].spriteID, m_Outline[i].ToListVector());
  217. outlineDataProvider.SetTessellationDetail(m_Outline[i].spriteID, m_Outline[i].tessellationDetail);
  218. }
  219. }
  220. ScriptableObject.DestroyImmediate(m_Outline);
  221. m_Outline = null;
  222. }
  223. return true;
  224. }
  225. private Styles styles
  226. {
  227. get
  228. {
  229. if (m_Styles == null)
  230. m_Styles = new Styles();
  231. return m_Styles;
  232. }
  233. }
  234. protected virtual List<SpriteOutline> selectedShapeOutline
  235. {
  236. get
  237. {
  238. return m_Outline[m_Selected.spriteID].spriteOutlines;
  239. }
  240. set
  241. {
  242. m_Outline[m_Selected.spriteID].spriteOutlines = value;
  243. }
  244. }
  245. private bool shapeEditorDirty
  246. {
  247. get; set;
  248. }
  249. private bool editingDisabled
  250. {
  251. get { return spriteEditorWindow.editingDisabled; }
  252. }
  253. private ISpriteEditor spriteEditorWindow
  254. {
  255. get; set;
  256. }
  257. private IUndoSystem undoSystem
  258. {
  259. get; set;
  260. }
  261. private IEventSystem eventSystem
  262. {
  263. get; set;
  264. }
  265. private IAssetDatabase assetDatabase
  266. {
  267. get; set;
  268. }
  269. private IGUIUtility guiUtility
  270. {
  271. get; set;
  272. }
  273. private IShapeEditorFactory shapeEditorFactory
  274. {
  275. get; set;
  276. }
  277. private void RectSelect(Rect r, ShapeEditor.SelectionType selectionType)
  278. {
  279. var localRect = EditorGUIExt.FromToRect(ScreenToLocal(r.min), ScreenToLocal(r.max));
  280. m_SelectionRect = localRect;
  281. }
  282. private void ClearSelection()
  283. {
  284. m_RequestRepaint = true;
  285. }
  286. protected virtual void LoadOutline()
  287. {
  288. m_Outline = ScriptableObject.CreateInstance<SpriteOutlineModel>();
  289. m_Outline.hideFlags = HideFlags.HideAndDontSave;
  290. var spriteDataProvider = spriteEditorWindow.GetDataProvider<ISpriteEditorDataProvider>();
  291. var outlineDataProvider = spriteEditorWindow.GetDataProvider<ISpriteOutlineDataProvider>();
  292. foreach (var rect in spriteDataProvider.GetSpriteRects())
  293. {
  294. var outlines = outlineDataProvider.GetOutlines(rect.spriteID);
  295. m_Outline.AddListVector2(rect.spriteID, outlines);
  296. m_Outline[m_Outline.Count - 1].tessellationDetail = outlineDataProvider.GetTessellationDetail(rect.spriteID);
  297. }
  298. }
  299. public override void OnModuleActivate()
  300. {
  301. m_TextureDataProvider = spriteEditorWindow.GetDataProvider<ITextureDataProvider>();
  302. LoadOutline();
  303. GenerateOutlineIfNotExist();
  304. undoSystem.RegisterUndoCallback(UndoRedoPerformed);
  305. shapeEditorDirty = true;
  306. SetupShapeEditor();
  307. spriteEditorWindow.enableMouseMoveEvent = true;
  308. }
  309. void GenerateOutlineIfNotExist()
  310. {
  311. var rectCache = spriteEditorWindow.GetDataProvider<ISpriteEditorDataProvider>().GetSpriteRects();
  312. if (rectCache != null)
  313. {
  314. bool needApply = false;
  315. for (int i = 0; i < rectCache.Length; ++i)
  316. {
  317. var rect = rectCache[i];
  318. if (!HasShapeOutline(rect))
  319. {
  320. EditorUtility.DisplayProgressBar(styles.generatingOutlineDialogTitle.text,
  321. string.Format(styles.generatingOutlineDialogContent.text, i + 1 , rectCache.Length),
  322. (float)(i) / rectCache.Length);
  323. SetupShapeEditorOutline(rect);
  324. needApply = true;
  325. }
  326. }
  327. if (needApply)
  328. {
  329. EditorUtility.ClearProgressBar();
  330. spriteEditorWindow.ApplyOrRevertModification(true);
  331. LoadOutline();
  332. }
  333. }
  334. }
  335. public override void OnModuleDeactivate()
  336. {
  337. undoSystem.UnregisterUndoCallback(UndoRedoPerformed);
  338. CleanupShapeEditors();
  339. m_Selected = null;
  340. spriteEditorWindow.enableMouseMoveEvent = false;
  341. if (m_Outline != null)
  342. {
  343. undoSystem.ClearUndo(m_Outline);
  344. ScriptableObject.DestroyImmediate(m_Outline);
  345. m_Outline = null;
  346. }
  347. }
  348. public override void DoMainGUI()
  349. {
  350. IEvent evt = eventSystem.current;
  351. m_RequestRepaint = false;
  352. m_HandleMatrix = Handles.matrix;
  353. m_MousePosition = Handles.inverseMatrix.MultiplyPoint(eventSystem.current.mousePosition);
  354. if (m_Selected == null || !m_Selected.rect.Contains(m_MousePosition) && !IsMouseOverOutlinePoints() && evt.shift == false)
  355. spriteEditorWindow.HandleSpriteSelection();
  356. HandleCreateNewOutline();
  357. m_WasRectSelecting = m_ShapeSelectionUI.isSelecting;
  358. UpdateShapeEditors();
  359. m_ShapeSelectionUI.OnGUI();
  360. DrawGizmos();
  361. if (m_RequestRepaint || evt.type == EventType.MouseMove)
  362. spriteEditorWindow.RequestRepaint();
  363. }
  364. public override void DoToolbarGUI(Rect drawArea)
  365. {
  366. var style = styles;
  367. Rect snapDrawArea = new Rect(drawArea.x, drawArea.y, EditorStyles.toolbarButton.CalcSize(style.snapButtonLabel).x, drawArea.height);
  368. m_Snap = GUI.Toggle(snapDrawArea, m_Snap, style.snapButtonLabel, EditorStyles.toolbarButton);
  369. using (new EditorGUI.DisabledScope(editingDisabled || m_Selected == null))
  370. {
  371. float totalWidth = drawArea.width - snapDrawArea.width;
  372. drawArea.x = snapDrawArea.xMax;
  373. drawArea.width = EditorStyles.toolbarButton.CalcSize(style.outlineTolerance).x;
  374. totalWidth -= drawArea.width;
  375. if (totalWidth < 0)
  376. drawArea.width += totalWidth;
  377. if (drawArea.width > 0)
  378. GUI.Label(drawArea, style.outlineTolerance, EditorStyles.miniLabel);
  379. drawArea.x += drawArea.width;
  380. drawArea.width = 100;
  381. totalWidth -= drawArea.width;
  382. if (totalWidth < 0)
  383. drawArea.width += totalWidth;
  384. if (drawArea.width > 0)
  385. {
  386. float tesselationValue = m_Selected != null ? m_Outline[m_Selected.spriteID].tessellationDetail : 0;
  387. EditorGUI.BeginChangeCheck();
  388. float oldFieldWidth = EditorGUIUtility.fieldWidth;
  389. float oldLabelWidth = EditorGUIUtility.labelWidth;
  390. EditorGUIUtility.fieldWidth = 35;
  391. EditorGUIUtility.labelWidth = 1;
  392. tesselationValue = EditorGUI.Slider(drawArea, Mathf.Clamp01(tesselationValue), 0, 1);
  393. if (EditorGUI.EndChangeCheck())
  394. {
  395. RecordUndo();
  396. m_Outline[m_Selected.spriteID].tessellationDetail = tesselationValue;
  397. }
  398. EditorGUIUtility.fieldWidth = oldFieldWidth;
  399. EditorGUIUtility.labelWidth = oldLabelWidth;
  400. }
  401. drawArea.x += drawArea.width + 2;
  402. drawArea.width = EditorStyles.toolbarButton.CalcSize(style.generateOutlineLabel).x;
  403. totalWidth -= drawArea.width;
  404. if (totalWidth < 0)
  405. drawArea.width += totalWidth;
  406. if (drawArea.width > 0 && GUI.Button(drawArea, style.generateOutlineLabel, EditorStyles.toolbarButton))
  407. {
  408. RecordUndo();
  409. selectedShapeOutline.Clear();
  410. SetupShapeEditorOutline(m_Selected);
  411. spriteEditorWindow.SetDataModified();
  412. shapeEditorDirty = true;
  413. }
  414. using (new EditorGUI.DisabledScope(m_Selected == null || !HasShapeOutline(m_Selected)))
  415. {
  416. drawArea.x += drawArea.width + 2;
  417. drawArea.width = EditorStyles.toolbarButton.CalcSize(style.copyButtonLabel).x;
  418. totalWidth -= drawArea.width;
  419. if (totalWidth < 0)
  420. drawArea.width += totalWidth;
  421. if (drawArea.width > 0 && GUI.Button(drawArea, style.copyButtonLabel, EditorStyles.toolbarButton))
  422. {
  423. Copy();
  424. }
  425. }
  426. using (new EditorGUI.DisabledScope(m_Selected == null || m_CopyOutline == null))
  427. {
  428. drawArea.x += drawArea.width;
  429. drawArea.width = EditorStyles.toolbarButton.CalcSize(style.pasteButtonLabel).x;
  430. totalWidth -= drawArea.width;
  431. if (totalWidth < 0)
  432. drawArea.width += totalWidth;
  433. if (drawArea.width > 0 && GUI.Button(drawArea, style.pasteButtonLabel, EditorStyles.toolbarButton))
  434. {
  435. Paste();
  436. }
  437. }
  438. using (new EditorGUI.DisabledScope(m_CopyOutline == null))
  439. {
  440. drawArea.x += drawArea.width;
  441. drawArea.width = EditorStyles.toolbarButton.CalcSize(style.pasteAllButtonLabel).x;
  442. totalWidth -= drawArea.width;
  443. if (totalWidth < 0)
  444. drawArea.width += totalWidth;
  445. if (drawArea.width > 0 && GUI.Button(drawArea, style.pasteAllButtonLabel, EditorStyles.toolbarButton))
  446. {
  447. PasteAll();
  448. }
  449. }
  450. }
  451. }
  452. public override void DoPostGUI()
  453. {}
  454. public override bool CanBeActivated()
  455. {
  456. return SpriteFrameModule.GetSpriteImportMode(spriteEditorWindow.GetDataProvider<ISpriteEditorDataProvider>()) != SpriteImportMode.None;
  457. }
  458. private void RecordUndo()
  459. {
  460. undoSystem.RegisterCompleteObjectUndo(m_Outline, "Outline changed");
  461. }
  462. public void CreateNewOutline(Rect rectOutline)
  463. {
  464. Rect rect = m_Selected.rect;
  465. if (rect.Contains(rectOutline.min) && rect.Contains(rectOutline.max))
  466. {
  467. RecordUndo();
  468. SpriteOutline so = new SpriteOutline();
  469. Vector2 outlineOffset = new Vector2(0.5f * rect.width + rect.x, 0.5f * rect.height + rect.y);
  470. Rect selectionRect = new Rect(rectOutline);
  471. selectionRect.min = SnapPoint(rectOutline.min);
  472. selectionRect.max = SnapPoint(rectOutline.max);
  473. so.Add(CapPointToRect(new Vector2(selectionRect.xMin, selectionRect.yMin), rect) - outlineOffset);
  474. so.Add(CapPointToRect(new Vector2(selectionRect.xMin, selectionRect.yMax), rect) - outlineOffset);
  475. so.Add(CapPointToRect(new Vector2(selectionRect.xMax, selectionRect.yMax), rect) - outlineOffset);
  476. so.Add(CapPointToRect(new Vector2(selectionRect.xMax, selectionRect.yMin), rect) - outlineOffset);
  477. selectedShapeOutline.Add(so);
  478. spriteEditorWindow.SetDataModified();
  479. shapeEditorDirty = true;
  480. }
  481. }
  482. private void HandleCreateNewOutline()
  483. {
  484. if (m_WasRectSelecting && m_ShapeSelectionUI.isSelecting == false && m_SelectionRect != null && m_Selected != null)
  485. {
  486. bool createNewOutline = true;
  487. foreach (var se in m_ShapeEditors)
  488. {
  489. if (se.selectedPoints.Count != 0)
  490. {
  491. createNewOutline = false;
  492. break;
  493. }
  494. }
  495. if (createNewOutline)
  496. CreateNewOutline(m_SelectionRect.Value);
  497. }
  498. m_SelectionRect = null;
  499. }
  500. public void UpdateShapeEditors()
  501. {
  502. SetupShapeEditor();
  503. if (m_Selected != null)
  504. {
  505. IEvent currentEvent = eventSystem.current;
  506. var wantsDelete = currentEvent.type == EventType.ExecuteCommand && (currentEvent.commandName == k_SoftDeleteCommandName || currentEvent.commandName == k_DeleteCommandName);
  507. for (int i = 0; i < m_ShapeEditors.Length; ++i)
  508. {
  509. if (m_ShapeEditors[i].GetPointsCount() == 0)
  510. continue;
  511. m_ShapeEditors[i].inEditMode = true;
  512. m_ShapeEditors[i].OnGUI();
  513. if (shapeEditorDirty)
  514. break;
  515. }
  516. if (wantsDelete)
  517. {
  518. // remove outline which have lesser than 3 points
  519. for (int i = selectedShapeOutline.Count - 1; i >= 0; --i)
  520. {
  521. if (selectedShapeOutline[i].Count < 3)
  522. {
  523. selectedShapeOutline.RemoveAt(i);
  524. shapeEditorDirty = true;
  525. }
  526. }
  527. }
  528. }
  529. }
  530. private bool IsMouseOverOutlinePoints()
  531. {
  532. if (m_Selected == null)
  533. return false;
  534. Vector2 outlineOffset = new Vector2(0.5f * m_Selected.rect.width + m_Selected.rect.x, 0.5f * m_Selected.rect.height + m_Selected.rect.y);
  535. float handleSize = GetHandleSize();
  536. Rect r = new Rect(0, 0, handleSize * 2, handleSize * 2);
  537. for (int i = 0; i < selectedShapeOutline.Count; ++i)
  538. {
  539. var outline = selectedShapeOutline[i];
  540. for (int j = 0; j < outline.Count; ++j)
  541. {
  542. r.center = outline[j] + outlineOffset;
  543. if (r.Contains(m_MousePosition))
  544. return true;
  545. }
  546. }
  547. return false;
  548. }
  549. private float GetHandleSize()
  550. {
  551. return k_HandleSize / m_HandleMatrix.m00;
  552. }
  553. private void CleanupShapeEditors()
  554. {
  555. if (m_ShapeEditors != null)
  556. {
  557. for (int i = 0; i < m_ShapeEditors.Length; ++i)
  558. {
  559. for (int j = 0; j < m_ShapeEditors.Length; ++j)
  560. {
  561. if (i != j)
  562. m_ShapeEditors[j].UnregisterFromShapeEditor(m_ShapeEditors[i]);
  563. }
  564. m_ShapeEditors[i].OnDisable();
  565. }
  566. }
  567. m_ShapeEditors = null;
  568. }
  569. public void SetupShapeEditor()
  570. {
  571. if (shapeEditorDirty || m_Selected != spriteEditorWindow.selectedSpriteRect)
  572. {
  573. m_Selected = spriteEditorWindow.selectedSpriteRect;
  574. CleanupShapeEditors();
  575. if (m_Selected != null)
  576. {
  577. if (!HasShapeOutline(m_Selected))
  578. SetupShapeEditorOutline(m_Selected);
  579. m_ShapeEditors = new ShapeEditor[selectedShapeOutline.Count];
  580. for (int i = 0; i < selectedShapeOutline.Count; ++i)
  581. {
  582. int outlineIndex = i;
  583. m_ShapeEditors[i] = shapeEditorFactory.CreateShapeEditor();
  584. m_ShapeEditors[i].SetRectSelectionTool(m_ShapeSelectionUI);
  585. m_ShapeEditors[i].LocalToWorldMatrix = () => m_HandleMatrix;
  586. m_ShapeEditors[i].LocalToScreen = (point) => Handles.matrix.MultiplyPoint(point);
  587. m_ShapeEditors[i].ScreenToLocal = ScreenToLocal;
  588. m_ShapeEditors[i].RecordUndo = RecordUndo;
  589. m_ShapeEditors[i].GetHandleSize = GetHandleSize;
  590. m_ShapeEditors[i].lineTexture = m_OutlineTexture;
  591. m_ShapeEditors[i].Snap = SnapPoint;
  592. m_ShapeEditors[i].GetPointPosition = (index) => GetPointPosition(outlineIndex, index);
  593. m_ShapeEditors[i].SetPointPosition = (index, position) => SetPointPosition(outlineIndex, index, position);
  594. m_ShapeEditors[i].InsertPointAt = (index, position) => InsertPointAt(outlineIndex, index, position);
  595. m_ShapeEditors[i].RemovePointAt = (index) => RemovePointAt(outlineIndex, index);
  596. m_ShapeEditors[i].GetPointsCount = () => GetPointsCount(outlineIndex);
  597. }
  598. for (int i = 0; i < selectedShapeOutline.Count; ++i)
  599. {
  600. for (int j = 0; j < selectedShapeOutline.Count; ++j)
  601. {
  602. if (i != j)
  603. m_ShapeEditors[j].RegisterToShapeEditor(m_ShapeEditors[i]);
  604. }
  605. }
  606. }
  607. else
  608. {
  609. m_ShapeEditors = new ShapeEditor[0];
  610. }
  611. }
  612. shapeEditorDirty = false;
  613. }
  614. protected virtual bool HasShapeOutline(SpriteRect spriteRect)
  615. {
  616. var outline = m_Outline[spriteRect.spriteID] != null ? m_Outline[spriteRect.spriteID].spriteOutlines : null;
  617. return outline != null;
  618. }
  619. protected virtual void SetupShapeEditorOutline(SpriteRect spriteRect)
  620. {
  621. var outline = m_Outline[spriteRect.spriteID];
  622. var outlines = GenerateSpriteRectOutline(spriteRect.rect,
  623. Math.Abs(outline.tessellationDetail - (-1f)) < Mathf.Epsilon ? 0 : outline.tessellationDetail,
  624. 0, m_TextureDataProvider);
  625. if (outlines.Count == 0)
  626. {
  627. Vector2 halfSize = spriteRect.rect.size * 0.5f;
  628. outlines = new List<SpriteOutline>()
  629. {
  630. new SpriteOutline()
  631. {
  632. m_Path = new List<Vector2>()
  633. {
  634. new Vector2(-halfSize.x, -halfSize.y),
  635. new Vector2(-halfSize.x, halfSize.y),
  636. new Vector2(halfSize.x, halfSize.y),
  637. new Vector2(halfSize.x, -halfSize.y),
  638. }
  639. }
  640. };
  641. }
  642. m_Outline[spriteRect.spriteID].spriteOutlines = outlines;
  643. }
  644. public Vector3 SnapPoint(Vector3 position)
  645. {
  646. if (m_Snap)
  647. {
  648. position.x = Mathf.RoundToInt(position.x);
  649. position.y = Mathf.RoundToInt(position.y);
  650. }
  651. return position;
  652. }
  653. public Vector3 GetPointPosition(int outlineIndex, int pointIndex)
  654. {
  655. if (outlineIndex >= 0 && outlineIndex < selectedShapeOutline.Count)
  656. {
  657. var outline = selectedShapeOutline[outlineIndex];
  658. if (pointIndex >= 0 && pointIndex < outline.Count)
  659. {
  660. return ConvertSpriteRectSpaceToTextureSpace(outline[pointIndex]);
  661. }
  662. }
  663. return new Vector3(float.NaN, float.NaN, float.NaN);
  664. }
  665. public void SetPointPosition(int outlineIndex, int pointIndex, Vector3 position)
  666. {
  667. selectedShapeOutline[outlineIndex][pointIndex] = ConvertTextureSpaceToSpriteRectSpace(CapPointToRect(position, m_Selected.rect));
  668. spriteEditorWindow.SetDataModified();
  669. }
  670. public void InsertPointAt(int outlineIndex, int pointIndex, Vector3 position)
  671. {
  672. selectedShapeOutline[outlineIndex].Insert(pointIndex, ConvertTextureSpaceToSpriteRectSpace(CapPointToRect(position, m_Selected.rect)));
  673. spriteEditorWindow.SetDataModified();
  674. }
  675. public void RemovePointAt(int outlineIndex, int i)
  676. {
  677. selectedShapeOutline[outlineIndex].RemoveAt(i);
  678. spriteEditorWindow.SetDataModified();
  679. }
  680. public int GetPointsCount(int outlineIndex)
  681. {
  682. return selectedShapeOutline[outlineIndex].Count;
  683. }
  684. private Vector2 ConvertSpriteRectSpaceToTextureSpace(Vector2 value)
  685. {
  686. Vector2 outlineOffset = new Vector2(0.5f * m_Selected.rect.width + m_Selected.rect.x, 0.5f * m_Selected.rect.height + m_Selected.rect.y);
  687. value += outlineOffset;
  688. return value;
  689. }
  690. private Vector2 ConvertTextureSpaceToSpriteRectSpace(Vector2 value)
  691. {
  692. Vector2 outlineOffset = new Vector2(0.5f * m_Selected.rect.width + m_Selected.rect.x, 0.5f * m_Selected.rect.height + m_Selected.rect.y);
  693. value -= outlineOffset;
  694. return value;
  695. }
  696. private Vector3 ScreenToLocal(Vector2 point)
  697. {
  698. return Handles.inverseMatrix.MultiplyPoint(point);
  699. }
  700. private void UndoRedoPerformed()
  701. {
  702. shapeEditorDirty = true;
  703. }
  704. private void DrawGizmos()
  705. {
  706. if (eventSystem.current.type == EventType.Repaint)
  707. {
  708. var selected = spriteEditorWindow.selectedSpriteRect;
  709. if (selected != null)
  710. {
  711. SpriteEditorUtility.BeginLines(styles.spriteBorderColor);
  712. SpriteEditorUtility.DrawBox(selected.rect);
  713. SpriteEditorUtility.EndLines();
  714. }
  715. }
  716. }
  717. protected static List<SpriteOutline> GenerateSpriteRectOutline(Rect rect, float detail, byte alphaTolerance, ITextureDataProvider textureProvider)
  718. {
  719. List<SpriteOutline> outline = new List<SpriteOutline>();
  720. var texture = textureProvider.GetReadableTexture2D();
  721. if (texture != null)
  722. {
  723. Vector2[][] paths;
  724. // we might have a texture that is capped because of max size or NPOT.
  725. // in that case, we need to convert values from capped space to actual texture space and back.
  726. int actualWidth = 0, actualHeight = 0;
  727. int cappedWidth, cappedHeight;
  728. textureProvider.GetTextureActualWidthAndHeight(out actualWidth, out actualHeight);
  729. cappedWidth = texture.width;
  730. cappedHeight = texture.height;
  731. Vector2 scale = new Vector2(cappedWidth / (float)actualWidth, cappedHeight / (float)actualHeight);
  732. Rect spriteRect = rect;
  733. spriteRect.xMin *= scale.x;
  734. spriteRect.xMax *= scale.x;
  735. spriteRect.yMin *= scale.y;
  736. spriteRect.yMax *= scale.y;
  737. UnityEditor.Sprites.SpriteUtility.GenerateOutline(texture, spriteRect, detail, alphaTolerance, true, out paths);
  738. Rect capRect = new Rect();
  739. capRect.size = rect.size;
  740. capRect.center = Vector2.zero;
  741. for (int j = 0; j < paths.Length; ++j)
  742. {
  743. SpriteOutline points = new SpriteOutline();
  744. foreach (Vector2 v in paths[j])
  745. points.Add(CapPointToRect(new Vector2(v.x / scale.x, v.y / scale.y), capRect));
  746. outline.Add(points);
  747. }
  748. }
  749. return outline;
  750. }
  751. public void Copy()
  752. {
  753. if (m_Selected == null || !HasShapeOutline(m_Selected))
  754. return;
  755. m_CopyOutline = new SpriteOutlineList(m_Selected.spriteID, m_Outline[m_Selected.spriteID].ToListVectorCapped(m_Selected.rect));
  756. }
  757. public void Paste()
  758. {
  759. if (m_Selected == null || m_CopyOutline == null)
  760. return;
  761. RecordUndo();
  762. m_Outline[m_Selected.spriteID] = new SpriteOutlineList(m_Selected.spriteID, m_CopyOutline.ToListVectorCapped(m_Selected.rect));
  763. spriteEditorWindow.SetDataModified();
  764. shapeEditorDirty = true;
  765. }
  766. public void PasteAll()
  767. {
  768. if (m_CopyOutline == null)
  769. return;
  770. RecordUndo();
  771. var rectCache = spriteEditorWindow.GetDataProvider<ISpriteEditorDataProvider>().GetSpriteRects();
  772. if (rectCache != null)
  773. {
  774. foreach (var spriteRect in rectCache)
  775. {
  776. var outlines = m_CopyOutline.ToListVectorCapped(spriteRect.rect);
  777. m_Outline[spriteRect.spriteID] = new SpriteOutlineList(spriteRect.spriteID, outlines);
  778. }
  779. }
  780. spriteEditorWindow.SetDataModified();
  781. shapeEditorDirty = true;
  782. }
  783. internal static Vector2 CapPointToRect(Vector2 so, Rect r)
  784. {
  785. so.x = Mathf.Min(r.xMax, so.x);
  786. so.x = Mathf.Max(r.xMin, so.x);
  787. so.y = Mathf.Min(r.yMax, so.y);
  788. so.y = Mathf.Max(r.yMin, so.y);
  789. return so;
  790. }
  791. }
  792. }