A game about forced loneliness, made by TACStudios
at master 3.6 kB view raw
1using UnityEngine; 2using System; 3using System.Collections; 4using System.Collections.Generic; 5 6namespace UnityEditor.U2D.Common.Path 7{ 8 [Serializable] 9 internal abstract class SerializableSelection<T> : ISelection<T>, ISerializationCallbackReceiver 10 { 11 internal readonly static int kInvalidID = -1; 12 13 [SerializeField] 14 private T[] m_Keys = new T[0]; 15 16 private HashSet<T> m_Selection = new HashSet<T>(); 17 private HashSet<T> m_TemporalSelection = new HashSet<T>(); 18 private bool m_SelectionInProgress = false; 19 20 public int Count 21 { 22 get { return m_Selection.Count + m_TemporalSelection.Count; } 23 } 24 25 public T activeElement 26 { 27 get { return First(); } 28 set 29 { 30 Clear(); 31 Select(value, true); 32 } 33 } 34 35 public T[] elements 36 { 37 get 38 { 39 var set = m_Selection; 40 41 if (m_SelectionInProgress) 42 { 43 var union = new HashSet<T>(m_Selection); 44 union.UnionWith(m_TemporalSelection); 45 set = union; 46 } 47 48 return new List<T>(set).ToArray(); 49 } 50 set 51 { 52 Clear(); 53 foreach(var element in value) 54 Select(element, true); 55 } 56 } 57 58 protected abstract T GetInvalidElement(); 59 60 public void Clear() 61 { 62 GetSelection().Clear(); 63 } 64 65 public void BeginSelection() 66 { 67 m_SelectionInProgress = true; 68 Clear(); 69 } 70 71 public void EndSelection(bool select) 72 { 73 m_SelectionInProgress = false; 74 75 if (select) 76 m_Selection.UnionWith(m_TemporalSelection); 77 else 78 m_Selection.ExceptWith(m_TemporalSelection); 79 80 m_TemporalSelection.Clear(); 81 } 82 83 public bool Select(T element, bool select) 84 { 85 var changed = false; 86 87 if(EqualityComparer<T>.Default.Equals(element, GetInvalidElement())) 88 return changed; 89 90 if (select) 91 changed = GetSelection().Add(element); 92 else if (Contains(element)) 93 changed = GetSelection().Remove(element); 94 95 return changed; 96 } 97 98 public bool Contains(T element) 99 { 100 return m_Selection.Contains(element) || m_TemporalSelection.Contains(element); 101 } 102 103 private HashSet<T> GetSelection() 104 { 105 if (m_SelectionInProgress) 106 return m_TemporalSelection; 107 108 return m_Selection; 109 } 110 111 private T First() 112 { 113 T element = First(m_Selection); 114 115 if(EqualityComparer<T>.Default.Equals(element, GetInvalidElement())) 116 element = First(m_TemporalSelection); 117 118 return element; 119 } 120 121 private T First(HashSet<T> set) 122 { 123 if(set.Count == 0) 124 return GetInvalidElement(); 125 126 using (var enumerator = set.GetEnumerator()) 127 { 128 Debug.Assert(enumerator.MoveNext()); 129 return enumerator.Current; 130 } 131 } 132 133 void ISerializationCallbackReceiver.OnBeforeSerialize() 134 { 135 m_Keys = new List<T>(m_Selection).ToArray(); 136 } 137 138 void ISerializationCallbackReceiver.OnAfterDeserialize() 139 { 140 elements = m_Keys; 141 } 142 } 143}