├── .gitattributes ├── .gitignore ├── Archon.SwissArmyLib.Editor ├── Archon.SwissArmyLib.Editor.csproj ├── Properties │ └── AssemblyInfo.cs ├── ResourceSystem │ └── ResourcePoolEditor.cs └── Utils │ ├── ExecutionOrderManager.cs │ └── ReadOnlyDrawer.cs ├── Archon.SwissArmyLib.sln ├── Archon.SwissArmyLib ├── Archon.SwissArmyLib.csproj ├── Archon.SwissArmyLib.csproj.DotSettings ├── Automata │ ├── BaseState.cs │ ├── FiniteStateMachine.cs │ ├── IPdaState.cs │ ├── IState.cs │ ├── PdaState.cs │ └── PushdownAutomaton.cs ├── Collections │ ├── DelayedList.cs │ ├── DictionaryWithDefault.cs │ ├── Grid2D.cs │ ├── Grid3D.cs │ ├── PooledLinkedList.cs │ └── PrioritizedList.cs ├── Coroutines │ ├── BetterCoroutine.cs │ ├── BetterCoroutines.cs │ ├── BetterCoroutinesExtensions.cs │ ├── IPoolableYieldInstruction.cs │ ├── WaitForAsyncOperation.cs │ ├── WaitForSecondsLite.cs │ ├── WaitForSecondsRealtimeLite.cs │ ├── WaitForWWW.cs │ ├── WaitUntilLite.cs │ └── WaitWhileLite.cs ├── Events │ ├── BuiltinEventIds.cs │ ├── Event.cs │ ├── GlobalEvents.cs │ ├── IEventListener.cs │ ├── Loops │ │ ├── CustomUpdateLoopBase.cs │ │ ├── FrameIntervalUpdateLoop.cs │ │ ├── ICustomUpdateLoop.cs │ │ ├── ManagedUpdate.cs │ │ ├── ManagedUpdateBehaviour.cs │ │ └── TimeIntervalUpdateLoop.cs │ └── TellMeWhen.cs ├── Gravity │ ├── GravitationalEntity.cs │ ├── GravitationalEntity2D.cs │ ├── GravitationalSystem.cs │ ├── IGravitationalAffecter.cs │ └── SphericalGravitationalPoint.cs ├── Partitioning │ ├── Bin2D.cs │ ├── Bin3D.cs │ ├── Octree.cs │ └── Quadtree.cs ├── Pooling │ ├── GameObjectPool.cs │ ├── IPool.cs │ ├── IPoolable.cs │ ├── Pool.cs │ ├── PoolHelper.cs │ └── PoolableGroup.cs ├── Properties │ └── AssemblyInfo.cs ├── ResourceSystem │ ├── ResourceEvent.cs │ ├── ResourcePool.cs │ ├── ResourcePoolBase.cs │ ├── ResourceRegen.cs │ └── Shield.cs └── Utils │ ├── BetterTime.cs │ ├── ColorUtils.cs │ ├── Extensions │ └── ListExtensions.cs │ ├── Lazy.cs │ ├── MainThreadDispatcher.cs │ ├── ServiceLocator.cs │ ├── Shake │ ├── BaseShake.cs │ ├── Shake.cs │ └── Shake2D.cs │ ├── UpdateLoop.cs │ └── _Editor │ ├── ExecutionOrderAttribute.cs │ └── ReadOnlyAttribute.cs ├── Archon.SwissArmyLibTests ├── Archon.SwissArmyLibTests.csproj ├── Collections │ ├── DelayedListTests.cs │ ├── Grid2DTests.cs │ ├── Grid3DTests.cs │ └── PrioritizedListTests.cs ├── Events │ └── EventTests.cs ├── Partitioning │ ├── Bin2DTests.cs │ ├── Bin3DTests.cs │ └── QuadtreeTests.cs ├── Properties │ └── AssemblyInfo.cs └── packages.config ├── Documentation ├── .gitignore ├── Content │ └── Welcome.aml ├── ContentLayout.content └── Documentation.shfbproj ├── LICENSE ├── README.rst ├── UnityLibraries ├── README.txt ├── UnityEditor.dll ├── UnityEditor.dll.mdb ├── UnityEditor.xml ├── UnityEngine.dll ├── UnityEngine.dll.mdb └── UnityEngine.xml ├── appveyor.yml └── logo.png /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /Archon.SwissArmyLib.Editor/Archon.SwissArmyLib.Editor.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {86576CEB-98C2-4234-9577-1335777CFB7D} 8 | Library 9 | Properties 10 | Archon.SwissArmyLib.Editor 11 | Archon.SwissArmyLib.Editor 12 | v3.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | ..\bin\Debug\Editor\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | ..\bin\Debug\Editor\Archon.SwissArmyLib.Editor.xml 24 | 25 | 26 | pdbonly 27 | true 28 | ..\bin\Release\Editor\ 29 | TRACE 30 | prompt 31 | 4 32 | ..\bin\Release\Editor\Archon.SwissArmyLib.Editor.xml 33 | 34 | 35 | ..\bin\Test\ 36 | TRACE 37 | ..\bin\Test\Editor\Archon.SwissArmyLib.Editor.xml 38 | true 39 | pdbonly 40 | AnyCPU 41 | prompt 42 | MinimumRecommendedRules.ruleset 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ..\UnityLibraries\UnityEditor.dll 53 | False 54 | 55 | 56 | ..\UnityLibraries\UnityEngine.dll 57 | False 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | {4e6e4ed1-096a-4dd2-b88f-0704bc769f22} 69 | Archon.SwissArmyLib 70 | False 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib.Editor/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Archon.SwissArmyLib.Editor")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Archon Interactive")] 12 | [assembly: AssemblyProduct("Archon.SwissArmyLib.Editor")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("86576ceb-98c2-4234-9577-1335777cfb7d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib.Editor/ResourceSystem/ResourcePoolEditor.cs: -------------------------------------------------------------------------------- 1 | using Archon.SwissArmyLib.ResourceSystem; 2 | using UnityEditor; 3 | using UnityEngine; 4 | 5 | namespace Archon.SwissArmyLib.Editor.ResourceSystem 6 | { 7 | /// 8 | /// Custom editor for components. 9 | /// 10 | /// Shows a health bar and debugging buttons. 11 | /// 12 | [CanEditMultipleObjects] 13 | [CustomEditor(typeof(ResourcePoolBase), true)] 14 | public class ResourcePoolEditor : UnityEditor.Editor 15 | { 16 | private float _addVal = 50; 17 | private float _removeVal = 50; 18 | 19 | /// 20 | public override void OnInspectorGUI() 21 | { 22 | if (targets.Length == 1) 23 | { 24 | var resourcePool = (ResourcePoolBase)target; 25 | EditorGUILayout.Separator(); 26 | var containerRect = EditorGUILayout.BeginHorizontal(); 27 | var barRect = GUILayoutUtility.GetRect(containerRect.width, 20); 28 | EditorGUI.ProgressBar(barRect, resourcePool.Percentage, string.Format("{0:F1} / {1:F1}", resourcePool.Current, resourcePool.Max)); 29 | EditorGUILayout.EndHorizontal(); 30 | EditorGUILayout.Separator(); 31 | } 32 | 33 | DrawDefaultInspector(); 34 | 35 | if (Application.isPlaying) 36 | { 37 | EditorGUILayout.Separator(); 38 | 39 | EditorGUILayout.BeginHorizontal(); 40 | _addVal = EditorGUILayout.FloatField(_addVal); 41 | if (GUILayout.Button("Add")) Add(_addVal); 42 | EditorGUILayout.EndHorizontal(); 43 | 44 | EditorGUILayout.BeginHorizontal(); 45 | _removeVal = EditorGUILayout.FloatField(_removeVal); 46 | if (GUILayout.Button("Remove")) Remove(_removeVal); 47 | EditorGUILayout.EndHorizontal(); 48 | 49 | EditorGUILayout.BeginHorizontal(); 50 | if (GUILayout.Button("Empty")) Empty(); 51 | if (GUILayout.Button("Fill")) Fill(); 52 | if (GUILayout.Button("Renew")) Renew(); 53 | EditorGUILayout.EndHorizontal(); 54 | } 55 | } 56 | 57 | /// 58 | /// Adds a resource amount to all targeted components. 59 | /// 60 | /// Amount to add 61 | protected void Add(float amount) 62 | { 63 | for (var i = 0; i < targets.Length; i++) 64 | ((ResourcePoolBase)targets[i]).Add(amount); 65 | } 66 | 67 | /// 68 | /// Removes a resource amount from all targeted components. 69 | /// 70 | /// Amount to remove 71 | protected void Remove(float amount) 72 | { 73 | for (var i = 0; i < targets.Length; i++) 74 | ((ResourcePoolBase)targets[i]).Remove(amount); 75 | } 76 | 77 | /// 78 | /// Empties all targeted components. 79 | /// 80 | protected void Empty() 81 | { 82 | for (var i = 0; i < targets.Length; i++) 83 | ((ResourcePoolBase)targets[i]).Empty(); 84 | } 85 | 86 | /// 87 | /// Fills all targeted components. 88 | /// 89 | protected void Fill() 90 | { 91 | for (var i = 0; i < targets.Length; i++) 92 | ((ResourcePoolBase) targets[i]).Fill(); 93 | } 94 | 95 | /// 96 | /// Renews all targeted components. 97 | /// 98 | protected void Renew() 99 | { 100 | for (var i = 0; i < targets.Length; i++) 101 | ((ResourcePoolBase)targets[i]).Renew(); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib.Editor/Utils/ExecutionOrderManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Archon.SwissArmyLib.Utils.Editor; 3 | using UnityEditor; 4 | 5 | namespace Archon.SwissArmyLib.Editor.Utils 6 | { 7 | /// 8 | /// Looks for classes using the and sets their execution order. 9 | /// 10 | [InitializeOnLoad] 11 | public class ExecutionOrderManager : UnityEditor.Editor 12 | { 13 | static ExecutionOrderManager() 14 | { 15 | foreach (var script in MonoImporter.GetAllRuntimeMonoScripts()) 16 | { 17 | if (script.GetClass() == null) continue; 18 | 19 | var attributes = Attribute.GetCustomAttributes(script.GetClass(), typeof(ExecutionOrderAttribute)); 20 | 21 | for (var i = 0; i < attributes.Length; i++) 22 | { 23 | var attribute = (ExecutionOrderAttribute) attributes[i]; 24 | 25 | var currentOrder = MonoImporter.GetExecutionOrder(script); 26 | 27 | if (currentOrder == attribute.Order) 28 | continue; 29 | 30 | if (currentOrder == 0 || attribute.Forced) 31 | MonoImporter.SetExecutionOrder(script, attribute.Order); 32 | } 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib.Editor/Utils/ReadOnlyDrawer.cs: -------------------------------------------------------------------------------- 1 | using Archon.SwissArmyLib.Utils.Editor; 2 | using UnityEditor; 3 | using UnityEngine; 4 | 5 | namespace Archon.SwissArmyLib.Editor.Utils 6 | { 7 | /// 8 | /// Makes fields marked with uninteractable via the inspector. 9 | /// 10 | [CustomPropertyDrawer(typeof(ReadOnlyAttribute))] 11 | public class ReadOnlyDrawer : PropertyDrawer 12 | { 13 | /// 14 | public override void OnGUI(Rect position, 15 | SerializedProperty property, 16 | GUIContent label) 17 | { 18 | var readOnly = (ReadOnlyAttribute) attribute; 19 | 20 | if (readOnly.OnlyWhilePlaying && !Application.isPlaying) 21 | EditorGUI.PropertyField(position, property, label, true); 22 | else 23 | { 24 | GUI.enabled = false; 25 | EditorGUI.PropertyField(position, property, label, true); 26 | GUI.enabled = true; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.8 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Archon.SwissArmyLib", "Archon.SwissArmyLib\Archon.SwissArmyLib.csproj", "{4E6E4ED1-096A-4DD2-B88F-0704BC769F22}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Archon.SwissArmyLib.Editor", "Archon.SwissArmyLib.Editor\Archon.SwissArmyLib.Editor.csproj", "{86576CEB-98C2-4234-9577-1335777CFB7D}" 9 | EndProject 10 | Project("{7CF6DF6D-3B04-46F8-A40B-537D21BCA0B4}") = "Documentation", "Documentation\Documentation.shfbproj", "{0C59110B-107A-4B22-9783-8CC0737A033F}" 11 | ProjectSection(ProjectDependencies) = postProject 12 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22} = {4E6E4ED1-096A-4DD2-B88F-0704BC769F22} 13 | {86576CEB-98C2-4234-9577-1335777CFB7D} = {86576CEB-98C2-4234-9577-1335777CFB7D} 14 | EndProjectSection 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Archon.SwissArmyLibTests", "Archon.SwissArmyLibTests\Archon.SwissArmyLibTests.csproj", "{38149324-335B-4316-8016-21AB9F9B3074}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | Test|Any CPU = Test|Any CPU 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22}.Test|Any CPU.ActiveCfg = Test|Any CPU 30 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22}.Test|Any CPU.Build.0 = Test|Any CPU 31 | {86576CEB-98C2-4234-9577-1335777CFB7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {86576CEB-98C2-4234-9577-1335777CFB7D}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {86576CEB-98C2-4234-9577-1335777CFB7D}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {86576CEB-98C2-4234-9577-1335777CFB7D}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {86576CEB-98C2-4234-9577-1335777CFB7D}.Test|Any CPU.ActiveCfg = Test|Any CPU 36 | {86576CEB-98C2-4234-9577-1335777CFB7D}.Test|Any CPU.Build.0 = Test|Any CPU 37 | {0C59110B-107A-4B22-9783-8CC0737A033F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {0C59110B-107A-4B22-9783-8CC0737A033F}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {0C59110B-107A-4B22-9783-8CC0737A033F}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {0C59110B-107A-4B22-9783-8CC0737A033F}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {0C59110B-107A-4B22-9783-8CC0737A033F}.Test|Any CPU.ActiveCfg = Release|Any CPU 42 | {38149324-335B-4316-8016-21AB9F9B3074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {38149324-335B-4316-8016-21AB9F9B3074}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {38149324-335B-4316-8016-21AB9F9B3074}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {38149324-335B-4316-8016-21AB9F9B3074}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {38149324-335B-4316-8016-21AB9F9B3074}.Test|Any CPU.ActiveCfg = Test|Any CPU 47 | {38149324-335B-4316-8016-21AB9F9B3074}.Test|Any CPU.Build.0 = Test|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | GlobalSection(ExtensibilityGlobals) = postSolution 53 | SolutionGuid = {9CE78E2F-6B87-474C-AC71-7FAE13DA0BB7} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Archon.SwissArmyLib.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22} 8 | Library 9 | Properties 10 | Archon.SwissArmyLib 11 | Archon.SwissArmyLib 12 | v3.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | ..\bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | ..\bin\Debug\Archon.SwissArmyLib.xml 24 | 25 | 26 | pdbonly 27 | true 28 | ..\bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | ..\bin\Release\Archon.SwissArmyLib.xml 33 | 34 | 35 | ..\bin\Test\ 36 | TRACE;TEST 37 | ..\bin\Test\Archon.SwissArmyLib.xml 38 | true 39 | pdbonly 40 | AnyCPU 41 | prompt 42 | MinimumRecommendedRules.ruleset 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ..\UnityLibraries\UnityEngine.dll 53 | False 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Archon.SwissArmyLib.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | CSharp40 -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Automata/BaseState.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Automata 2 | { 3 | /// 4 | /// A simple abstract class that implements . 5 | /// 6 | /// You might be looking for or . 7 | /// 8 | /// The type of the machine. 9 | /// The type of the context. 10 | public abstract class BaseState : IState 11 | { 12 | /// 13 | public TMachine Machine { get; set; } 14 | 15 | /// 16 | public TContext Context { get; set; } 17 | 18 | /// 19 | /// Amount of (active) time spent in this state since it was entered. 20 | /// 21 | public float TimeInState { get; private set; } 22 | 23 | /// 24 | /// Called when the state is entered. 25 | /// 26 | public virtual void Begin() 27 | { 28 | TimeInState = 0; 29 | } 30 | 31 | /// 32 | /// Called every frame just before . 33 | /// Use this to check whether you should change state. 34 | /// 35 | public virtual void Reason() { } 36 | 37 | /// 38 | /// Called every frame after , if the state hasn't been changed. 39 | /// 40 | public virtual void Act(float deltaTime) 41 | { 42 | TimeInState += deltaTime; 43 | } 44 | 45 | /// 46 | /// Called when the state is exited. 47 | /// 48 | public virtual void End() { } 49 | } 50 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Automata/FiniteStateMachine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Archon.SwissArmyLib.Automata 5 | { 6 | /// 7 | /// Represents a state to be used in a . 8 | /// 9 | /// The type of the context. 10 | public interface IFsmState : IState, T> { } 11 | 12 | /// 13 | /// A simple abstract class that implements and can be used in a 14 | /// 15 | /// You're not required to use this, but it's easier. 16 | /// 17 | /// The type of the context. 18 | public abstract class FsmState : BaseState, T>, IFsmState { } 19 | 20 | /// 21 | /// A simple Finite State Machine with states as objects inspired by Prime31's excellent StateKit. 22 | /// 23 | /// If your state classes have an empty constructor, the state machine can create the states automatically when needed (using ). 24 | /// If not you should create the state instance yourself and register the state in the machine. 25 | /// 26 | /// Whether or not a null state is valid is up to your design. 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// The type of the context. 32 | public class FiniteStateMachine 33 | { 34 | /// 35 | /// A shared context which all states have access to. 36 | /// 37 | public T Context { get; private set; } 38 | 39 | /// 40 | /// The active state. 41 | /// 42 | public IFsmState CurrentState { get; private set; } 43 | 44 | /// 45 | /// The previously active state. 46 | /// 47 | public IFsmState PreviousState { get; private set; } 48 | 49 | private readonly Dictionary> _states = new Dictionary>(); 50 | 51 | /// 52 | /// Creates a new Finite State Machine. 53 | /// 54 | /// If you need control over how the states are created, you can register them manually using . 55 | /// If not, then you can freely use which will create the states using their default constructor. 56 | /// 57 | /// A shared context for the states. 58 | public FiniteStateMachine(T context) 59 | { 60 | Context = context; 61 | } 62 | 63 | /// 64 | /// Creates a new Finite State Machine and changes the state to . 65 | /// 66 | /// If you need control over how the states are created, you can register them manually using . 67 | /// If not, then you can freely use which will create the states using their default constructor. 68 | /// 69 | /// 70 | /// 71 | public FiniteStateMachine(T context, IFsmState startState) : this(context) 72 | { 73 | RegisterState(startState); 74 | ChangeState(startState); 75 | } 76 | 77 | /// 78 | /// Call this every time the machine should update. Eg. every frame. 79 | /// 80 | public void Update(float deltaTime) 81 | { 82 | var currentState = CurrentState; 83 | 84 | if (currentState != null) 85 | { 86 | currentState.Reason(); 87 | 88 | // we only want to update the state if it's still the current one 89 | if (currentState == CurrentState) 90 | CurrentState.Act(deltaTime); 91 | } 92 | } 93 | 94 | /// 95 | /// Preemptively add a state instance. 96 | /// Useful if the state doesn't have an empty constructor and therefore cannot be used with ChangeStateAuto. 97 | /// 98 | /// The state to register. 99 | public void RegisterState(IFsmState state) 100 | { 101 | _states[state.GetType()] = state; 102 | } 103 | 104 | /// 105 | /// Checks whether a state type is registered. 106 | /// 107 | /// The state type to check. 108 | /// True if registered, false otherwise. 109 | public bool IsStateRegistered(Type stateType) 110 | { 111 | return _states.ContainsKey(stateType); 112 | ; } 113 | 114 | /// 115 | /// Generic version of . 116 | /// Checks whether a state type is registered. 117 | /// 118 | /// The state type to check. 119 | /// Tru if registered, false otherwise. 120 | public bool IsStateRegistered() where TState : IFsmState 121 | { 122 | return _states.ContainsKey(typeof(TState)); 123 | } 124 | 125 | /// 126 | /// Changes the active state to the given state type. 127 | /// If a state of that type isn't already registered, it will automatically create a new instance using the empty constructor. 128 | /// 129 | /// 130 | /// 131 | public TState ChangeStateAuto() where TState : IFsmState, new() 132 | { 133 | var type = typeof(TState); 134 | IFsmState state; 135 | 136 | if (!_states.TryGetValue(type, out state)) 137 | _states[type] = state = new TState(); 138 | 139 | return ChangeState((TState) state); 140 | } 141 | 142 | /// 143 | /// Changes the active state to the given state type. 144 | /// An instance of that type should already had been registered to use this method. 145 | /// 146 | /// 147 | /// 148 | public TState ChangeState() where TState : IFsmState 149 | { 150 | var type = typeof(TState); 151 | IFsmState state; 152 | 153 | if (!_states.TryGetValue(type, out state)) 154 | throw new InvalidOperationException(string.Format("A state of type '{0}' is not registered, did you mean to use ChangeStateAuto?", type)); 155 | 156 | return ChangeState((TState)state); 157 | } 158 | 159 | /// 160 | /// Changes the active state to a specific state instance. 161 | /// This will (if not null) also register the state. 162 | /// 163 | /// 164 | /// 165 | /// 166 | public TState ChangeState(TState state) where TState : IFsmState 167 | { 168 | if (CurrentState != null) 169 | CurrentState.End(); 170 | 171 | PreviousState = CurrentState; 172 | CurrentState = state; 173 | 174 | if (CurrentState != null) 175 | { 176 | RegisterState(state); 177 | CurrentState.Machine = this; 178 | CurrentState.Context = Context; 179 | CurrentState.Begin(); 180 | } 181 | 182 | return state; 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Automata/IPdaState.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Automata 2 | { 3 | /// 4 | /// Represents a state to be used in a . 5 | /// 6 | /// The type of the context. 7 | public interface IPdaState : IState, T> 8 | { 9 | /// 10 | /// Called when a state is pushed ontop of this state. 11 | /// 12 | void Pause(); 13 | 14 | /// 15 | /// Called when the state above us is popped. 16 | /// 17 | void Resume(); 18 | } 19 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Automata/IState.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Automata 2 | { 3 | /// 4 | /// Represents a state to be used in a state machine. 5 | /// 6 | /// You might be looking for or . 7 | /// 8 | /// The type of the machine. 9 | /// The type of the context. 10 | public interface IState 11 | { 12 | /// 13 | /// The state machine this state belongs to. 14 | /// 15 | TMachine Machine { get; set; } 16 | 17 | /// 18 | /// The context for this state. 19 | /// 20 | TContext Context { get; set; } 21 | 22 | /// 23 | /// Called when the state is entered. 24 | /// 25 | void Begin(); 26 | 27 | /// 28 | /// Called every frame just before . 29 | /// Use this to check whether you should change state. 30 | /// 31 | void Reason(); 32 | 33 | /// 34 | /// Called every frame after , if the state hasn't been changed. 35 | /// 36 | void Act(float deltaTime); 37 | 38 | /// 39 | /// Called when the state is exited. 40 | /// 41 | void End(); 42 | } 43 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Automata/PdaState.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Automata 2 | { 3 | /// 4 | /// A simple abstract class that implements and can be used in a 5 | /// 6 | /// You're not required to use this, but it's easier. 7 | /// 8 | /// The type of the context. 9 | public class PdaState : BaseState, T>, IPdaState 10 | { 11 | /// 12 | /// Called when a state is pushed ontop of this state. 13 | /// 14 | public virtual void Pause() { } 15 | 16 | /// 17 | /// Called when the state above us is popped. 18 | /// 19 | public virtual void Resume() { } 20 | } 21 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Collections/DictionaryWithDefault.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Archon.SwissArmyLib.Collections 4 | { 5 | /// 6 | /// A but with a default value for missing entries. 7 | /// 8 | /// 9 | /// 10 | public class DictionaryWithDefault : Dictionary 11 | { 12 | /// 13 | /// Default value for missing entries. 14 | /// 15 | public TValue DefaultValue { get; set; } 16 | 17 | /// 18 | /// Gets or sets the value associated with the given key. 19 | /// 20 | /// If the key isn't in the dictionary, will be returned. 21 | /// 22 | /// 23 | public new TValue this[TKey key] 24 | { 25 | get 26 | { 27 | TValue t; 28 | return TryGetValue(key, out t) ? t : DefaultValue; 29 | } 30 | set 31 | { 32 | base[key] = value; 33 | } 34 | } 35 | 36 | /// 37 | /// Creates a new Dictionary with DefaultValue set to TValue's default value. 38 | /// 39 | public DictionaryWithDefault() 40 | { 41 | } 42 | 43 | /// 44 | /// Creates a new Dictionary using the supplied value as the default for missing entries. 45 | /// 46 | /// 47 | public DictionaryWithDefault(TValue defaultValue) 48 | { 49 | DefaultValue = defaultValue; 50 | } 51 | 52 | /// 53 | /// Creates a new Dictionary using the supplied value as the default for missing entries and a specific comparer. 54 | /// 55 | /// 56 | /// 57 | public DictionaryWithDefault(TValue defaultValue, IEqualityComparer comparer) : base(comparer) 58 | { 59 | DefaultValue = defaultValue; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Collections/Grid2D.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Archon.SwissArmyLib.Collections 4 | { 5 | /// 6 | /// A generic two-dimensional grid. 7 | /// 8 | /// 9 | /// 10 | /// The type of content cells can contain. 11 | public class Grid2D 12 | { 13 | private T[][] _data; 14 | 15 | /// 16 | /// Gets the width (number of columns) of the grid. 17 | /// 18 | public int Width { get; private set; } 19 | 20 | /// 21 | /// Gets the height (number of rows) of the grid. 22 | /// 23 | public int Height { get; private set; } 24 | 25 | /// 26 | /// Gets or sets the default values used for clearing or initializing new cells. 27 | /// 28 | public T DefaultValue { get; set; } 29 | 30 | /// 31 | /// Gets or sets the value of the cell located at the specified coordinate. 32 | /// 33 | /// 34 | /// 35 | /// The contents of the cell. 36 | public T this[int x, int y] 37 | { 38 | get 39 | { 40 | if (x < 0 || y < 0 || x >= Width || y >= Height) 41 | throw new IndexOutOfRangeException(); 42 | 43 | return _data[x][y]; 44 | } 45 | set 46 | { 47 | if (x < 0 || y < 0 || x >= Width || y >= Height) 48 | throw new IndexOutOfRangeException(); 49 | 50 | _data[x][y] = value; 51 | } 52 | } 53 | 54 | private int InternalWidth { get { return _data.Length; } } 55 | private int InternalHeight { get { return _data[0].Length; } } 56 | 57 | /// 58 | /// Creates a new 2D Grid with the specified width and height. 59 | /// Cells will be initialized with their type's default value. 60 | /// 61 | /// Number of columns 62 | /// Number of rows 63 | public Grid2D(int width, int height) 64 | { 65 | Width = width; 66 | Height = height; 67 | 68 | _data = CreateArrays(width, height); 69 | } 70 | 71 | /// 72 | /// Creates a new 2D Grid with the specified width and height. 73 | /// Cells will be initialized with the value of . 74 | /// 75 | /// Number of columns 76 | /// Number of rows 77 | /// The value used for initializing new cells. 78 | public Grid2D(int width, int height, T defaultValue) : this(width, height) 79 | { 80 | DefaultValue = defaultValue; 81 | Clear(); 82 | } 83 | 84 | /// 85 | /// Gets the value of the cell located at the specified coordinate. 86 | /// 87 | /// 88 | /// 89 | /// 90 | /// 91 | /// The cell contents. 92 | public T Get(int x, int y) 93 | { 94 | return this[x, y]; 95 | } 96 | 97 | /// 98 | /// Sets the value of the cell located at the specified coordinate. 99 | /// 100 | /// 101 | /// 102 | /// 103 | /// 104 | /// The value to set the cell to. 105 | public void Set(int x, int y, T value) 106 | { 107 | this[x, y] = value; 108 | } 109 | 110 | /// 111 | /// Clears the grid, setting every cell to . 112 | /// 113 | public void Clear() 114 | { 115 | Clear(DefaultValue); 116 | } 117 | 118 | /// 119 | /// Clears the grid, setting every cell to the given value. 120 | /// 121 | public void Clear(T clearValue) 122 | { 123 | Fill(clearValue, 0, 0, Width - 1, Height - 1); 124 | } 125 | 126 | /// 127 | /// Fills everything in the specified rectangle to the given value. 128 | /// 129 | /// The value to fill the cells with. 130 | /// Bottom left corner's x value. 131 | /// Bottom left corner's y value. 132 | /// Upper right corner's x value. 133 | /// Upper right corner's y value. 134 | public void Fill(T value, int minX, int minY, int maxX, int maxY) 135 | { 136 | for (var x = minX; x <= maxX; x++) 137 | { 138 | var heightArray = _data[x]; 139 | 140 | for (var y = minY; y <= maxY; y++) 141 | heightArray[y] = value; 142 | } 143 | } 144 | 145 | /// 146 | /// Resizes the Grid to the given size, keeping data the same but any new cells will be set to . 147 | /// 148 | /// Growing the grid will allocate new arrays, shrinking will not. 149 | /// 150 | /// The new width. 151 | /// The new height. 152 | public void Resize(int width, int height) 153 | { 154 | var oldWidth = Width; 155 | var oldHeight = Height; 156 | 157 | if (width > InternalWidth || height > InternalHeight) 158 | { 159 | var oldData = _data; 160 | _data = CreateArrays(width, height); 161 | CopyArraysContents(oldData, _data); 162 | } 163 | 164 | Width = width; 165 | Height = height; 166 | 167 | if (width > oldWidth || height > oldHeight) 168 | { 169 | Fill(DefaultValue, 0, oldHeight, width - 1, height - 1); 170 | Fill(DefaultValue, oldWidth, 0, width - 1, oldHeight - 1); 171 | } 172 | } 173 | 174 | private static T[][] CreateArrays(int width, int height) 175 | { 176 | var arrays = new T[width][]; 177 | 178 | for (var x = 0; x < width; x++) 179 | arrays[x] = new T[height]; 180 | 181 | return arrays; 182 | } 183 | 184 | private static void CopyArraysContents(T[][] src, T[][] dst) 185 | { 186 | var srcWidth = src.Length; 187 | var srcHeight = src[0].Length; 188 | 189 | var dstWidth = dst.Length; 190 | var dstHeight = dst[0].Length; 191 | 192 | for (var x = 0; x < srcWidth && x < dstWidth; x++) 193 | { 194 | var srcHeightArray = src[x]; 195 | var dstHeightArray = dst[x]; 196 | 197 | for (var y = 0; y < srcHeight && y < dstHeight; y++) 198 | dstHeightArray[y] = srcHeightArray[y]; 199 | } 200 | } 201 | } 202 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/BetterCoroutine.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using Archon.SwissArmyLib.Events.Loops; 3 | using Archon.SwissArmyLib.Pooling; 4 | using UnityEngine; 5 | 6 | namespace Archon.SwissArmyLib.Coroutines 7 | { 8 | internal sealed class BetterCoroutine : IPoolable 9 | { 10 | internal int Id; 11 | internal bool IsDone; 12 | internal bool IsPaused; 13 | internal bool IsParentPaused; 14 | internal int UpdateLoopId; 15 | internal IEnumerator Enumerator; 16 | internal BetterCoroutine Parent; 17 | internal BetterCoroutine Child; 18 | 19 | internal float WaitTillTime = float.MinValue; 20 | internal bool WaitTimeIsUnscaled; 21 | internal bool WaitingForEndOfFrame; 22 | 23 | internal bool IsLinkedToObject; 24 | internal GameObject LinkedObject; 25 | internal bool IsLinkedToComponent; 26 | internal MonoBehaviour LinkedComponent; 27 | 28 | void IPoolable.OnSpawned() 29 | { 30 | 31 | } 32 | 33 | void IPoolable.OnDespawned() 34 | { 35 | var poolableYieldInstruction = Enumerator as IPoolableYieldInstruction; 36 | if (poolableYieldInstruction != null) 37 | poolableYieldInstruction.Despawn(); 38 | 39 | Id = -1; 40 | IsDone = false; 41 | IsPaused = false; 42 | IsParentPaused = false; 43 | UpdateLoopId = ManagedUpdate.EventIds.Update; 44 | Enumerator = null; 45 | Parent = null; 46 | Child = null; 47 | 48 | WaitTillTime = float.MinValue; 49 | WaitTimeIsUnscaled = false; 50 | WaitingForEndOfFrame = false; 51 | 52 | LinkedObject = null; 53 | LinkedComponent = null; 54 | IsLinkedToObject = false; 55 | IsLinkedToComponent = false; 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/BetterCoroutinesExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using Archon.SwissArmyLib.Events.Loops; 3 | using Archon.SwissArmyLib.Utils; 4 | using UnityEngine; 5 | 6 | namespace Archon.SwissArmyLib.Coroutines 7 | { 8 | /// 9 | /// A bunch of helpful extensions for starting and stopping coroutines. 10 | /// 11 | public static class BetterCoroutinesExtensions 12 | { 13 | /// 14 | /// Starts a new coroutine. 15 | /// 16 | /// 17 | /// 18 | /// Which update loop should the coroutine be part of? 19 | /// The id of the coroutine. 20 | public static int StartBetterCoroutine(this Object unityObject, IEnumerator enumerator, 21 | UpdateLoop updateLoop = UpdateLoop.Update) 22 | { 23 | return BetterCoroutines.Start(enumerator, updateLoop); 24 | } 25 | 26 | /// 27 | /// Starts a new coroutine. 28 | /// 29 | /// 30 | /// 31 | /// Which update loop should the coroutine be part of? 32 | /// The id of the coroutine. 33 | public static int StartBetterCoroutine(this Object unityObject, IEnumerator enumerator, 34 | int updateLoopId) 35 | { 36 | return BetterCoroutines.Start(enumerator, updateLoopId); 37 | } 38 | 39 | /// 40 | /// Starts a new coroutine with its lifetime linked to this component. 41 | /// The coroutine will be stopped when the linked component is disabled or destroyed. 42 | /// 43 | /// The component to link the coroutine to. 44 | /// 45 | /// Which update loop should the coroutine be part of? 46 | /// The id of the coroutine. 47 | public static int StartBetterCoroutineLinked(this MonoBehaviour monoBehaviour, IEnumerator enumerator, 48 | UpdateLoop updateLoop = UpdateLoop.Update) 49 | { 50 | return BetterCoroutines.Start(enumerator, monoBehaviour, updateLoop); 51 | } 52 | 53 | /// 54 | /// Starts a new coroutine with its lifetime linked to this component. 55 | /// The coroutine will be stopped when the linked component is disabled or destroyed. 56 | /// 57 | /// The component to link the coroutine to. 58 | /// 59 | /// Which update loop should the coroutine be part of? 60 | /// The id of the coroutine. 61 | public static int StartBetterCoroutineLinked(this MonoBehaviour monoBehaviour, IEnumerator enumerator, 62 | int updateLoopId) 63 | { 64 | return BetterCoroutines.Start(enumerator, monoBehaviour, updateLoopId); 65 | } 66 | 67 | /// 68 | /// Starts a new coroutine with its lifetime linked to this gameobject. 69 | /// The coroutine will be stopped when the linked gameobject is disabled or destroyed. 70 | /// 71 | /// The gameobject to link the coroutine to. 72 | /// 73 | /// Which update loop should the coroutine be part of? 74 | /// The id of the coroutine. 75 | public static int StartBetterCoroutineLinked(this GameObject gameObject, IEnumerator enumerator, 76 | UpdateLoop updateLoop = UpdateLoop.Update) 77 | { 78 | return BetterCoroutines.Start(enumerator, gameObject, updateLoop); 79 | } 80 | 81 | /// 82 | /// Starts a new coroutine with its lifetime linked to this gameobject. 83 | /// The coroutine will be stopped when the linked gameobject is disabled or destroyed. 84 | /// 85 | /// The gameobject to link the coroutine to. 86 | /// 87 | /// Which update loop should the coroutine be part of? 88 | /// The id of the coroutine. 89 | public static int StartBetterCoroutineLinked(this GameObject gameObject, IEnumerator enumerator, 90 | int updateLoopId) 91 | { 92 | return BetterCoroutines.Start(enumerator, gameObject, updateLoopId); 93 | } 94 | 95 | /// 96 | /// Stops a running coroutine prematurely. 97 | /// 98 | /// This will stop any child coroutines as well. 99 | /// 100 | /// 101 | /// The id of the coroutine to stop. 102 | /// True if the coroutine was found and stopped, otherwise false. 103 | public static bool StopBetterCoroutine(this Object unityObject, int coroutineId) 104 | { 105 | return BetterCoroutines.Stop(coroutineId); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/IPoolableYieldInstruction.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Coroutines 2 | { 3 | /// 4 | /// Represents a yield instruction that can be freed when the coroutine they're running in is despawned. 5 | /// 6 | public interface IPoolableYieldInstruction 7 | { 8 | /// 9 | /// Frees the yield instruction placing them back in its pool. 10 | /// 11 | void Despawn(); 12 | } 13 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/WaitForAsyncOperation.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using Archon.SwissArmyLib.Pooling; 3 | using UnityEngine; 4 | 5 | namespace Archon.SwissArmyLib.Coroutines 6 | { 7 | internal sealed class WaitForAsyncOperation : CustomYieldInstruction, IPoolableYieldInstruction 8 | { 9 | private static readonly Pool Pool = new Pool(() => new WaitForAsyncOperation()); 10 | 11 | public static IEnumerator Create(AsyncOperation operation) 12 | { 13 | var waiter = Pool.Spawn(); 14 | waiter._operation = operation; 15 | return waiter; 16 | } 17 | 18 | private AsyncOperation _operation; 19 | 20 | private WaitForAsyncOperation() 21 | { 22 | 23 | } 24 | 25 | /// 26 | public override bool keepWaiting 27 | { 28 | get { return !_operation.isDone; } 29 | } 30 | 31 | public void Despawn() 32 | { 33 | _operation = null; 34 | Pool.Despawn(this); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/WaitForSecondsLite.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Coroutines 2 | { 3 | internal sealed class WaitForSecondsLite 4 | { 5 | internal static readonly WaitForSecondsLite Instance = new WaitForSecondsLite(); 6 | 7 | public float Duration; 8 | public bool Unscaled; 9 | 10 | private WaitForSecondsLite() { } 11 | } 12 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/WaitForSecondsRealtimeLite.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using Archon.SwissArmyLib.Pooling; 3 | using UnityEngine; 4 | 5 | namespace Archon.SwissArmyLib.Coroutines 6 | { 7 | internal sealed class WaitForSecondsRealtimeLite : CustomYieldInstruction, IPoolableYieldInstruction 8 | { 9 | private static readonly Pool Pool = new Pool(() => new WaitForSecondsRealtimeLite()); 10 | 11 | public static IEnumerator Create(float seconds) 12 | { 13 | var waiter = Pool.Spawn(); 14 | waiter._expirationTime = Time.realtimeSinceStartup + seconds; 15 | return waiter; 16 | } 17 | 18 | private float _expirationTime; 19 | 20 | private WaitForSecondsRealtimeLite() 21 | { 22 | } 23 | 24 | /// 25 | public override bool keepWaiting 26 | { 27 | get { return Time.realtimeSinceStartup < _expirationTime; } 28 | } 29 | 30 | public void Despawn() 31 | { 32 | _expirationTime = 0; 33 | Pool.Despawn(this); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/WaitForWWW.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using Archon.SwissArmyLib.Pooling; 3 | using UnityEngine; 4 | 5 | namespace Archon.SwissArmyLib.Coroutines 6 | { 7 | internal sealed class WaitForWWW : CustomYieldInstruction, IPoolableYieldInstruction 8 | { 9 | private static readonly Pool Pool = new Pool(() => new WaitForWWW()); 10 | 11 | public static IEnumerator Create(WWW wwwObject) 12 | { 13 | var waiter = Pool.Spawn(); 14 | waiter._wwwObject = wwwObject; 15 | return waiter; 16 | } 17 | 18 | private WWW _wwwObject; 19 | 20 | private WaitForWWW() 21 | { 22 | 23 | } 24 | 25 | /// 26 | public override bool keepWaiting 27 | { 28 | get { return !_wwwObject.isDone; } 29 | } 30 | 31 | public void Despawn() 32 | { 33 | _wwwObject = null; 34 | Pool.Despawn(this); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/WaitUntilLite.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using Archon.SwissArmyLib.Pooling; 4 | using UnityEngine; 5 | 6 | namespace Archon.SwissArmyLib.Coroutines 7 | { 8 | internal sealed class WaitUntilLite : CustomYieldInstruction, IPoolableYieldInstruction 9 | { 10 | private static readonly Pool Pool = new Pool(() => new WaitUntilLite()); 11 | 12 | public static IEnumerator Create(Func predicate) 13 | { 14 | var waiter = Pool.Spawn(); 15 | waiter._predicate = predicate; 16 | return waiter; 17 | } 18 | 19 | private Func _predicate; 20 | 21 | private WaitUntilLite() 22 | { 23 | 24 | } 25 | 26 | /// 27 | public override bool keepWaiting 28 | { 29 | get { return !_predicate(); } 30 | } 31 | 32 | public void Despawn() 33 | { 34 | _predicate = null; 35 | Pool.Despawn(this); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Coroutines/WaitWhileLite.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using Archon.SwissArmyLib.Pooling; 4 | using UnityEngine; 5 | 6 | namespace Archon.SwissArmyLib.Coroutines 7 | { 8 | internal sealed class WaitWhileLite : CustomYieldInstruction, IPoolableYieldInstruction 9 | { 10 | private static readonly Pool Pool = new Pool(() => new WaitWhileLite()); 11 | 12 | public static IEnumerator Create(Func predicate) 13 | { 14 | var waiter = Pool.Spawn(); 15 | waiter._predicate = predicate; 16 | return waiter; 17 | } 18 | 19 | private Func _predicate; 20 | 21 | private WaitWhileLite() 22 | { 23 | 24 | } 25 | 26 | /// 27 | public override bool keepWaiting 28 | { 29 | get { return _predicate(); } 30 | } 31 | 32 | public void Despawn() 33 | { 34 | _predicate = null; 35 | Pool.Despawn(this); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/BuiltinEventIds.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Events 2 | { 3 | /// 4 | /// Contains the event ids used by SwissArmyLib. 5 | /// 6 | public static class BuiltinEventIds 7 | { 8 | /// 9 | /// ManagedUpdate 10 | /// 11 | public const int 12 | Update = -1000, 13 | LateUpdate = -1001, 14 | FixedUpdate = -1002; 15 | 16 | /// 17 | /// ResourcePool 18 | /// 19 | public const int 20 | PreChange = -8000, 21 | Change = -8001, 22 | Empty = -8002, 23 | Full = -8003, 24 | Renew = -8004; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/IEventListener.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Events 2 | { 3 | /// 4 | /// Defines a method to be used for event callbacks. 5 | /// 6 | public interface IEventListener 7 | { 8 | /// 9 | /// Called when an event is invoked. 10 | /// 11 | /// The id of the event. 12 | void OnEvent(int eventId); 13 | } 14 | 15 | /// 16 | /// Defines a method to be used for event callbacks with a parameter of type . 17 | /// 18 | /// 19 | public interface IEventListener 20 | { 21 | /// 22 | /// Called when an event is invoked. 23 | /// 24 | /// The id of the event. 25 | /// The args for the event. 26 | void OnEvent(int eventId, TArgs args); 27 | } 28 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/Loops/CustomUpdateLoopBase.cs: -------------------------------------------------------------------------------- 1 | using Archon.SwissArmyLib.Utils; 2 | 3 | namespace Archon.SwissArmyLib.Events.Loops 4 | { 5 | /// 6 | /// An abstract class for custom update loops that implement basic 7 | /// functionality to track invokation times and deltatimes. 8 | /// 9 | public abstract class CustomUpdateLoopBase : ICustomUpdateLoop 10 | { 11 | /// 12 | /// Gets or sets in scaled time when this update loop last ran. 13 | /// 14 | protected float PreviousRunTimeScaled; 15 | 16 | /// 17 | /// Gets or sets in unscaled time when this update loop last ran. 18 | /// 19 | protected float PreviousRunTimeUnscaled; 20 | 21 | /// 22 | public Event Event { get; protected set; } 23 | 24 | /// 25 | public abstract bool IsTimeToRun { get; } 26 | 27 | /// 28 | public float DeltaTime 29 | { 30 | get { return BetterTime.Time - PreviousRunTimeScaled; } 31 | } 32 | 33 | /// 34 | public float UnscaledDeltaTime 35 | { 36 | get { return BetterTime.UnscaledTime - PreviousRunTimeUnscaled; } 37 | } 38 | 39 | /// 40 | public virtual void Invoke() 41 | { 42 | Event.Invoke(); 43 | 44 | PreviousRunTimeScaled = BetterTime.Time; 45 | PreviousRunTimeUnscaled = BetterTime.UnscaledTime; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/Loops/FrameIntervalUpdateLoop.cs: -------------------------------------------------------------------------------- 1 | using Archon.SwissArmyLib.Utils; 2 | 3 | namespace Archon.SwissArmyLib.Events.Loops 4 | { 5 | /// 6 | /// A basic custom update loop that runs every nth frame. 7 | /// 8 | /// 9 | /// 10 | public class FrameIntervalUpdateLoop : CustomUpdateLoopBase 11 | { 12 | private int _previousUpdateFrame; 13 | private int _nextUpdateFrame; 14 | private int _interval; 15 | 16 | /// 17 | public override bool IsTimeToRun 18 | { 19 | get 20 | { 21 | return BetterTime.FrameCount >= _nextUpdateFrame; 22 | } 23 | } 24 | 25 | /// 26 | /// Gets or sets the frame interval that this update loop should run. 27 | /// 28 | public int Interval 29 | { 30 | get { return _interval; } 31 | set 32 | { 33 | _interval = value; 34 | _nextUpdateFrame = _previousUpdateFrame + value; 35 | } 36 | } 37 | 38 | /// 39 | /// Creates a new FrameIntervalUpdateLoop. 40 | /// 41 | /// The event id that this update loop should use. 42 | /// The amount of frames between each call of this update loop. 43 | public FrameIntervalUpdateLoop(int eventId, int interval) 44 | { 45 | Event = new Event(eventId); 46 | Interval = interval; 47 | } 48 | 49 | /// 50 | public override void Invoke() 51 | { 52 | base.Invoke(); 53 | 54 | _previousUpdateFrame = BetterTime.FrameCount; 55 | _nextUpdateFrame = _previousUpdateFrame + Interval; 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/Loops/ICustomUpdateLoop.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Events.Loops 2 | { 3 | /// 4 | /// Represents an implementation of a custom update loop. 5 | /// 6 | /// You will probably be better of subclassing for 7 | /// a simpler start, but it's here if you need it. 8 | /// 9 | public interface ICustomUpdateLoop 10 | { 11 | /// 12 | /// Gets the event associated with this update loop. 13 | /// 14 | Event Event { get; } 15 | 16 | /// 17 | /// Gets whether it's time for this update loop to run again. 18 | /// 19 | bool IsTimeToRun { get; } 20 | 21 | /// 22 | /// Gets the scaled time since this update loop last ran. 23 | /// 24 | float DeltaTime { get; } 25 | 26 | /// 27 | /// Gets the unscaled time since this update loop last ran. 28 | /// 29 | float UnscaledDeltaTime { get; } 30 | 31 | /// 32 | /// Runs this update loop's event. 33 | /// 34 | void Invoke(); 35 | } 36 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/Loops/ManagedUpdateBehaviour.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.Events.Loops 4 | { 5 | /// 6 | /// Makes a subclass get notified on an update. 7 | /// 8 | public interface IUpdateable 9 | { 10 | /// 11 | /// Called every frame. 12 | /// 13 | void OnUpdate(); 14 | } 15 | 16 | /// 17 | /// Makes a subclass get notified on a late update. 18 | /// 19 | public interface ILateUpdateable 20 | { 21 | /// 22 | /// Called every frame, after the regular update loop. 23 | /// 24 | void OnLateUpdate(); 25 | } 26 | 27 | /// 28 | /// Makes a subclass get notified on a fixed update. 29 | /// 30 | public interface IFixedUpdateable 31 | { 32 | /// 33 | /// Called every fixed update. 34 | /// 35 | void OnFixedUpdate(); 36 | } 37 | 38 | /// 39 | /// Makes a subclass get notified when a custom update loop ticks. 40 | /// 41 | public interface ICustomUpdateable 42 | { 43 | /// 44 | /// Gets the event ids for the custom update loops that should be listened to. 45 | /// 46 | /// The event ids to listen for. 47 | int[] GetCustomUpdateIds(); 48 | 49 | /// 50 | /// Called whenever one of the custom update loops tick. 51 | /// 52 | /// 53 | void OnCustomUpdate(int eventId); 54 | } 55 | 56 | /// 57 | /// A subclass of MonoBehaviour that uses for update events. 58 | /// 59 | /// To receive updates implement one or more of the appropriate interfaces: 60 | /// , , and . 61 | /// 62 | public abstract class ManagedUpdateBehaviour : MonoBehaviour, IEventListener 63 | { 64 | /// 65 | /// Affects whether this components' events will be called before or after others'. 66 | /// 67 | /// Basically a reimplementation of Unity's ScriptExecutionOrder. 68 | /// 69 | protected virtual int ExecutionOrder { get { return 0; } } 70 | 71 | private bool _startWasCalled; 72 | private bool _isListening; 73 | private IUpdateable _updateable; 74 | private ILateUpdateable _lateUpdateable; 75 | private IFixedUpdateable _fixedUpdateable; 76 | private ICustomUpdateable _customUpdateable; 77 | 78 | private int[] _customUpdateIds; 79 | 80 | /// 81 | /// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. 82 | /// 83 | protected virtual void Start() 84 | { 85 | // ReSharper disable SuspiciousTypeConversion.Global 86 | _updateable = this as IUpdateable; 87 | _lateUpdateable = this as ILateUpdateable; 88 | _fixedUpdateable = this as IFixedUpdateable; 89 | _customUpdateable = this as ICustomUpdateable; 90 | // ReSharper restore SuspiciousTypeConversion.Global 91 | 92 | if (_updateable == null 93 | && _lateUpdateable == null 94 | && _fixedUpdateable == null 95 | && _customUpdateable == null) 96 | { 97 | Debug.LogWarning("This component doesn't implement any update interfaces.", this); 98 | } 99 | 100 | _startWasCalled = true; 101 | StartListening(); 102 | } 103 | 104 | /// 105 | /// Called when the component is enabled. 106 | /// 107 | protected virtual void OnEnable() 108 | { 109 | // interface references aren't serialized when unity hot-reloads 110 | if (Application.isEditor) 111 | { 112 | // ReSharper disable SuspiciousTypeConversion.Global 113 | if (_updateable == null) _updateable = this as IUpdateable; 114 | if (_lateUpdateable == null) _lateUpdateable = this as ILateUpdateable; 115 | if (_fixedUpdateable == null) _fixedUpdateable = this as IFixedUpdateable; 116 | if (_customUpdateable == null) _customUpdateable = this as ICustomUpdateable; 117 | // ReSharper restore SuspiciousTypeConversion.Global 118 | } 119 | 120 | // We don't want Update calls before Start has been called. 121 | if (_startWasCalled) 122 | StartListening(); 123 | } 124 | 125 | /// 126 | /// Called when the component is disabled. 127 | /// 128 | protected virtual void OnDisable() 129 | { 130 | if (_startWasCalled) 131 | StopListening(); 132 | } 133 | 134 | private void StartListening() 135 | { 136 | if (_isListening) 137 | { 138 | Debug.LogError("Attempt at starting to listen for updates, while already listening. Did you forget to call base.OnDisable()?"); 139 | return; 140 | } 141 | 142 | var executionOrder = ExecutionOrder; 143 | 144 | if (_updateable != null) 145 | ManagedUpdate.OnUpdate.AddListener(this, executionOrder); 146 | if (_lateUpdateable != null) 147 | ManagedUpdate.OnLateUpdate.AddListener(this, executionOrder); 148 | if (_fixedUpdateable != null) 149 | ManagedUpdate.OnFixedUpdate.AddListener(this, executionOrder); 150 | 151 | if (_customUpdateable != null) 152 | { 153 | if (_customUpdateIds == null) 154 | _customUpdateIds = _customUpdateable.GetCustomUpdateIds() ?? new int[0]; 155 | 156 | for (var i = 0; i < _customUpdateIds.Length; i++) 157 | ManagedUpdate.AddListener(_customUpdateIds[i], this, executionOrder); 158 | } 159 | 160 | _isListening = true; 161 | } 162 | 163 | private void StopListening() 164 | { 165 | if (!_isListening) 166 | { 167 | Debug.LogError("Attempted to stop listening for updates while not listening. Did you forget to call base.Start() or base.OnEnable()?"); 168 | return; 169 | } 170 | 171 | if (_updateable != null) 172 | ManagedUpdate.OnUpdate.RemoveListener(this); 173 | if (_lateUpdateable != null) 174 | ManagedUpdate.OnLateUpdate.RemoveListener(this); 175 | if (_fixedUpdateable != null) 176 | ManagedUpdate.OnFixedUpdate.RemoveListener(this); 177 | 178 | if (_customUpdateable != null && _customUpdateIds != null) 179 | { 180 | for (var i = 0; i < _customUpdateIds.Length; i++) 181 | ManagedUpdate.RemoveListener(_customUpdateIds[i], this); 182 | } 183 | 184 | _isListening = false; 185 | } 186 | 187 | /// 188 | public virtual void OnEvent(int eventId) 189 | { 190 | switch (eventId) 191 | { 192 | case ManagedUpdate.EventIds.Update: 193 | _updateable.OnUpdate(); 194 | return; 195 | case ManagedUpdate.EventIds.LateUpdate: 196 | _lateUpdateable.OnLateUpdate(); 197 | return; 198 | case ManagedUpdate.EventIds.FixedUpdate: 199 | _fixedUpdateable.OnFixedUpdate(); 200 | return; 201 | } 202 | 203 | if (_customUpdateIds != null) 204 | { 205 | for (var i = 0; i < _customUpdateIds.Length; i++) 206 | { 207 | if (_customUpdateIds[i] != eventId) continue; 208 | 209 | _customUpdateable.OnCustomUpdate(eventId); 210 | return; 211 | } 212 | } 213 | } 214 | } 215 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Events/Loops/TimeIntervalUpdateLoop.cs: -------------------------------------------------------------------------------- 1 | using Archon.SwissArmyLib.Utils; 2 | 3 | namespace Archon.SwissArmyLib.Events.Loops 4 | { 5 | /// 6 | /// A basic custom update loop that runs every nth second either in scaled or unscaled time. 7 | /// 8 | /// 9 | /// 10 | public class TimeIntervalUpdateLoop : CustomUpdateLoopBase 11 | { 12 | private float _nextUpdateTime; 13 | private float _interval; 14 | 15 | /// 16 | public override bool IsTimeToRun 17 | { 18 | get 19 | { 20 | var time = UsingScaledTime ? BetterTime.Time : BetterTime.UnscaledTime; 21 | return time >= _nextUpdateTime; 22 | } 23 | } 24 | 25 | /// 26 | /// Gets or sets the amount of seconds between each time this update loop runs. 27 | /// 28 | public float Interval 29 | { 30 | get { return _interval; } 31 | set 32 | { 33 | _interval = value; 34 | var previousTime = UsingScaledTime ? PreviousRunTimeScaled : PreviousRunTimeUnscaled; 35 | _nextUpdateTime = previousTime + value; 36 | } 37 | } 38 | 39 | /// 40 | /// Gets whether this interval update loop uses scaled or unscaled time for its interval. 41 | /// 42 | public bool UsingScaledTime { get; private set; } 43 | 44 | /// 45 | /// Creates a new TimeIntervalUpdateLoop. 46 | /// 47 | /// The event id that the update loop should use. 48 | /// The amount of seconds between each time this update loop should run. 49 | /// Whether the interval should use scaled or unscaled time. 50 | public TimeIntervalUpdateLoop(int eventId, float interval, bool usingScaledTime = true) 51 | { 52 | Event = new Event(eventId); 53 | Interval = interval; 54 | UsingScaledTime = usingScaledTime; 55 | } 56 | 57 | /// 58 | public override void Invoke() 59 | { 60 | base.Invoke(); 61 | 62 | var time = UsingScaledTime ? BetterTime.Time : BetterTime.UnscaledTime; 63 | _nextUpdateTime = time + Interval; 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Gravity/GravitationalEntity.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using UnityEngine; 3 | 4 | namespace Archon.SwissArmyLib.Gravity 5 | { 6 | /// 7 | /// Makes this 's part of the gravitational system. 8 | /// 9 | /// For 2D physics see . 10 | /// 11 | [AddComponentMenu("Archon/Gravity/GravitationalEntity")] 12 | [RequireComponent(typeof(Rigidbody))] 13 | public class GravitationalEntity : MonoBehaviour 14 | { 15 | private Rigidbody _rigidbody; 16 | 17 | [UsedImplicitly] 18 | private void Awake() 19 | { 20 | _rigidbody = GetComponent(); 21 | } 22 | 23 | [UsedImplicitly] 24 | private void OnEnable() 25 | { 26 | GravitationalSystem.Register(_rigidbody); 27 | } 28 | 29 | [UsedImplicitly] 30 | private void OnDisable() 31 | { 32 | GravitationalSystem.Unregister(_rigidbody); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Gravity/GravitationalEntity2D.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using UnityEngine; 3 | 4 | namespace Archon.SwissArmyLib.Gravity 5 | { 6 | /// 7 | /// Makes this 's part of the gravitational system. 8 | /// 9 | /// For 3D physics see . 10 | /// 11 | [AddComponentMenu("Archon/Gravity/GravitationalEntity2D")] 12 | [RequireComponent(typeof(Rigidbody2D))] 13 | public class GravitationalEntity2D : MonoBehaviour 14 | { 15 | private Rigidbody2D _rigidbody; 16 | 17 | [UsedImplicitly] 18 | private void Awake() 19 | { 20 | _rigidbody = GetComponent(); 21 | } 22 | 23 | [UsedImplicitly] 24 | private void OnEnable() 25 | { 26 | GravitationalSystem.Register(_rigidbody); 27 | } 28 | 29 | [UsedImplicitly] 30 | private void OnDisable() 31 | { 32 | GravitationalSystem.Unregister(_rigidbody); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Gravity/GravitationalSystem.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Archon.SwissArmyLib.Events; 4 | using Archon.SwissArmyLib.Events.Loops; 5 | using Archon.SwissArmyLib.Utils; 6 | using UnityEngine; 7 | 8 | namespace Archon.SwissArmyLib.Gravity 9 | { 10 | /// 11 | /// A gravitational system to allow for a more flexible gravity instead of just a constant directional gravity. 12 | /// 13 | /// Useful for planets, black holes, magnets etc. 14 | /// 15 | /// Rigidbodies that should be affected should have the component (or if using 2d physics). 16 | /// 17 | /// Add gravitational forces by implementing the interface and registering it in the system. 18 | /// See for a simple example implementation. 19 | /// 20 | /// You might want to set Unity's gravity to (0,0,0). 21 | /// 22 | public class GravitationalSystem : IEventListener { 23 | 24 | private static readonly List Affecters = new List(); 25 | private static readonly List Rigidbodies = new List(); 26 | private static readonly List Rigidbodies2D = new List(); 27 | 28 | static GravitationalSystem() 29 | { 30 | var instance = new GravitationalSystem(); 31 | ServiceLocator.RegisterSingleton(instance); 32 | ServiceLocator.GlobalReset += () => ServiceLocator.RegisterSingleton(instance); 33 | } 34 | 35 | private GravitationalSystem() 36 | { 37 | ManagedUpdate.OnFixedUpdate.AddListener(this); 38 | } 39 | 40 | /// 41 | /// Destructor 42 | /// 43 | ~GravitationalSystem() 44 | { 45 | ManagedUpdate.OnFixedUpdate.RemoveListener(this); 46 | } 47 | 48 | /// 49 | /// Registers a gravitational affecter to be part of the system. 50 | /// 51 | /// The affecter to register. 52 | public static void Register(IGravitationalAffecter affecter) 53 | { 54 | if (ReferenceEquals(affecter, null)) 55 | throw new ArgumentNullException("affecter"); 56 | 57 | Affecters.Add(affecter); 58 | } 59 | 60 | /// 61 | /// Registers a that should be affected by gravitational forces in this system. 62 | /// 63 | /// The rigidbody to register. 64 | public static void Register(Rigidbody rigidbody) 65 | { 66 | if (ReferenceEquals(rigidbody, null)) 67 | throw new ArgumentNullException("rigidbody"); 68 | 69 | Rigidbodies.Add(rigidbody); 70 | } 71 | 72 | /// 73 | /// Registers a that should be affected by gravitational forces in this system. 74 | /// 75 | /// The rigidbody to register. 76 | public static void Register(Rigidbody2D rigidbody) 77 | { 78 | if (ReferenceEquals(rigidbody, null)) 79 | throw new ArgumentNullException("rigidbody"); 80 | 81 | Rigidbodies2D.Add(rigidbody); 82 | } 83 | 84 | /// 85 | /// Unregisters a gravitational affecter from the system, so it no longer affects entities. 86 | /// 87 | /// The affecter to unregister. 88 | public static void Unregister(IGravitationalAffecter affecter) 89 | { 90 | if (ReferenceEquals(affecter, null)) 91 | throw new ArgumentNullException("affecter"); 92 | 93 | Affecters.Remove(affecter); 94 | } 95 | 96 | /// 97 | /// Unregisters a from the system, so it no longer is affected by gravitational forces in this system. 98 | /// 99 | /// The rigidbody to unregister. 100 | public static void Unregister(Rigidbody rigidbody) 101 | { 102 | if (ReferenceEquals(rigidbody, null)) 103 | throw new ArgumentNullException("rigidbody"); 104 | 105 | Rigidbodies.Remove(rigidbody); 106 | } 107 | 108 | /// 109 | /// Unregisters a from the system, so it no longer is affected by gravitational forces in this system. 110 | /// 111 | /// The rigidbody to unregister. 112 | public static void Unregister(Rigidbody2D rigidbody) 113 | { 114 | if (ReferenceEquals(rigidbody, null)) 115 | throw new ArgumentNullException("rigidbody"); 116 | 117 | Rigidbodies2D.Remove(rigidbody); 118 | } 119 | 120 | /// 121 | /// Gets the sum of all gravitational forces at a specific location. 122 | /// 123 | /// The location to test. 124 | /// A vector representing the sum of gravitational force at . 125 | public static Vector3 GetGravityAtPoint(Vector3 location) 126 | { 127 | var gravity = new Vector3(); 128 | 129 | var affecterCount = Affecters.Count; 130 | for (var i = 0; i < affecterCount; i++) 131 | { 132 | var force = Affecters[i].GetForceAt(location); 133 | gravity.x += force.x; 134 | gravity.y += force.y; 135 | gravity.z += force.z; 136 | } 137 | 138 | return gravity; 139 | } 140 | 141 | void IEventListener.OnEvent(int eventId) 142 | { 143 | if (eventId != ManagedUpdate.EventIds.FixedUpdate) 144 | return; 145 | 146 | var rigidbodyCount = Rigidbodies.Count; 147 | for (var i = 0; i < rigidbodyCount; i++) 148 | { 149 | var body = Rigidbodies[i]; 150 | 151 | if (body.useGravity && !body.IsSleeping()) 152 | { 153 | var gravity = GetGravityAtPoint(body.position); 154 | if (gravity.sqrMagnitude > 0.0001f) 155 | body.AddForce(gravity); 156 | } 157 | } 158 | 159 | var rigidbody2DCount = Rigidbodies2D.Count; 160 | for (var i = 0; i < rigidbody2DCount; i++) 161 | { 162 | var body = Rigidbodies2D[i]; 163 | var gravityScale = body.gravityScale; 164 | 165 | if (body.simulated && gravityScale > 0 && body.IsAwake()) 166 | { 167 | Vector2 gravity = GetGravityAtPoint(body.position); 168 | if (gravity.sqrMagnitude < 0.0001f) 169 | continue; 170 | 171 | gravity.x *= gravityScale; 172 | gravity.y *= gravityScale; 173 | body.AddForce(gravity); 174 | } 175 | } 176 | } 177 | } 178 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Gravity/IGravitationalAffecter.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.Gravity 4 | { 5 | /// 6 | /// Represents a gravitational pull on entities. 7 | /// 8 | public interface IGravitationalAffecter 9 | { 10 | /// 11 | /// Calculates how much gravitational pull is at a specific location caused by this affecter. 12 | /// 13 | /// The location to test. 14 | /// A vector representing the force at . 15 | Vector3 GetForceAt(Vector3 location); 16 | } 17 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Gravity/SphericalGravitationalPoint.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using UnityEngine; 3 | 4 | namespace Archon.SwissArmyLib.Gravity 5 | { 6 | /// 7 | /// A sphere-shaped gravitational point. 8 | /// 9 | /// The force is currently constant and not dependent on how close the entities are. 10 | /// 11 | [AddComponentMenu("Archon/Gravity/SphericalGravitationalPoint")] 12 | public class SphericalGravitationalPoint : MonoBehaviour, IGravitationalAffecter 13 | { 14 | [SerializeField] private float _strength = 9.82f; 15 | [SerializeField] private float _radius = 1; 16 | [SerializeField] private AnimationCurve _dropoffCurve = AnimationCurve.Linear(0, 1, 1, 0); 17 | [SerializeField] private bool _isGlobal; 18 | 19 | private float _radiusSqr; 20 | private Transform _transform; 21 | 22 | /// 23 | /// The gravitational pull of this point. 24 | /// 25 | public float Strength 26 | { 27 | get { return _strength; } 28 | set { _strength = value; } 29 | } 30 | 31 | /// 32 | /// Gets or sets the radius of this gravitational point. 33 | /// 34 | /// If is true, then this property is ignored. 35 | /// 36 | public float Radius 37 | { 38 | get { return _radius; } 39 | set 40 | { 41 | _radius = value; 42 | _radiusSqr = value * value; 43 | } 44 | } 45 | 46 | /// 47 | /// Gets or sets the dropoff curve of the gravitational force. 48 | /// 49 | public AnimationCurve DropoffCurve 50 | { 51 | get { return _dropoffCurve; } 52 | set { _dropoffCurve = value; } 53 | } 54 | 55 | /// 56 | /// Gets or sets whether this point should affect all entities regardless of whether they're in range. 57 | /// 58 | public bool IsGlobal 59 | { 60 | get { return _isGlobal; } 61 | set { _isGlobal = value; } 62 | } 63 | 64 | [UsedImplicitly] 65 | private void Awake() 66 | { 67 | _transform = transform; 68 | _radiusSqr = _radius * _radius; 69 | } 70 | 71 | [UsedImplicitly] 72 | private void OnEnable() 73 | { 74 | GravitationalSystem.Register(this); 75 | } 76 | 77 | [UsedImplicitly] 78 | private void OnDisable() 79 | { 80 | GravitationalSystem.Unregister(this); 81 | } 82 | 83 | [UsedImplicitly] 84 | private void OnDrawGizmos() 85 | { 86 | Gizmos.color = Color.magenta; 87 | Gizmos.DrawWireSphere(_transform.position, _radius); 88 | } 89 | 90 | /// 91 | public Vector3 GetForceAt(Vector3 location) 92 | { 93 | var deltaPos = _transform.position - location; 94 | 95 | var sqrDist = deltaPos.sqrMagnitude; 96 | 97 | if (_isGlobal || sqrDist < _radiusSqr) 98 | { 99 | var strength = _dropoffCurve.Evaluate(sqrDist / _radiusSqr) * _strength; 100 | var force = deltaPos.normalized; 101 | force.x *= strength; 102 | force.y *= strength; 103 | force.z *= strength; 104 | return force; 105 | } 106 | 107 | return new Vector3(); 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Pooling/GameObjectPool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using UnityEngine; 3 | using UnityEngine.SceneManagement; 4 | using Object = UnityEngine.Object; 5 | 6 | namespace Archon.SwissArmyLib.Pooling 7 | { 8 | /// 9 | /// An object pool that can recycle prefab instances. 10 | /// 11 | /// The type of the component on the prefab. 12 | public class GameObjectPool : Pool, IDisposable where T : Object 13 | { 14 | /// 15 | /// Gets the prefab used to instantiate GameObjects. 16 | /// 17 | public T Prefab { get; private set; } 18 | 19 | private readonly Transform _root; 20 | private readonly bool _multiScene; 21 | 22 | /// 23 | /// Creates a new GameObject pool for the specified prefab. 24 | /// 25 | /// The prefab used for instantiating instances. 26 | /// Should the pool and its contents survive a scene change? 27 | public GameObjectPool(T prefab, bool multiScene) : this(prefab.name, () => Object.Instantiate(prefab), multiScene) 28 | { 29 | if (ReferenceEquals(prefab, null)) 30 | throw new ArgumentNullException("prefab"); 31 | 32 | Prefab = prefab; 33 | } 34 | 35 | /// 36 | /// Creates a new GameObject pool with a custom name and a factory method used for instantiating instances. 37 | /// 38 | /// The name of the pool. 39 | /// The factory method used to instantiating instances. 40 | /// Should the pool and its contents survive a scene change? 41 | public GameObjectPool(string name, Func create, bool multiScene) : base(create) 42 | { 43 | var rootGO = new GameObject(string.Format("'{0}' Pool", name)); 44 | _root = rootGO.transform; 45 | 46 | _multiScene = multiScene; 47 | if (multiScene) 48 | Object.DontDestroyOnLoad(rootGO); 49 | 50 | SceneManager.sceneUnloaded += OnSceneUnloaded; 51 | } 52 | 53 | /// 54 | /// Destructor. 55 | /// 56 | ~GameObjectPool() 57 | { 58 | if (_root) 59 | Object.Destroy(_root.gameObject); 60 | } 61 | 62 | /// 63 | /// Destroys the pool and any despawned objects in it. 64 | /// 65 | public void Dispose() 66 | { 67 | SceneManager.sceneUnloaded -= OnSceneUnloaded; 68 | if (_root) 69 | Object.Destroy(_root.gameObject); 70 | Free.Clear(); 71 | } 72 | 73 | private void OnSceneUnloaded(Scene unloadedScene) 74 | { 75 | // clean up any instances that might've been destroyed 76 | for (var i = Free.Count - 1; i >= 0; i--) 77 | { 78 | if (!Free[i]) 79 | Free.RemoveAt(i); 80 | } 81 | } 82 | 83 | /// 84 | protected override T SpawnInternal() 85 | { 86 | var obj = base.SpawnInternal(); 87 | 88 | var gameObject = GetGameObject(obj); 89 | gameObject.transform.SetParent(null, false); 90 | if (_multiScene) 91 | SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene()); 92 | 93 | return obj; 94 | } 95 | 96 | /// 97 | /// Spawns a recycled object if there's one available, otherwise creates a new instance. 98 | /// 99 | /// The spawned object. 100 | public T Spawn(Transform parent) 101 | { 102 | var obj = SpawnInternal(); 103 | 104 | var gameObject = GetGameObject(obj); 105 | 106 | var transform = gameObject.transform; 107 | transform.SetParent(parent, false); 108 | 109 | OnSpawned(obj); 110 | 111 | return obj; 112 | } 113 | 114 | /// 115 | /// Spawns a recycled object if there's one available, otherwise creates a new instance. 116 | /// 117 | /// The spawned object. 118 | public T Spawn(Vector3 position) 119 | { 120 | var obj = SpawnInternal(); 121 | 122 | var gameObject = GetGameObject(obj); 123 | 124 | var transform = gameObject.transform; 125 | transform.SetPositionAndRotation(position, Quaternion.identity); 126 | 127 | OnSpawned(obj); 128 | 129 | return obj; 130 | } 131 | 132 | /// 133 | /// Spawns a recycled object if there's one available, otherwise creates a new instance. 134 | /// 135 | /// The spawned object. 136 | public T Spawn(Vector3 position, Quaternion rotation) 137 | { 138 | var obj = SpawnInternal(); 139 | 140 | var gameObject = GetGameObject(obj); 141 | 142 | var transform = gameObject.transform; 143 | transform.SetPositionAndRotation(position, rotation); 144 | 145 | OnSpawned(obj); 146 | 147 | return obj; 148 | } 149 | 150 | /// 151 | /// Spawns a recycled object if there's one available, otherwise creates a new instance. 152 | /// 153 | /// The spawned object. 154 | public T Spawn(Vector3 position, Quaternion rotation, Transform parent) 155 | { 156 | var obj = SpawnInternal(); 157 | 158 | var gameObject = GetGameObject(obj); 159 | 160 | var transform = gameObject.transform; 161 | transform.SetParent(parent, false); 162 | transform.SetPositionAndRotation(position, rotation); 163 | 164 | OnSpawned(obj); 165 | 166 | return obj; 167 | } 168 | 169 | /// 170 | public override void Despawn(T target) 171 | { 172 | if (ReferenceEquals(target, null)) 173 | throw new ArgumentNullException("target"); 174 | 175 | try 176 | { 177 | base.Despawn(target); 178 | } 179 | catch (ArgumentException) 180 | { 181 | throw new ArgumentException(string.Format("Target '{0}' is already despawned!", target.name), "target"); 182 | } 183 | 184 | var gameObject = GetGameObject(target); 185 | gameObject.SetActive(false); 186 | 187 | var transform = gameObject.transform; 188 | transform.SetParent(_root, false); 189 | } 190 | 191 | /// 192 | protected override void OnSpawned(T target) 193 | { 194 | var gameObject = GetGameObject(target); 195 | gameObject.SetActive(true); 196 | 197 | base.OnSpawned(target); 198 | } 199 | 200 | private static GameObject GetGameObject(T obj) 201 | { 202 | if (ReferenceEquals(obj, null)) 203 | throw new ArgumentNullException("obj"); 204 | 205 | var component = obj as Component; 206 | if (component != null) 207 | return component.gameObject; 208 | 209 | return obj as GameObject; 210 | } 211 | } 212 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Pooling/IPool.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Pooling 2 | { 3 | /// 4 | /// Represents an object pool that has methods for spawning and despawning objects. 5 | /// 6 | /// The type of objects that this pool can be used for. 7 | public interface IPool 8 | { 9 | /// 10 | /// Spawns a recycled or new instance of the type . 11 | /// 12 | /// The spawned instance. 13 | T Spawn(); 14 | 15 | /// 16 | /// Despawns an instance of the type and marks it for reuse. 17 | /// 18 | /// The instance to despawn. 19 | void Despawn(T target); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Pooling/IPoolable.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Pooling 2 | { 3 | /// 4 | /// Represents an object that can be recycled in an and should be notified when it's spawned and despawned. 5 | /// 6 | public interface IPoolable 7 | { 8 | /// 9 | /// Called when the object is spawned (either fresh or recycled). 10 | /// 11 | void OnSpawned(); 12 | 13 | /// 14 | /// Called when the object is despawned and marked for recycling. 15 | /// 16 | void OnDespawned(); 17 | } 18 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Pooling/Pool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Archon.SwissArmyLib.Events; 4 | using UnityEngine; 5 | 6 | namespace Archon.SwissArmyLib.Pooling 7 | { 8 | /// 9 | /// An object pool that can recycle objects of the type . 10 | /// 11 | /// If the type implements they will be notified when they're spawned and despawned. 12 | /// 13 | /// The type of objects this object pool should contain. 14 | public class Pool : IPool, TellMeWhen.ITimerCallback where T : class 15 | { 16 | /// 17 | /// Gets the current amount of free instances in the pool. 18 | /// 19 | public int FreeCount { get { return Free.Count; } } 20 | 21 | /// 22 | /// Contains the items ready to be reused. 23 | /// 24 | protected readonly List Free = new List(); 25 | 26 | private readonly Func _factory; 27 | 28 | private int _nextTimerId; 29 | private readonly Dictionary _instanceToTimerId = new Dictionary(); 30 | 31 | /// 32 | /// Creates a new object pool that uses the specified factory method to create object instances. 33 | /// 34 | /// Factory method to use for creating new instances. 35 | public Pool(Func create) 36 | { 37 | if (ReferenceEquals(create, null)) 38 | throw new ArgumentNullException("create"); 39 | 40 | _factory = create; 41 | } 42 | 43 | /// 44 | /// Fills the pool with objects so that it contains the specified amount of objects. 45 | /// 46 | /// If it already contains the specified amount or more, nothing will be done. 47 | /// 48 | /// 49 | public void Prewarm(int targetCount) 50 | { 51 | if (Free.Capacity < targetCount) 52 | Free.Capacity = targetCount; 53 | 54 | for (var i = 0; i < targetCount && Free.Count < targetCount; i++) 55 | Despawn(_factory()); 56 | } 57 | 58 | /// 59 | /// Spawns a recycled object if there's one available, otherwise creates a new instance. 60 | /// 61 | /// The spawned object. 62 | public T Spawn() 63 | { 64 | var obj = SpawnInternal(); 65 | OnSpawned(obj); 66 | 67 | return obj; 68 | } 69 | 70 | /// 71 | /// Recycles or creates a object if there's one available without calling . 72 | /// 73 | /// The spawned object. 74 | protected virtual T SpawnInternal() 75 | { 76 | T obj; 77 | 78 | if (Free.Count > 0) 79 | { 80 | obj = Free[Free.Count - 1]; 81 | Free.RemoveAt(Free.Count - 1); 82 | } 83 | else 84 | obj = _factory(); 85 | 86 | return obj; 87 | } 88 | 89 | /// 90 | /// Despawns an object, adding it back to the pool. 91 | /// 92 | /// The object to despawn. 93 | public virtual void Despawn(T target) 94 | { 95 | if (ReferenceEquals(target, null)) 96 | throw new ArgumentNullException("target"); 97 | 98 | #if !TEST 99 | // costly check, so we only run it in the editor 100 | if (Application.isEditor && Free.Contains(target)) 101 | throw new ArgumentException("Target is already despawned!", "target"); 102 | #endif 103 | 104 | _instanceToTimerId.Remove(target); 105 | OnDespawned(target); 106 | Free.Add(target); 107 | } 108 | 109 | /// 110 | /// Called when an object has been spawned and removed from the pool. 111 | /// 112 | /// The spawned object. 113 | protected virtual void OnSpawned(T target) 114 | { 115 | var poolable = target as IPoolable; 116 | 117 | if (poolable != null) 118 | poolable.OnSpawned(); 119 | } 120 | 121 | /// 122 | /// Called when an object has been despawned and placed back in the pool. 123 | /// 124 | /// The despawned object. 125 | protected virtual void OnDespawned(T target) 126 | { 127 | var poolable = target as IPoolable; 128 | 129 | if (poolable != null) 130 | poolable.OnDespawned(); 131 | } 132 | 133 | /// 134 | /// Despawns an object after a delay. 135 | /// 136 | /// The target to despawn. 137 | /// Time in seconds to wait before despawning the target. 138 | /// Should the delay be according to or ? 139 | public void Despawn(T target, float delay, bool unscaledTime = false) 140 | { 141 | if (ReferenceEquals(target, null)) 142 | throw new ArgumentNullException("target"); 143 | 144 | var id = _nextTimerId++; 145 | _instanceToTimerId[target] = id; 146 | 147 | if (unscaledTime) 148 | TellMeWhen.SecondsUnscaled(delay, this, id, target); 149 | else 150 | TellMeWhen.Seconds(delay, this, id, target); 151 | } 152 | 153 | /// 154 | /// Cancels a pending timed despawn. 155 | /// 156 | /// The target that shouldn't despawn after all. 157 | public void CancelDespawn(T target) 158 | { 159 | if (ReferenceEquals(target, null)) 160 | throw new ArgumentNullException("target"); 161 | 162 | _instanceToTimerId.Remove(target); 163 | } 164 | 165 | void TellMeWhen.ITimerCallback.OnTimesUp(int id, object args) 166 | { 167 | var target = args as T; 168 | 169 | int mappedId; 170 | 171 | if (target != null && _instanceToTimerId.TryGetValue(target, out mappedId) && mappedId == id) 172 | Despawn(target); 173 | } 174 | } 175 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Pooling/PoolableGroup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Archon.SwissArmyLib.Utils.Editor; 5 | using JetBrains.Annotations; 6 | using UnityEngine; 7 | 8 | namespace Archon.SwissArmyLib.Pooling 9 | { 10 | /// 11 | /// Manages a list of IPoolable components found in the hierarchy of this GameObject and notifies them when it is spawned and despawned. 12 | /// 13 | [AddComponentMenu("Archon/Poolable Group")] 14 | public sealed class PoolableGroup : MonoBehaviour, IPoolable, ISerializationCallbackReceiver 15 | { 16 | [SerializeField, ReadOnly, UsedImplicitly] 17 | private List _poolableComponents = new List(); 18 | 19 | void IPoolable.OnSpawned() 20 | { 21 | for (var i = 0; i < _poolableComponents.Count; i++) 22 | ((IPoolable)_poolableComponents[i]).OnSpawned(); 23 | } 24 | 25 | void IPoolable.OnDespawned() 26 | { 27 | for (var i = 0; i < _poolableComponents.Count; i++) 28 | ((IPoolable) _poolableComponents[i]).OnDespawned(); 29 | } 30 | 31 | /// 32 | /// Manually add a poolable object to be notified when this component is spawned or despawned. 33 | /// 34 | /// Useful if you dynamically add IPoolable components at runtime. 35 | /// 36 | /// The poolable object that should be notified. 37 | public void AddManually(T poolable) where T : MonoBehaviour, IPoolable 38 | { 39 | if (ReferenceEquals(poolable, null)) 40 | throw new ArgumentNullException("poolable"); 41 | 42 | _poolableComponents.Add(poolable); 43 | } 44 | 45 | /// 46 | /// Manually removes a poolable object so that it no longer is notified when this component is spawned or despawned. 47 | /// 48 | /// The poolable object that should no longer be notified. 49 | public void RemoveManually(T poolable) where T : MonoBehaviour, IPoolable 50 | { 51 | if (ReferenceEquals(poolable, null)) 52 | throw new ArgumentNullException("poolable"); 53 | 54 | _poolableComponents.Remove(poolable); 55 | } 56 | 57 | void ISerializationCallbackReceiver.OnBeforeSerialize() 58 | { 59 | if (!Application.isPlaying) 60 | { 61 | _poolableComponents.Clear(); 62 | var children = GetComponentsInChildren(true).Cast(); 63 | _poolableComponents.AddRange(children); 64 | _poolableComponents.Remove(this); 65 | } 66 | } 67 | 68 | void ISerializationCallbackReceiver.OnAfterDeserialize() 69 | { 70 | 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Archon.SwissArmyLib")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("Archon Interactive")] 11 | [assembly: AssemblyProduct("Archon.SwissArmyLib")] 12 | [assembly: AssemblyCopyright("Copyright © 2017")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("4e6e4ed1-096a-4dd2-b88f-0704bc769f22")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/ResourceSystem/ResourceEvent.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.ResourceSystem 2 | { 3 | internal class ResourceEvent : IResourceChangeEvent, IResourcePreChangeEvent 4 | { 5 | /// 6 | public float OriginalDelta { get; set; } 7 | 8 | /// 9 | public float ModifiedDelta { get; set; } 10 | 11 | /// 12 | public float AppliedDelta { get; set; } 13 | 14 | /// 15 | public TSource Source { get; set; } 16 | 17 | /// 18 | public TArgs Args { get; set; } 19 | } 20 | 21 | /// 22 | /// Defines an event for after a resource pool has been changed. 23 | /// 24 | public interface IResourceChangeEvent : IResourceEvent 25 | { 26 | /// 27 | /// Gets the originally requested resource change. 28 | /// 29 | float OriginalDelta { get; } 30 | 31 | /// 32 | /// Gets the modified delta after listeners of had their chance to affect it. 33 | /// 34 | float ModifiedDelta { get; } 35 | 36 | /// 37 | /// Gets the actual applied (and clamped) delta. 38 | /// Basically just the difference in resource amount before and after the change. 39 | /// 40 | float AppliedDelta { get; } 41 | } 42 | 43 | /// 44 | /// Defines a change event that has not yet happened, and can be altered. 45 | /// 46 | public interface IResourcePreChangeEvent : IResourceEvent 47 | { 48 | /// 49 | /// Gets the originally requested resource change. 50 | /// 51 | float OriginalDelta { get; } 52 | 53 | /// 54 | /// Gets or sets the modified delta that will be applied after this event. 55 | /// 56 | float ModifiedDelta { get; set; } 57 | } 58 | 59 | /// 60 | /// Defines a barebones resource event. 61 | /// 62 | public interface IResourceEvent 63 | { 64 | /// 65 | /// Gets or sets the source of the resource change. 66 | /// 67 | TSource Source { get; set; } 68 | 69 | /// 70 | /// Gets or sets the args that the sender sent with the change. 71 | /// 72 | TArgs Args { get; set; } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/ResourceSystem/ResourcePoolBase.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.ResourceSystem 4 | { 5 | /// 6 | /// Non-generic base class for to allow its editor to work for subclasses. 7 | /// 8 | public abstract class ResourcePoolBase : MonoBehaviour 9 | { 10 | /// 11 | /// Gets the current amount of resource in this pool. 12 | /// 13 | public abstract float Current { get; protected set; } 14 | 15 | /// 16 | /// Gets or sets the maximum amount of source that can be in this pool. 17 | /// 18 | public abstract float Max { get; set; } 19 | 20 | /// 21 | /// Gets or sets whether adding resource should be disabled after the pool is completely empty, until it is renewed again. 22 | /// 23 | public abstract bool EmptyTillRenewed { get; set; } 24 | 25 | /// 26 | /// Gets a how full the resource is percentage-wise (0 to 1) 27 | /// 28 | public abstract float Percentage { get; } 29 | 30 | /// 31 | /// Gets whether the pool is completely empty. 32 | /// 33 | public abstract bool IsEmpty { get; } 34 | 35 | /// 36 | /// Gets whether the pool is completely empty. 37 | /// 38 | public abstract bool IsFull { get; } 39 | 40 | /// 41 | /// Get the (scaled) time since this pool was last empty. 42 | /// 43 | public abstract float TimeSinceEmpty { get; } 44 | 45 | /// 46 | /// Adds the specified amount of resource to the pool. 47 | /// 48 | /// The amount to add. 49 | /// Controls whether to force the change, despite modifications by listeners. 50 | /// The resulting change in the pool. 51 | public abstract float Add(float amount, bool forced = false); 52 | 53 | /// 54 | /// Removes the specified amount of resource to the pool. 55 | /// 56 | /// The amount to remove. 57 | /// Controls whether to force the change, despite modifications by listeners. 58 | /// The resulting change in the pool. 59 | public abstract float Remove(float amount, bool forced = false); 60 | 61 | /// 62 | /// Completely empties the pool. 63 | /// 64 | /// Controls whether to force the change, despite modifications by listeners. 65 | /// The resulting change in the pool. 66 | public abstract float Empty(bool forced = false); 67 | 68 | /// 69 | /// Fully fills the pool. 70 | /// 71 | /// Controls whether to force the change, despite modifications by listeners. 72 | /// The resulting change in the pool. 73 | public abstract float Fill(bool forced = false); 74 | 75 | /// 76 | /// Fills the pool to the specified amount. 77 | /// 78 | /// The amount of resource to restore to. 79 | /// Controls whether to force the change, despite modifications by listeners. 80 | /// The resulting change in the pool. 81 | public abstract float Fill(float toValue, bool forced = false); 82 | 83 | /// 84 | /// Fully restores the pool, regardless of . 85 | /// 86 | /// Controls whether to force the change, despite modifications by listeners. 87 | /// The resulting change in the pool. 88 | public abstract float Renew(bool forced = false); 89 | 90 | /// 91 | /// Restores the pool to the specified amount, regardless of . 92 | /// 93 | /// The amount of resource to restore to. 94 | /// Controls whether to force the change, despite modifications by listeners. 95 | /// The resulting change in the pool. 96 | public abstract float Renew(float toValue, bool forced = false); 97 | } 98 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/ResourceSystem/ResourceRegen.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Archon.SwissArmyLib.Events; 3 | using Archon.SwissArmyLib.Utils; 4 | using Archon.SwissArmyLib.Utils.Editor; 5 | using JetBrains.Annotations; 6 | using UnityEngine; 7 | 8 | namespace Archon.SwissArmyLib.ResourceSystem 9 | { 10 | /// 11 | /// Adds resource to a at a constant rate or in intervals. 12 | /// 13 | /// If the is not set, it will try to find a on the same GameObject. 14 | /// 15 | /// If you need type-safety consider subclassing the generic version: . 16 | /// 17 | /// 18 | /// This non-generic version only works for the non-generic . 19 | /// 20 | /// 21 | public class ResourceRegen : ResourceRegen 22 | { 23 | [Tooltip("The target resource pool that should regen.")] 24 | [SerializeField, ReadOnly(OnlyWhilePlaying = true)] 25 | private ResourcePool _target; 26 | 27 | /// 28 | protected override void Awake() 29 | { 30 | Target = _target; 31 | base.Awake(); 32 | } 33 | } 34 | 35 | /// 36 | /// Adds resource to a at a constant rate or in intervals. 37 | /// 38 | /// If the is not set, it will try to find a on the same GameObject. 39 | /// 40 | /// Generic version of in case you want type-safety. 41 | /// To be able to use this you should make a non-generic subclass. 42 | /// 43 | public class ResourceRegen : MonoBehaviour, IEventListener> 44 | { 45 | [Tooltip("Time in seconds that regen should be paused when the target loses resource.")] 46 | [SerializeField] private float _downTimeOnResourceLoss; 47 | 48 | [Tooltip("Amount of resource that should be gained per second.")] 49 | [SerializeField] private float _constantAmountPerSecond; 50 | 51 | [Tooltip("Amount of resource that should be gained every interval.")] 52 | [SerializeField] private float _amountPerInterval; 53 | [Tooltip("How often in seconds that resource should be gained.")] 54 | [SerializeField] private float _interval; 55 | 56 | private ResourcePool _target; 57 | private float _lastInterval; 58 | private float _lastLossTime; 59 | 60 | /// 61 | /// Gets or sets how often in seconds that resources should be gained. 62 | /// 63 | public float Interval 64 | { 65 | get { return _interval; } 66 | set { _interval = value; } 67 | } 68 | 69 | /// 70 | /// Gets or sets the amount of resource that should be gained every . 71 | /// 72 | public float AmountPerInterval 73 | { 74 | get { return _amountPerInterval; } 75 | set { _amountPerInterval = value; } 76 | } 77 | 78 | /// 79 | /// Gets or sets the amount of resource that should be gained per second. 80 | /// 81 | public float ConstantAmountPerSecond 82 | { 83 | get { return _constantAmountPerSecond; } 84 | set { _constantAmountPerSecond = value; } 85 | } 86 | 87 | /// 88 | /// Gets or sets the amount of time in seconds to stop healing after the loses resource. 89 | /// 90 | public float DownTimeOnResourceLoss 91 | { 92 | get { return _downTimeOnResourceLoss; } 93 | set { _downTimeOnResourceLoss = value; } 94 | } 95 | 96 | /// 97 | /// Gets or sets the target that should regen. 98 | /// 99 | public ResourcePool Target 100 | { 101 | get { return _target; } 102 | set 103 | { 104 | if (_target != null && enabled) 105 | _target.OnChange.RemoveListener(this); 106 | 107 | _target = value; 108 | 109 | if (_target != null && enabled) 110 | _target.OnChange.AddListener(this); 111 | } 112 | } 113 | 114 | /// 115 | /// Called when the MonoBehaviour is added to a GameObject. 116 | /// 117 | [UsedImplicitly] 118 | protected virtual void Awake() 119 | { 120 | if (_target == null) 121 | _target = GetComponent>(); 122 | } 123 | 124 | /// 125 | /// Called when the MonoBehaviour is enabled. 126 | /// 127 | [UsedImplicitly] 128 | protected void OnEnable() 129 | { 130 | if (_target != null) 131 | _target.OnChange.AddListener(this); 132 | } 133 | 134 | /// 135 | /// Called when the MonoBehaviour is disabled. 136 | /// 137 | [UsedImplicitly] 138 | protected void OnDisable() 139 | { 140 | if (_target != null) 141 | _target.OnChange.RemoveListener(this); 142 | } 143 | 144 | /// 145 | /// Called every frame. 146 | /// 147 | [UsedImplicitly] 148 | protected void Update() 149 | { 150 | if (_target == null) 151 | return; 152 | 153 | var time = BetterTime.Time; 154 | 155 | if (time < _lastLossTime + DownTimeOnResourceLoss) 156 | return; 157 | 158 | if (Math.Abs(ConstantAmountPerSecond) > 0.001f) 159 | _target.Add(ConstantAmountPerSecond * BetterTime.DeltaTime); 160 | 161 | if (Interval > 0 && time > _lastInterval + Interval) 162 | { 163 | _target.Add(AmountPerInterval); 164 | _lastInterval = time; 165 | } 166 | } 167 | 168 | void IEventListener>.OnEvent(int eventId, IResourceChangeEvent args) 169 | { 170 | if (args.AppliedDelta < 0) 171 | _lastLossTime = BetterTime.Time; 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/BetterTime.cs: -------------------------------------------------------------------------------- 1 | using Archon.SwissArmyLib.Utils.Editor; 2 | using JetBrains.Annotations; 3 | using UnityEngine; 4 | using UnityTime = UnityEngine.Time; 5 | 6 | namespace Archon.SwissArmyLib.Utils 7 | { 8 | [ExecutionOrder(Order = int.MinValue, Forced = true)] 9 | [AddComponentMenu("")] 10 | internal class BetterTimeUpdater : MonoBehaviour 11 | { 12 | [UsedImplicitly] 13 | private void Awake() 14 | { 15 | BetterTime.Update(); 16 | } 17 | 18 | [UsedImplicitly] 19 | private void OnEnable() 20 | { 21 | var instance = ServiceLocator.Resolve(); 22 | 23 | if (instance == null) 24 | ServiceLocator.RegisterSingleton(this); 25 | else if (instance != this) 26 | Destroy(this); 27 | } 28 | 29 | [UsedImplicitly] 30 | private void Start() 31 | { 32 | BetterTime.Update(); 33 | } 34 | 35 | [UsedImplicitly] 36 | private void Update() 37 | { 38 | BetterTime.Update(); 39 | } 40 | 41 | [UsedImplicitly] 42 | private void FixedUpdate() 43 | { 44 | BetterTime.Update(); 45 | } 46 | } 47 | 48 | /// 49 | /// A simple wrapper for Unity's that caches values to avoid the marshal overhead of each call. 50 | /// 51 | /// The performance benefit is very small, but completely free. 52 | /// 53 | /// Only readonly properties (except for ) are cached, but everything is wrapped anyway so you don't have to use multiple time classes. 54 | /// 55 | /// Since this is just a wrapper just refer to Unity's documentation about what each property does. 56 | /// 57 | public static class BetterTime 58 | { 59 | private static float _fixedDeltaTime; 60 | 61 | /// 62 | /// Gets or sets the scalar that is applied to , etc. 63 | /// 64 | public static float TimeScale 65 | { 66 | get { return UnityTime.timeScale; } 67 | set { UnityTime.timeScale = value; } 68 | } 69 | 70 | /// 71 | /// Gets the total number of frames that have passed. 72 | /// 73 | public static int FrameCount { get; private set; } 74 | 75 | /// 76 | /// Gets the (scaled) time in seconds at the beginning of this frame. 77 | /// 78 | public static float Time { get; private set; } 79 | 80 | /// 81 | /// Gets the difference in seconds since the last frame. (Scaled according to ) 82 | /// 83 | public static float DeltaTime { get; private set; } 84 | 85 | /// 86 | /// Gets a smoothed out time difference in seconds since the last frame. (Scaled according to ) 87 | /// 88 | public static float SmoothDeltaTime { get; private set; } 89 | 90 | /// 91 | /// Gets the unscaled time difference in seconds since the last frame. 92 | /// 93 | public static float UnscaledDeltaTime { get; private set; } 94 | 95 | /// 96 | /// Gets the unscaled time in seconds at the beginning of this frame. 97 | /// 98 | public static float UnscaledTime { get; private set; } 99 | 100 | /// 101 | /// Gets or sets the fixed time in seconds between FixedUpdate. 102 | /// 103 | public static float FixedDeltaTime 104 | { 105 | get { return _fixedDeltaTime; } 106 | set 107 | { 108 | _fixedDeltaTime = value; 109 | UnityTime.fixedDeltaTime = value; 110 | } 111 | } 112 | 113 | /// 114 | /// Gets the time that the latest FixedUpdate started. This is scaled according to . 115 | /// 116 | public static float FixedTime { get; private set; } 117 | 118 | /// 119 | /// Gets the unscaled time difference since the previous FixedUpdate. 120 | /// 121 | public static float FixedUnscaledDeltaTime { get; private set; } 122 | 123 | /// 124 | /// Gets the unscaled time that the latest FixedUpdate started. 125 | /// 126 | public static float FixedUnscaledTime { get; private set; } 127 | 128 | /// 129 | /// Gets whether we're inside a FixedUpdate at the moment. 130 | /// 131 | public static bool InFixedTimeStep { get { return UnityTime.inFixedTimeStep; } } 132 | 133 | /// 134 | /// Gets the real time in seconds since the game started. 135 | /// 136 | public static float RealTimeSinceStartup { get { return UnityTime.realtimeSinceStartup; }} 137 | 138 | /// 139 | /// Gets the time since the last level was loaded. 140 | /// 141 | public static float TimeSinceLevelLoad { get; private set; } 142 | 143 | /// 144 | /// Gets or sets the maximum time in seconds that a fixed timestep frame can take. 145 | /// 146 | public static float MaximumDeltaTime 147 | { 148 | get { return UnityTime.maximumDeltaTime; } 149 | set { UnityTime.maximumDeltaTime = value; } 150 | } 151 | 152 | /// 153 | /// Gets or sets the maximum time in seconds that a frame can spend on updating particles. 154 | /// 155 | public static float MaximumParticleDeltaTime 156 | { 157 | get { return UnityTime.maximumParticleDeltaTime; } 158 | set { UnityTime.maximumParticleDeltaTime = value; } 159 | } 160 | 161 | /// 162 | /// Slows game playback time to allow screenshots to be saved between frames. 163 | /// 164 | public static int CaptureFramerate 165 | { 166 | get { return UnityTime.captureFramerate; } 167 | set { UnityTime.captureFramerate = value; } 168 | } 169 | 170 | static BetterTime() 171 | { 172 | if (!ServiceLocator.IsRegistered()) 173 | ServiceLocator.RegisterSingleton(); 174 | 175 | ServiceLocator.GlobalReset += () => ServiceLocator.RegisterSingleton(); 176 | } 177 | 178 | internal static void Update() 179 | { 180 | FrameCount = UnityTime.frameCount; 181 | 182 | Time = UnityTime.time; 183 | TimeSinceLevelLoad = UnityTime.timeSinceLevelLoad; 184 | DeltaTime = UnityTime.deltaTime; 185 | SmoothDeltaTime = UnityTime.smoothDeltaTime; 186 | 187 | UnscaledTime = UnityTime.unscaledTime; 188 | UnscaledDeltaTime = UnityTime.unscaledDeltaTime; 189 | 190 | FixedTime = UnityTime.fixedTime; 191 | _fixedDeltaTime = UnityTime.fixedDeltaTime; 192 | FixedUnscaledTime = UnityTime.fixedUnscaledTime; 193 | FixedUnscaledDeltaTime = UnityTime.fixedUnscaledDeltaTime; 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/ColorUtils.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.Utils 4 | { 5 | /// 6 | /// Utility methods for . 7 | /// 8 | public static class ColorUtils 9 | { 10 | /// 11 | /// Converts the given color to its equivalent hex color in the form of #RRGGBBAA (eg. #000000FF for opaque black). 12 | /// 13 | /// The color to convert. 14 | /// The hex representation of . 15 | public static string ToHex(this Color color) 16 | { 17 | Color32 c = color; 18 | return string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", c.r, c.g, c.b, c.a); 19 | } 20 | 21 | /// 22 | /// Wraps the supplied string in rich text color tags. 23 | /// 24 | /// The text to be colored. 25 | /// The color to make the text. 26 | /// wrapped in color tags. 27 | public static string RichTextColor(string text, Color color) 28 | { 29 | return string.Format("{1}", color.ToHex(), text); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/Extensions/ListExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Archon.SwissArmyLib.Utils.Extensions 5 | { 6 | /// 7 | /// Extensions for List 8 | /// 9 | public static class ListExtensions 10 | { 11 | private static readonly Random Random = new Random(); 12 | 13 | /// 14 | /// Shuffles the list using Fisher–Yates shuffle algorithm. 15 | /// 16 | /// 17 | /// The list to shuffle. 18 | public static void Shuffle(this IList list) 19 | { 20 | var n = list.Count; 21 | while (n > 1) 22 | { 23 | n--; 24 | var k = Random.Next(n + 1); 25 | var value = list[k]; 26 | list[k] = list[n]; 27 | list[n] = value; 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/Lazy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Archon.SwissArmyLib.Utils 4 | { 5 | /// 6 | /// Provides support for lazy initialization. 7 | /// 8 | /// If you're on .NET 4.0 or higher you might want to use System.Lazy instead. 9 | /// 10 | /// The type of the lazily initialized value. 11 | public class Lazy 12 | { 13 | private T _value; 14 | private readonly Func _valueFactory; 15 | private bool _isValueCreated; 16 | 17 | /// 18 | /// Gets the lazily initialized value of this instance. 19 | /// 20 | public T Value 21 | { 22 | get 23 | { 24 | if (!_isValueCreated) 25 | Initialize(); 26 | 27 | return _value; 28 | } 29 | } 30 | 31 | /// 32 | /// Gets whether the value has been initialized. 33 | /// 34 | public bool IsValueCreated 35 | { 36 | get { return _isValueCreated; } 37 | } 38 | 39 | /// 40 | /// Initializes a new instance of the class. 41 | /// The default constructor will be used to create the lazily initialized value. 42 | /// 43 | public Lazy() : this(Activator.CreateInstance) 44 | { 45 | 46 | } 47 | 48 | /// 49 | /// Initializes a new instance of the class. 50 | /// The specified initialization function will be used. 51 | /// 52 | /// The function to use for producing the lazily initialized value. 53 | public Lazy(Func valueFactory) 54 | { 55 | if (ReferenceEquals(valueFactory, null)) 56 | throw new ArgumentNullException("valueFactory"); 57 | 58 | _valueFactory = valueFactory; 59 | } 60 | 61 | private void Initialize() 62 | { 63 | _value = _valueFactory(); 64 | _isValueCreated = true; 65 | } 66 | 67 | /// 68 | /// Creates a string representation of property for this instance. 69 | /// 70 | /// The result of ToString() on the lazily initialized value. 71 | public override string ToString() 72 | { 73 | return Value.ToString(); 74 | } 75 | 76 | /// 77 | /// Explicitly casts the to its lazily initialized value. 78 | /// 79 | /// 80 | /// 81 | public static explicit operator T(Lazy lazy) 82 | { 83 | return lazy.Value; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/MainThreadDispatcher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | using Archon.SwissArmyLib.Events.Loops; 5 | using UnityEngine; 6 | 7 | namespace Archon.SwissArmyLib.Utils 8 | { 9 | /// 10 | /// A dispatcher for running actions on the main thread from other threads. 11 | /// Useful for when you need to use the Unity API in your own threads, since most of the API requires to be run on the main thread. 12 | /// 13 | /// Initialize the dispatcher by running from the main thread (eg. a MonoBehaviour). 14 | /// After initialization you can enqueue actions to run via . The actions will be run in the next Unity update loop. 15 | /// 16 | public static class MainThreadDispatcher 17 | { 18 | /// 19 | /// Checks whether the current thread is the main thread. 20 | /// 21 | public static bool IsMainThread 22 | { 23 | get 24 | { 25 | EnsureInitialized(); 26 | return Thread.CurrentThread == _mainThread; 27 | } 28 | } 29 | 30 | private static readonly Queue ActionQueue = new Queue(); 31 | private static Thread _mainThread; 32 | 33 | /// 34 | /// Initializes the MainThreadDispatcher if not already done. 35 | /// Make sure this is run from the main thread. 36 | /// 37 | public static void Initialize() 38 | { 39 | if (_mainThread != null) 40 | return; 41 | 42 | _mainThread = Thread.CurrentThread; 43 | ManagedUpdate.OnUpdate.AddListener(RunPendingActions); 44 | } 45 | 46 | /// 47 | /// Enqueues the action to be run on the main thread instead of the active thread. 48 | /// 49 | /// The action to enqueue. 50 | public static void Enqueue(Action action) 51 | { 52 | EnsureInitialized(); 53 | 54 | if (IsMainThread) 55 | Debug.LogWarning("Enqueue called from the main thread. Are you sure this is what you meant to do?"); 56 | 57 | lock (ActionQueue) 58 | { 59 | ActionQueue.Enqueue(action); 60 | } 61 | } 62 | 63 | private static void EnsureInitialized() 64 | { 65 | if (_mainThread == null) 66 | { 67 | Debug.LogError("Dispatcher has not been initialized yet. Did you forget to call Initialize()?"); 68 | throw new InvalidOperationException("Dispatcher is not initialized."); 69 | } 70 | } 71 | 72 | private static void RunPendingActions() 73 | { 74 | lock (ActionQueue) 75 | { 76 | while (ActionQueue.Count > 0) 77 | { 78 | try 79 | { 80 | ActionQueue.Dequeue().Invoke(); 81 | } 82 | catch (Exception e) 83 | { 84 | Debug.LogError(e); 85 | } 86 | } 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/Shake/BaseShake.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.Utils.Shake 4 | { 5 | /// 6 | /// Represents an object that can shake a value of the type . 7 | /// 8 | /// The type of value to be shaked. 9 | public abstract class BaseShake 10 | { 11 | /// 12 | /// Gets or sets whether the shake should use or . 13 | /// 14 | public bool UnscaledTime { get; set; } 15 | 16 | /// 17 | /// Gets how long the shake last. 18 | /// 19 | public float Duration { get; private set; } 20 | 21 | /// 22 | /// Gets the frequency of the shake. 23 | /// 24 | public int Frequency { get; private set; } 25 | 26 | /// 27 | /// Gets the amplitude of the shake. 28 | /// 29 | public float Amplitude { get; private set; } 30 | 31 | /// 32 | /// Gets the shake's current progress in the range 0 to 1. 33 | /// 34 | public float NormalizedTime 35 | { 36 | get 37 | { 38 | return Mathf.InverseLerp(StartTime, StartTime + Duration, CurrentTime); 39 | } 40 | } 41 | 42 | /// 43 | /// Gets whether the shake is done. 44 | /// 45 | public bool IsDone 46 | { 47 | get { return NormalizedTime >= 1f; } 48 | } 49 | 50 | /// 51 | /// Gets or sets the time that the shake started. 52 | /// 53 | protected float StartTime { get; set; } 54 | 55 | /// 56 | /// Gets the current scaled or unscaled time. 57 | /// 58 | protected float CurrentTime 59 | { 60 | get { return UnscaledTime ? BetterTime.UnscaledTime : BetterTime.Time; } 61 | } 62 | 63 | /// 64 | /// Starts (or restarts) the shake with new parameters. 65 | /// 66 | /// Amplitude of the new shake. 67 | /// Frequency of the new shake. 68 | /// Duration of the new shake. 69 | public virtual void Start(float amplitude, int frequency, float duration) 70 | { 71 | Amplitude = amplitude; 72 | Duration = duration; 73 | Frequency = frequency; 74 | 75 | StartTime = CurrentTime; 76 | } 77 | 78 | /// 79 | /// Gets the amplitude at the current time. 80 | /// 81 | /// The current amplitude. 82 | public T GetAmplitude() 83 | { 84 | return GetAmplitude(NormalizedTime); 85 | } 86 | 87 | /// 88 | /// Gets the amplitude at a specific (normalized) time. 89 | /// 90 | /// The normalized time to get the amplitude for (0-1) 91 | /// The amplitude at the specific time. 92 | public abstract T GetAmplitude(float t); 93 | } 94 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/Shake/Shake.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | using Random = UnityEngine.Random; 4 | 5 | namespace Archon.SwissArmyLib.Utils.Shake 6 | { 7 | /// 8 | /// An object that can shake a float over time. 9 | /// 10 | public class Shake : BaseShake 11 | { 12 | private readonly List _samples = new List(); 13 | 14 | /// 15 | public override void Start(float amplitude, int frequency, float duration) 16 | { 17 | base.Start(amplitude, frequency, duration); 18 | 19 | _samples.Clear(); 20 | 21 | var samples = duration*frequency; 22 | 23 | for (var i = 0; i < samples; i++) 24 | _samples.Add(Random.value * 2 - 1); 25 | } 26 | 27 | /// 28 | public override float GetAmplitude(float t) 29 | { 30 | var sampleIndex = Mathf.FloorToInt(_samples.Count*t); 31 | var firstSample = GetSample(sampleIndex); 32 | var secondSample = GetSample(sampleIndex+1); 33 | 34 | var innerT = _samples.Count*t - sampleIndex; 35 | 36 | return Mathf.Lerp(firstSample, secondSample, innerT) * (1 - t) * Amplitude; 37 | } 38 | 39 | private float GetSample(int index) 40 | { 41 | if (index < 0 || index >= _samples.Count) 42 | return 0; 43 | 44 | return _samples[index]; 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/Shake/Shake2D.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.Utils.Shake 4 | { 5 | /// 6 | /// An object that can shake a over time. 7 | /// 8 | public class Shake2D : BaseShake 9 | { 10 | /// 11 | /// The shake used for shaking the value of the . 12 | /// 13 | public readonly Shake Horizontal = new Shake(); 14 | 15 | /// 16 | /// The shake used for shaking the value of the . 17 | /// 18 | public readonly Shake Vertical = new Shake(); 19 | 20 | /// 21 | public override void Start(float amplitude, int frequency, float duration) 22 | { 23 | base.Start(amplitude, frequency, duration); 24 | 25 | Horizontal.Start(amplitude, frequency, duration); 26 | Vertical.Start(amplitude, frequency, duration); 27 | } 28 | 29 | /// 30 | public override Vector2 GetAmplitude(float t) 31 | { 32 | return new Vector2(Horizontal.GetAmplitude(t), Vertical.GetAmplitude(t)); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/UpdateLoop.cs: -------------------------------------------------------------------------------- 1 | namespace Archon.SwissArmyLib.Utils 2 | { 3 | /// 4 | /// Unity's update loops. 5 | /// 6 | public enum UpdateLoop 7 | { 8 | #pragma warning disable 1591 9 | Update, 10 | LateUpdate, 11 | FixedUpdate, 12 | #pragma warning restore 1591 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/_Editor/ExecutionOrderAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using UnityEngine; 3 | 4 | namespace Archon.SwissArmyLib.Utils.Editor 5 | { 6 | /// 7 | /// Changes the ScriptExecutionOrder of a if it's not already explicitly set (or if is true). 8 | /// 9 | public class ExecutionOrderAttribute : Attribute 10 | { 11 | /// 12 | /// The order you want for the script to have. 13 | /// 14 | public int Order; 15 | 16 | /// 17 | /// Whether you want the order to be forcibly set and not just used as a default value. 18 | /// 19 | public bool Forced; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Archon.SwissArmyLib/Utils/_Editor/ReadOnlyAttribute.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace Archon.SwissArmyLib.Utils.Editor 4 | { 5 | /// 6 | /// Marks the field to be unchangable via the inspector. 7 | /// 8 | public class ReadOnlyAttribute : PropertyAttribute 9 | { 10 | /// 11 | /// Whether it should only be readonly during play mode. 12 | /// 13 | public bool OnlyWhilePlaying; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Archon.SwissArmyLibTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {38149324-335B-4316-8016-21AB9F9B3074} 8 | Library 9 | Properties 10 | Archon.SwissArmyLibTests 11 | Archon.SwissArmyLibTests 12 | v4.5 13 | 512 14 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 10.0 16 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 17 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 18 | False 19 | UnitTest 20 | 21 | 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | 32 | 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE 37 | prompt 38 | 4 39 | 40 | 41 | bin\Test\ 42 | TRACE 43 | true 44 | pdbonly 45 | AnyCPU 46 | prompt 47 | MinimumRecommendedRules.ruleset 48 | 49 | 50 | 51 | ..\packages\NUnit.3.8.1\lib\net45\nunit.framework.dll 52 | 53 | 54 | 55 | ..\UnityLibraries\UnityEngine.dll 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | {4E6E4ED1-096A-4DD2-B88F-0704BC769F22} 83 | Archon.SwissArmyLib 84 | 85 | 86 | 87 | 88 | 89 | 90 | False 91 | 92 | 93 | False 94 | 95 | 96 | False 97 | 98 | 99 | False 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 109 | 110 | 111 | 112 | 119 | -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Collections/DelayedListTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using NUnit.Framework; 3 | 4 | namespace Archon.SwissArmyLib.Collections.Tests 5 | { 6 | [TestFixture] 7 | public class DelayedListTests 8 | { 9 | private static void Fill(ICollection list, int amount) 10 | { 11 | for (var i = 0; i < amount; i++) 12 | list.Add(new object()); 13 | } 14 | 15 | [Test] 16 | public void Add_Unprocessed_NotAddedYet() 17 | { 18 | var list = new DelayedList(); 19 | 20 | list.Add(new object()); 21 | 22 | Assert.IsEmpty(list); 23 | } 24 | 25 | [Test] 26 | public void Add_Processed_ItemIsAdded() 27 | { 28 | var list = new DelayedList(); 29 | var item = new object(); 30 | 31 | list.Add(item); 32 | list.ProcessPending(); 33 | 34 | Assert.IsTrue(list.Contains(item)); 35 | } 36 | 37 | [Test] 38 | public void AddThenRemove_Processed_NotAdded() 39 | { 40 | var list = new DelayedList(); 41 | var item = new object(); 42 | 43 | list.Add(item); 44 | list.Remove(item); 45 | list.ProcessPending(); 46 | 47 | Assert.IsFalse(list.Contains(item)); 48 | } 49 | 50 | [Test] 51 | public void RemoveThenAdd_Processed_Added() 52 | { 53 | var list = new DelayedList(); 54 | var item = new object(); 55 | 56 | list.Remove(item); 57 | list.Add(item); 58 | list.ProcessPending(); 59 | 60 | Assert.IsTrue(list.Contains(item)); 61 | } 62 | 63 | [Test] 64 | public void Remove_Unprocessed_NotRemovedYet() 65 | { 66 | var list = new DelayedList(); 67 | var item = new object(); 68 | 69 | list.Add(item); 70 | list.ProcessPending(); 71 | list.Remove(item); 72 | 73 | Assert.IsTrue(list.Contains(item)); 74 | } 75 | 76 | [Test] 77 | public void Remove_Processed_ItemIsRemoved() 78 | { 79 | var list = new DelayedList(); 80 | var item = new object(); 81 | 82 | list.Add(item); 83 | list.ProcessPending(); 84 | list.Remove(item); 85 | list.ProcessPending(); 86 | 87 | Assert.IsFalse(list.Contains(item)); 88 | } 89 | 90 | [Test] 91 | public void Remove_Empty_Processed_NothingChanged() 92 | { 93 | var list = new DelayedList(); 94 | var item = new object(); 95 | 96 | list.Remove(item); 97 | list.ProcessPending(); 98 | 99 | Assert.IsEmpty(list); 100 | } 101 | 102 | [Test] 103 | public void Remove_NotInList_Processed_NothingChanged() 104 | { 105 | var list = new DelayedList(); 106 | var item = new object(); 107 | 108 | Fill(list, 5); 109 | list.ProcessPending(); 110 | list.Remove(item); 111 | list.ProcessPending(); 112 | 113 | Assert.AreEqual(5, list.Count); 114 | } 115 | 116 | [Test] 117 | public void AddThenClear_Processed_NoItemsAdded() 118 | { 119 | var list = new DelayedList(); 120 | 121 | Fill(list, 5); 122 | list.Clear(); 123 | list.ProcessPending(); 124 | 125 | Assert.IsEmpty(list); 126 | } 127 | 128 | [Test] 129 | public void Clear_Processed_AllItemsRemoved() 130 | { 131 | var list = new DelayedList(); 132 | 133 | Fill(list, 5); 134 | list.ProcessPending(); 135 | 136 | list.Clear(); 137 | list.ProcessPending(); 138 | 139 | Assert.IsEmpty(list); 140 | } 141 | 142 | [Test] 143 | public void ClearThenAdd_Processed_OnlyAddedItemLeft() 144 | { 145 | var list = new DelayedList(); 146 | var item = new object(); 147 | 148 | Fill(list, 5); 149 | list.ProcessPending(); 150 | 151 | list.Clear(); 152 | list.Add(item); 153 | list.ProcessPending(); 154 | 155 | Assert.AreEqual(1, list.Count); 156 | Assert.AreSame(item, list[0]); 157 | } 158 | 159 | [Test] 160 | public void ClearInstantly_Unprocessed_AllItemsRemoved() 161 | { 162 | var list = new DelayedList(); 163 | 164 | Fill(list, 5); 165 | list.ProcessPending(); 166 | list.ClearInstantly(); 167 | 168 | Assert.IsEmpty(list); 169 | } 170 | 171 | [Test] 172 | public void AddThenClearPending_Processed_NoItemsAdded() 173 | { 174 | var list = new DelayedList(); 175 | 176 | Fill(list, 5); 177 | list.ClearPending(); 178 | list.ProcessPending(); 179 | 180 | Assert.IsEmpty(list); 181 | } 182 | } 183 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Collections/Grid2DTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NUnit.Framework; 3 | 4 | namespace Archon.SwissArmyLib.Collections.Tests 5 | { 6 | [TestFixture] 7 | public class Grid2DTests 8 | { 9 | [Test] 10 | public void Constructor_CorrectSize() 11 | { 12 | var grid = new Grid2D(100, 50); 13 | 14 | Assert.AreEqual(100, grid.Width); 15 | Assert.AreEqual(50, grid.Height); 16 | } 17 | 18 | [Test] 19 | public void Constructor_AllCellsAreDefaultValue() 20 | { 21 | var grid = new Grid2D(100, 50, 33); 22 | 23 | for (var x = 0; x < grid.Width; x++) 24 | for (var y = 0; y < grid.Height; y++) 25 | Assert.AreEqual(33, grid[x, y], "({0},{1})", x, y); 26 | } 27 | 28 | [Test] 29 | public void AllCellsUsableAndUnique() 30 | { 31 | var grid = new Grid2D(100, 50, 33); 32 | 33 | for (var x = 0; x < grid.Width; x++) 34 | for (var y = 0; y < grid.Height; y++) 35 | grid[x, y] = x * grid.Height + y; 36 | 37 | for (var x = 0; x < grid.Width; x++) 38 | for (var y = 0; y < grid.Height; y++) 39 | Assert.AreEqual(x * grid.Height + y, grid[x, y], "({0},{1})", x, y); 40 | } 41 | 42 | [Test] 43 | public void Clear_Default_AllCleared() 44 | { 45 | var grid = new Grid2D(100, 50, 33); 46 | grid.Clear(1); 47 | 48 | grid.Clear(); 49 | 50 | for (var x = 0; x < grid.Width; x++) 51 | for (var y = 0; y < grid.Height; y++) 52 | Assert.AreEqual(33, grid[x, y], "({0},{1})", x, y); 53 | } 54 | 55 | public void Clear_Specific_AllCleared() 56 | { 57 | var grid = new Grid2D(100, 50, 33); 58 | 59 | grid.Clear(1); 60 | 61 | for (var x = 0; x < grid.Width; x++) 62 | for (var y = 0; y < grid.Height; y++) 63 | Assert.AreEqual(1, grid[x, y], "({0},{1})", x, y); 64 | } 65 | 66 | [Test] 67 | public void Fill_OnlyTouchesRect() 68 | { 69 | var width = 100; 70 | var height = 50; 71 | 72 | var grid = new Grid2D(width, height, 33); 73 | 74 | int minX = 5, minY = 10; 75 | int maxX = width-5, maxY = height - 10; 76 | 77 | grid.Fill(1, minX, minY, maxX, maxY); 78 | 79 | for (var x = 0; x < grid.Width; x++) 80 | { 81 | for (var y = 0; y < grid.Height; y++) 82 | { 83 | // outside rect 84 | if (x < minX || x > maxX || y < minY || y > maxY) 85 | { 86 | Assert.AreEqual(33, grid[x, y], "({0},{1})", x, y); 87 | } 88 | else 89 | Assert.AreEqual(1, grid[x, y], "({0},{1})", x, y); 90 | } 91 | } 92 | } 93 | 94 | [Test] 95 | public void OutOfBoundsThrowsException() 96 | { 97 | var grid = new Grid2D(10, 10); 98 | var i = 0; 99 | 100 | // getter 101 | Assert.Catch(() => i = grid[-1, 0]); 102 | Assert.Catch(() => i = grid[0, -1]); 103 | Assert.Catch(() => i = grid[10, 0]); 104 | Assert.Catch(() => i = grid[0, 10]); 105 | 106 | // setter 107 | Assert.Catch(() => grid[-1, 0] = 5); 108 | Assert.Catch(() => grid[0, -1] = 5); 109 | Assert.Catch(() => grid[10, 0] = 5); 110 | Assert.Catch(() => grid[0, 10] = 5); 111 | } 112 | 113 | [TestCase(20, 25, Description = "Bigger")] 114 | [TestCase(5, 2, Description = "Smaller")] 115 | [TestCase(10, 15, Description = "Mixed")] 116 | public void Resize_CorrectSize(int toWidth, int toHeight) 117 | { 118 | var grid = new Grid2D(10, 10); 119 | 120 | grid.Resize(toWidth, toHeight); 121 | 122 | Assert.AreEqual(toWidth, grid.Width); 123 | Assert.AreEqual(toHeight, grid.Height); 124 | } 125 | 126 | [Test] 127 | public void Resize_CellsStayTheSame() 128 | { 129 | int startWidth = 10, startHeight = 15; 130 | 131 | var grid = new Grid2D(startWidth, startHeight); 132 | 133 | for (var x = 0; x < grid.Width; x++) 134 | for (var y = 0; y < grid.Height; y++) 135 | grid[x, y] = x * startHeight + y; 136 | 137 | grid.Resize(20, 20); 138 | 139 | for (var x = 0; x < startWidth; x++) 140 | for (var y = 0; y < startHeight; y++) 141 | Assert.AreEqual(x * startHeight + y, grid[x, y], "({0},{1})", x, y); 142 | } 143 | 144 | [Test] 145 | public void Resize_NewCellsHaveDefaultValue() 146 | { 147 | var startWidth = 10; 148 | var startHeight = 10; 149 | var defaultVal = 5; 150 | var grid = new Grid2D(startWidth, startHeight, defaultVal); 151 | grid.Clear(10); 152 | 153 | grid.Resize(20, 20); 154 | 155 | for (var x = 0; x < grid.Width; x++) 156 | { 157 | for (var y = 0; y < grid.Height; y++) 158 | { 159 | if (x >= startWidth || y >= startHeight) 160 | Assert.AreEqual(defaultVal, grid[x, y], "({0},{1})", x, y); 161 | else 162 | Assert.AreEqual(10, grid[x, y], "({0},{1})", x, y); 163 | } 164 | } 165 | } 166 | } 167 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Collections/Grid3DTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NUnit.Framework; 3 | 4 | namespace Archon.SwissArmyLib.Collections.Tests 5 | { 6 | [TestFixture] 7 | public class Grid3DTests 8 | { 9 | [Test] 10 | public void Constructor_CorrectSize() 11 | { 12 | var grid = new Grid3D(100, 50, 24); 13 | 14 | Assert.AreEqual(100, grid.Width); 15 | Assert.AreEqual(50, grid.Height); 16 | Assert.AreEqual(24, grid.Depth); 17 | } 18 | 19 | [Test] 20 | public void Constructor_AllCellsAreDefaultValue() 21 | { 22 | var grid = new Grid3D(100, 50, 24, 33); 23 | 24 | for (var x = 0; x < grid.Width; x++) 25 | for (var y = 0; y < grid.Height; y++) 26 | for (var z = 0; z < grid.Depth; z++) 27 | Assert.AreEqual(33, grid[x, y, z], "({0},{1},{2})", x, y, z); 28 | } 29 | 30 | [Test] 31 | public void AllCellsUsableAndUnique() 32 | { 33 | var grid = new Grid3D(100, 50, 24, 33); 34 | 35 | for (var x = 0; x < grid.Width; x++) 36 | for (var y = 0; y < grid.Height; y++) 37 | for (var z = 0; z < grid.Depth; z++) 38 | grid[x, y, z] = x * grid.Height + y * grid.Depth + z; 39 | 40 | for (var x = 0; x < grid.Width; x++) 41 | for (var y = 0; y < grid.Height; y++) 42 | for (var z = 0; z < grid.Depth; z++) 43 | Assert.AreEqual(x * grid.Height + y * grid.Depth + z, grid[x, y, z], "({0},{1},{2})", x, y, z); 44 | } 45 | 46 | [Test] 47 | public void Clear_Default_AllCleared() 48 | { 49 | var grid = new Grid3D(100, 50, 24, 33); 50 | grid.Clear(1); 51 | 52 | grid.Clear(); 53 | 54 | for (var x = 0; x < grid.Width; x++) 55 | for (var y = 0; y < grid.Height; y++) 56 | for (var z = 0; z < grid.Depth; z++) 57 | Assert.AreEqual(33, grid[x, y, z], "({0},{1},{2})", x, y, z); 58 | } 59 | 60 | public void Clear_Specific_AllCleared() 61 | { 62 | var grid = new Grid3D(100, 50, 33); 63 | 64 | grid.Clear(1); 65 | 66 | for (var x = 0; x < grid.Width; x++) 67 | for (var y = 0; y < grid.Height; y++) 68 | for (var z = 0; z < grid.Depth; z++) 69 | Assert.AreEqual(1, grid[x, y, z], "({0},{1},{2})", x, y, z); 70 | } 71 | 72 | [Test] 73 | public void Fill_OnlyTouchesCube() 74 | { 75 | var width = 100; 76 | var height = 50; 77 | var depth = 24; 78 | 79 | var grid = new Grid3D(width, height, depth, 33); 80 | 81 | int minX = 5, minY = 10, minZ = 8; 82 | int maxX = width-5, maxY = height - 10, maxZ = depth - 8; 83 | 84 | grid.Fill(1, minX, minY, minZ, maxX, maxY, maxZ); 85 | 86 | for (var x = 0; x < grid.Width; x++) 87 | { 88 | for (var y = 0; y < grid.Height; y++) 89 | { 90 | for (var z = 0; z < grid.Depth; z++) 91 | { 92 | // outside cube 93 | if (x < minX || x > maxX 94 | || y < minY || y > maxY 95 | || z < minZ || z > maxZ) 96 | { 97 | Assert.AreEqual(33, grid[x, y, z], "({0},{1},{2})", x, y, z); 98 | } 99 | else 100 | Assert.AreEqual(1, grid[x, y, z], "({0},{1},{2})", x, y, z); 101 | } 102 | } 103 | } 104 | } 105 | 106 | [Test] 107 | public void OutOfBoundsThrowsException() 108 | { 109 | var grid = new Grid3D(10, 10, 10); 110 | var i = 0; 111 | 112 | // getter 113 | Assert.Catch(() => i = grid[-1, 0, 0]); 114 | Assert.Catch(() => i = grid[0, -1, 0]); 115 | Assert.Catch(() => i = grid[0, 0, -1]); 116 | Assert.Catch(() => i = grid[10, 0, 0]); 117 | Assert.Catch(() => i = grid[0, 10, 0]); 118 | Assert.Catch(() => i = grid[0, 0, 10]); 119 | 120 | // setter 121 | Assert.Catch(() => grid[-1, 0, 0] = 5); 122 | Assert.Catch(() => grid[0, -1, 0] = 5); 123 | Assert.Catch(() => grid[0, 0, -1] = 5); 124 | Assert.Catch(() => grid[10, 0, 0] = 5); 125 | Assert.Catch(() => grid[0, 10, 0] = 5); 126 | Assert.Catch(() => grid[0, 0, 10] = 5); 127 | } 128 | 129 | [TestCase(20, 25, 23, Description = "Bigger")] 130 | [TestCase(5, 2, 8, Description = "Smaller")] 131 | [TestCase(10, 15, 8, Description = "Mixed")] 132 | public void Resize_CorrectSize(int toWidth, int toHeight, int toDepth) 133 | { 134 | var grid = new Grid3D(10, 10, 10); 135 | 136 | grid.Resize(toWidth, toHeight, toDepth); 137 | 138 | Assert.AreEqual(toWidth, grid.Width); 139 | Assert.AreEqual(toHeight, grid.Height); 140 | Assert.AreEqual(toDepth, grid.Depth); 141 | } 142 | 143 | [Test] 144 | public void Resize_CellsStayTheSame() 145 | { 146 | int startWidth = 10, 147 | startHeight = 15, 148 | startDepth = 20; 149 | 150 | var grid = new Grid3D(startWidth, startHeight, startDepth); 151 | 152 | for (var x = 0; x < grid.Width; x++) 153 | for (var y = 0; y < grid.Height; y++) 154 | for (var z = 0; z < grid.Depth; z++) 155 | grid[x, y, z] = x * startHeight + y * startDepth + z; 156 | 157 | grid.Resize(20, 20, 25); 158 | 159 | for (var x = 0; x < startWidth; x++) 160 | for (var y = 0; y < startHeight; y++) 161 | for (var z = 0; z < startDepth; z++) 162 | Assert.AreEqual(x * startHeight + y * startDepth + z, grid[x, y, z], "({0},{1},{2})", x, y, z); 163 | } 164 | 165 | [Test] 166 | public void Resize_NewCellsHaveDefaultValue() 167 | { 168 | var startWidth = 10; 169 | var startHeight = 10; 170 | var startDepth = 10; 171 | var defaultVal = 5; 172 | var grid = new Grid3D(startWidth, startHeight, startDepth, defaultVal); 173 | grid.Clear(10); 174 | 175 | grid.Resize(20, 20, 20); 176 | 177 | for (var x = 0; x < grid.Width; x++) 178 | { 179 | for (var y = 0; y < grid.Height; y++) 180 | { 181 | for (var z = 0; z < grid.Depth; z++) 182 | { 183 | if (x >= startWidth || y >= startHeight || z >= startDepth) 184 | Assert.AreEqual(defaultVal, grid[x, y, z], "({0},{1},{2})", x, y, z); 185 | else 186 | Assert.AreEqual(10, grid[x, y, z], "({0},{1},{2})", x, y, z); 187 | } 188 | } 189 | } 190 | } 191 | } 192 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Collections/PrioritizedListTests.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using NUnit.Framework; 3 | 4 | namespace Archon.SwissArmyLib.Collections.Tests 5 | { 6 | [TestFixture] 7 | public class PrioritizedListTests 8 | { 9 | private static void Fill(PrioritizedList list, int startPriority, int endPriority) 10 | { 11 | for (var priority = startPriority; priority <= endPriority; priority++) 12 | list.Add(new object(), priority); 13 | } 14 | 15 | [Test] 16 | public void Add_ItemIsAdded() 17 | { 18 | var item = new object(); 19 | var list = new PrioritizedList(); 20 | 21 | list.Add(item); 22 | 23 | Assert.IsTrue(list.Contains(item)); 24 | } 25 | 26 | [Test] 27 | public void Add_Ascending_LowestPriority_IsAddedFirst() 28 | { 29 | var item = new object(); 30 | var list = new PrioritizedList(ListSortDirection.Ascending); 31 | 32 | Fill(list, -5, 5); 33 | list.Add(item, -100); 34 | 35 | Assert.AreSame(item, list[0].Item); 36 | } 37 | 38 | [Test] 39 | public void Add_Ascending_HighestPriority_IsAddedLast() 40 | { 41 | var item = new object(); 42 | var list = new PrioritizedList(ListSortDirection.Ascending); 43 | 44 | Fill(list, -5, 5); 45 | list.Add(item, 100); 46 | 47 | Assert.AreSame(item, list[list.Count - 1].Item); 48 | } 49 | 50 | [Test] 51 | public void Add_Ascending_SamePriority_IsAddedAfterOthers() 52 | { 53 | var item = new object(); 54 | var list = new PrioritizedList(ListSortDirection.Ascending); 55 | 56 | Fill(list, -5, 5); 57 | list.Add(item, list[3].Priority); 58 | 59 | Assert.AreSame(item, list[4].Item); 60 | } 61 | 62 | [Test] 63 | public void Add_Descending_LowestPriority_IsAddedLast() 64 | { 65 | var item = new object(); 66 | var list = new PrioritizedList(ListSortDirection.Descending); 67 | 68 | Fill(list, -5, 5); 69 | list.Add(item, -100); 70 | 71 | Assert.AreSame(item, list[list.Count - 1].Item); 72 | } 73 | 74 | [Test] 75 | public void Add_Descending_HighestPriority_IsAddedFirst() 76 | { 77 | var item = new object(); 78 | var list = new PrioritizedList(ListSortDirection.Descending); 79 | 80 | Fill(list, -5, 5); 81 | list.Add(item, 100); 82 | 83 | Assert.AreSame(item, list[0].Item); 84 | } 85 | 86 | [Test] 87 | public void Add_Descending_SamePriority_IsAddedAfterOthers() 88 | { 89 | var item = new object(); 90 | var list = new PrioritizedList(ListSortDirection.Descending); 91 | 92 | Fill(list, -5, 5); 93 | list.Add(item, list[3].Priority); 94 | 95 | Assert.AreSame(item, list[4].Item); 96 | } 97 | 98 | [Test] 99 | public void Remove_TargetIsRemoved() 100 | { 101 | var item = new object(); 102 | var list = new PrioritizedList { item }; 103 | 104 | Fill(list, -5, 5); 105 | list.Remove(item); 106 | 107 | Assert.IsFalse(list.Contains(item)); 108 | } 109 | 110 | [Test] 111 | public void Remove_Empty_NoErrors() 112 | { 113 | var item = new object(); 114 | var list = new PrioritizedList(); 115 | 116 | Assert.DoesNotThrow(() => list.Remove(item)); 117 | } 118 | 119 | [Test] 120 | public void Contains_True() 121 | { 122 | var item = new object(); 123 | var list = new PrioritizedList { item }; 124 | 125 | Fill(list, -5, 5); 126 | 127 | Assert.IsTrue(list.Contains(item)); 128 | } 129 | 130 | [Test] 131 | public void Contains_False() 132 | { 133 | var item = new object(); 134 | var list = new PrioritizedList(); 135 | 136 | Fill(list, -5, 5); 137 | 138 | Assert.IsFalse(list.Contains(item)); 139 | } 140 | 141 | [Test] 142 | public void IndexOf_FindsItem() 143 | { 144 | var item = new object(); 145 | var list = new PrioritizedList(); 146 | 147 | Fill(list, -5, 5); 148 | list.Add(item, list[4].Priority); 149 | 150 | var index = list.IndexOf(item); 151 | Assert.AreEqual(5, index); 152 | } 153 | 154 | [Test] 155 | public void Clear_EverythingIsRemoved() 156 | { 157 | var list = new PrioritizedList(); 158 | 159 | Fill(list, -5, 5); 160 | list.Clear(); 161 | 162 | Assert.AreEqual(0, list.Count); 163 | } 164 | } 165 | } -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Events/EventTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NUnit.Framework; 3 | 4 | namespace Archon.SwissArmyLib.Events.Tests 5 | { 6 | [TestFixture] 7 | public class EventTests 8 | { 9 | public class InterfaceListener : IEventListener 10 | { 11 | public Action Callback; 12 | 13 | public InterfaceListener(Action callback) 14 | { 15 | Callback = callback; 16 | } 17 | 18 | public void OnEvent(int eventId) 19 | { 20 | Callback?.Invoke(); 21 | } 22 | } 23 | 24 | [Test] 25 | public void AddListener_Interface_ListenerIsAdded() 26 | { 27 | var e = new Event(0); 28 | var listener = new InterfaceListener(null); 29 | 30 | e.AddListener(listener); 31 | 32 | Assert.IsTrue(e.HasListener(listener)); 33 | } 34 | 35 | [Test] 36 | public void AddListener_Delegate_ListenerIsAdded() 37 | { 38 | var e = new Event(0); 39 | Action listener = () => { }; 40 | 41 | e.AddListener(listener); 42 | 43 | Assert.IsTrue(e.HasListener(listener)); 44 | } 45 | 46 | [Test] 47 | public void RemoveListener_Interface_ListenerIsRemoved() 48 | { 49 | var e = new Event(0); 50 | var listener = new InterfaceListener(null); 51 | 52 | e.AddListener(listener); 53 | e.RemoveListener(listener); 54 | 55 | Assert.IsFalse(e.HasListener(listener)); 56 | } 57 | 58 | [Test] 59 | public void RemoveListener_Delegate_ListenerIsRemoved() 60 | { 61 | var e = new Event(0); 62 | Action listener = () => { }; 63 | 64 | e.AddListener(listener); 65 | e.RemoveListener(listener); 66 | 67 | Assert.IsFalse(e.HasListener(listener)); 68 | } 69 | 70 | [Test] 71 | public void RemoveListener_Empty_NoChange() 72 | { 73 | var e = new Event(0); 74 | var interfaceListener = new InterfaceListener(null); 75 | Action delegateListener = () => { }; 76 | 77 | e.RemoveListener(interfaceListener); 78 | e.RemoveListener(delegateListener); 79 | 80 | Assert.IsEmpty(e.Listeners); 81 | } 82 | 83 | [Test] 84 | public void Clear_AllListenersRemoved() 85 | { 86 | var e = new Event(0); 87 | 88 | for (var i = 0; i < 10; i++) 89 | { 90 | e.AddListener(new InterfaceListener(null)); 91 | e.AddListener(() => { }); 92 | } 93 | 94 | e.Clear(); 95 | 96 | Assert.IsEmpty(e.Listeners); 97 | } 98 | 99 | [Test] 100 | public void Invoke_AllListenersCalled() 101 | { 102 | var e = new Event(0); 103 | var callCount = 0; 104 | for (var i = 0; i < 10; i++) 105 | { 106 | e.AddListener(new InterfaceListener(() => callCount++)); 107 | e.AddListener(() => callCount++); 108 | } 109 | 110 | e.Invoke(); 111 | 112 | Assert.AreEqual(20, callCount); 113 | } 114 | 115 | [Test] 116 | public void Invoke_ListenerException_NoThrow() 117 | { 118 | var e = new Event(0); 119 | e.SuppressExceptions = true; 120 | 121 | for (var i = 0; i < 10; i++) 122 | { 123 | e.AddListener(new InterfaceListener(() => throw new Exception())); 124 | e.AddListener(() => throw new Exception()); 125 | } 126 | 127 | Assert.DoesNotThrow(() => e.Invoke()); 128 | } 129 | 130 | [Test] 131 | public void Invoke_AddListener_ListenerIsAddedNextCall() 132 | { 133 | var wasCalled = false; 134 | var e = new Event(0); 135 | var secondListener = new InterfaceListener(() => wasCalled = true); 136 | var firstListener = new InterfaceListener(() => e.AddListener(secondListener)); 137 | 138 | e.AddListener(firstListener); 139 | e.Invoke(); 140 | 141 | Assert.IsFalse(wasCalled); 142 | e.Invoke(); 143 | 144 | Assert.IsTrue(wasCalled); 145 | } 146 | 147 | [Test] 148 | public void Invoke_RemoveListener_ListenerIsRemovedNextCall() 149 | { 150 | var wasCalled = false; 151 | var e = new Event(0); 152 | var secondListener = new InterfaceListener(() => wasCalled = true); 153 | var firstListener = new InterfaceListener(() => e.RemoveListener(secondListener)); 154 | 155 | e.AddListener(firstListener); 156 | e.AddListener(secondListener); 157 | e.Invoke(); 158 | 159 | Assert.IsTrue(wasCalled); 160 | wasCalled = false; 161 | 162 | e.Invoke(); 163 | Assert.IsFalse(wasCalled); 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Partitioning/Bin2DTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using NUnit.Framework; 4 | using UnityEngine; 5 | 6 | namespace Archon.SwissArmyLib.Partitioning.Tests 7 | { 8 | [TestFixture] 9 | public class Bin2DTests 10 | { 11 | private static Rect GetRectInsideCell(int x, int y, float cellWidth, float cellHeight) 12 | { 13 | const float margin = 0.0001f; 14 | return new Rect(x + margin, y + margin, cellWidth - margin * 2, cellHeight - margin * 2); 15 | } 16 | 17 | private static Rect GetRectInsideCells(int minX, int minY, int maxX, int maxY, float cellWidth, 18 | float cellHeight) 19 | { 20 | var min = GetRectInsideCell(minX, minY, cellWidth, cellHeight); 21 | var max = GetRectInsideCell(maxX, maxY, cellWidth, cellHeight); 22 | 23 | return Rect.MinMaxRect(min.xMin, min.yMin, max.xMax, max.yMax); 24 | } 25 | 26 | [Test] 27 | public void Constructor_CorrectSize() 28 | { 29 | var bin = new Bin2D(9, 18, 1, 2); 30 | 31 | Assert.AreEqual(9, bin.Width); 32 | Assert.AreEqual(18, bin.Height); 33 | Assert.AreEqual(1, bin.CellWidth, 0.001f); 34 | Assert.AreEqual(2, bin.CellHeight, 0.001f); 35 | } 36 | 37 | [TestCase(0, 8)] 38 | [TestCase(4, 5)] 39 | public void Insert_InsideCell_CorrectCell(int expectedX, int expectedY) 40 | { 41 | var bin = new Bin2D(9, 9, 1, 1); 42 | var val = new object(); 43 | 44 | bin.Insert(val, GetRectInsideCell(expectedX, expectedY, 1, 1)); 45 | 46 | for (var x = 0; x < bin.Width; x++) 47 | { 48 | for (var y = 0; y < bin.Height; y++) 49 | { 50 | if (x == expectedX && y == expectedY) 51 | continue; 52 | 53 | Assert.IsNull(bin[x, y]); 54 | } 55 | } 56 | 57 | Assert.IsNotNull(bin[expectedX, expectedY]); 58 | Assert.IsTrue(bin[expectedX, expectedY].Contains(val)); 59 | } 60 | 61 | [TestCase(-1, 0)] 62 | [TestCase(9, 0)] 63 | [TestCase(0, -1)] 64 | [TestCase(0, 9)] 65 | public void Insert_OutOfBounds_NotAdded(int cellX, int cellY) 66 | { 67 | var bin = new Bin2D(9, 9, 1, 1); 68 | var val = new object(); 69 | 70 | bin.Insert(val, GetRectInsideCell(cellX, cellY, 1, 1)); 71 | 72 | for (var x = 0; x < bin.Width; x++) 73 | for (var y = 0; y < bin.Height; y++) 74 | Assert.IsNull(bin[x, y]); 75 | } 76 | 77 | [TestCase(1, 1, 7, 1)] // overlap x 78 | [TestCase(1, 1, 1, 7)] // overlap y 79 | [TestCase(1, 1, 7, 7)] // overlap both 80 | [TestCase(-1, -1, 9, 9)] // fully covered 81 | [TestCase(-1, -1, -1, -1)] // out of bounds 82 | public void Insert_Overlap_CorrectCells(int minX, int minY, int maxX, int maxY) 83 | { 84 | var bin = new Bin2D(9, 9, 1, 1); 85 | var val = new object(); 86 | 87 | var rect = GetRectInsideCells(minX, minY, maxX, maxY, 1, 1); 88 | bin.Insert(val, rect); 89 | 90 | for (var x = 0; x < bin.Width; x++) 91 | { 92 | for (var y = 0; y < bin.Height; y++) 93 | { 94 | if (x >= minX && y >= minY 95 | && x <= maxX && y <= maxY) 96 | { 97 | Assert.IsNotNull(bin[x, y]); 98 | Assert.IsTrue(bin[x, y].Contains(val)); 99 | } 100 | else 101 | Assert.IsNull(bin[x, y]); 102 | } 103 | } 104 | } 105 | 106 | [TestCase(1, 1, 7, 1)] // overlap x 107 | [TestCase(1, 1, 1, 7)] // overlap y 108 | [TestCase(1, 1, 7, 7)] // overlap both 109 | [TestCase(-1, -1, 9, 9)] // fully covered 110 | [TestCase(-1, -1, -1, -1)] // out of bounds 111 | public void Insert_WithOffsetOrigin_CorrectCells(int minX, int minY, int maxX, int maxY) 112 | { 113 | var origin = new Vector2(-4.5f, -4.5f); 114 | 115 | var bin = new Bin2D(9, 9, 1, 1, origin); 116 | var val = new object(); 117 | 118 | var rect = GetRectInsideCells(minX, minY, maxX, maxY, 1, 1); 119 | rect.x += origin.x; 120 | rect.y += origin.y; 121 | 122 | bin.Insert(val, rect); 123 | 124 | for (var x = 0; x < bin.Width; x++) 125 | { 126 | for (var y = 0; y < bin.Height; y++) 127 | { 128 | if (x >= minX && y >= minY 129 | && x <= maxX && y <= maxY) 130 | { 131 | Assert.IsNotNull(bin[x, y]); 132 | Assert.IsTrue(bin[x, y].Contains(val)); 133 | } 134 | else 135 | Assert.IsNull(bin[x, y]); 136 | } 137 | } 138 | } 139 | 140 | [Test] 141 | public void Retrieve_Empty_NoResults() 142 | { 143 | var bin = new Bin2D(9, 9, 1, 1); 144 | var rect = GetRectInsideCells(-1, -1, bin.Width, bin.Height, bin.CellWidth, bin.CellHeight); 145 | var results = new HashSet(); 146 | 147 | bin.Retrieve(rect, results); 148 | 149 | Assert.IsEmpty(results); 150 | } 151 | 152 | [TestCase(0, 0, 0, 0)] 153 | [TestCase(8, 8, 8, 8)] 154 | [TestCase(4, 1, 4, 1)] 155 | [TestCase(-1, -1, 9, 9)] // full overlap 156 | [TestCase(1, 1, 7, 7)] 157 | [TestCase(4, 1, 7, 3)] 158 | public void Retrieve_CorrectResults(int minX, int minY, int maxX, int maxY) 159 | { 160 | var bin = new Bin2D(9, 9, 1, 1); 161 | var results = new HashSet(); 162 | var val = new object(); 163 | var bounds = GetRectInsideCells(minX, minY, maxX, maxY, bin.CellWidth, bin.CellHeight); 164 | 165 | bin.Insert(val, bounds); 166 | bin.Retrieve(bounds, results); 167 | 168 | Assert.True(results.Contains(val)); 169 | } 170 | 171 | 172 | [Test] 173 | public void Remove_NoBounds_RemovedFromCells() 174 | { 175 | var bin = new Bin2D(9, 9, 1, 1); 176 | var results = new HashSet(); 177 | var val = new object(); 178 | var bounds = GetRectInsideCells(3, 6, 7, 8, bin.CellWidth, bin.CellHeight); 179 | 180 | bin.Insert(val, bounds); 181 | bin.Remove(val); 182 | bin.Retrieve(bounds, results); 183 | 184 | Assert.False(results.Contains(val)); 185 | } 186 | 187 | [Test] 188 | public void Remove_WithBounds_RemovedFromCells() 189 | { 190 | var bin = new Bin2D(9, 9, 1, 1); 191 | var results = new HashSet(); 192 | var val = new object(); 193 | var bounds = GetRectInsideCells(3, 6, 7, 8, bin.CellWidth, bin.CellHeight); 194 | 195 | bin.Insert(val, bounds); 196 | bin.Remove(val, bounds); 197 | bin.Retrieve(bounds, results); 198 | 199 | Assert.False(results.Contains(val)); 200 | } 201 | 202 | [Test] 203 | public void Clear_AllCellsEmpty() 204 | { 205 | var bin = new Bin2D(9, 9, 1, 1); 206 | var results = new HashSet(); 207 | var fullBounds = GetRectInsideCells(-1, -1, bin.Width, bin.Height, bin.CellWidth, bin.CellHeight); 208 | 209 | bin.Retrieve(fullBounds, results); 210 | 211 | Assert.AreEqual(0, results.Count); 212 | } 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Archon.SwissArmyLibTests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Archon.SwissArmyLibTests")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("38149324-335b-4316-8016-21ab9f9b3074")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Archon.SwissArmyLibTests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Documentation/.gitignore: -------------------------------------------------------------------------------- 1 | Help/ -------------------------------------------------------------------------------- /Documentation/Content/Welcome.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Repository 9 | https://github.com/ArchonInteractive/SwissArmyLib 10 | 11 | 12 | ● 13 | 14 | 15 | Wiki 16 | https://github.com/ArchonInteractive/SwissArmyLib/wiki 17 | 18 | 19 | 20 | 21 | Welcome to the API reference for SwissArmyLib. 22 | 23 | 24 |
25 | About 26 | 27 | 28 | SwissArmyLib is an attempt to create a collection of useful utilities primarily intended for Unity projects, but feel free to rip parts out and use them for whatever you want. 29 | 30 | 31 | 32 | A very important part in the design decisions of this library was to keep the garbage generation low. This means you will probably frown a little upon the use of interfaces for callbacks, instead of just using delicious delegates. It also means using the trusty old for loops for iterating through collections where possible. 33 | 34 | 35 | 36 | There's a lot of libraries with some of the same features, but they're often walled off behind a restrictive or ambiguous license. 37 | This project is under the very permissive MIT license and we honestly do not care what you use it for. 38 | 39 | 40 |
41 |
42 |
43 | -------------------------------------------------------------------------------- /Documentation/ContentLayout.content: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Documentation/Documentation.shfbproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 6 | Debug 7 | AnyCPU 8 | 2.0 9 | 0c59110b-107a-4b22-9783-8cc0737a033f 10 | 2015.6.5.0 11 | 12 | Documentation 13 | Documentation 14 | Documentation 15 | 16 | .NET Framework 3.5 17 | Help\ 18 | Documentation 19 | en-US 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 100 38 | OnlyErrors 39 | Website 40 | False 41 | True 42 | False 43 | True 44 | 1.0.0.0 45 | 2 46 | True 47 | C# 48 | Blank 49 | False 50 | VS2013 51 | False 52 | MemberName 53 | SwissArmyLib 54 | AboveNamespaces 55 | None 56 | Msdn 57 | False 58 | True 59 | False 60 | ..\ 61 | 62 | Contains classes for state machines. 63 | Contains useful collection types. 64 | Contains classes with a UnityEditor dependency. 65 | Editor classes related to the ResourceSystem. 66 | Misc editor utilities. 67 | Contains classes related to events and time handling. 68 | Contains classes related to the gravitational system. 69 | Contains classes related to object pooling. 70 | Contains classes related to the resource system (health, mana, etc). 71 | Contains various smaller utilities. 72 | Contains various smaller utilities. 73 | Contains helpful utilities for the Unity editor. 74 | Contains various extension classes. 75 | Contains helpful classes for shaking (eg. screenshake). 76 | 77 | %SHFB_COMPONENTS%\ 78 | 79 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | ..\UnityLibraries\UnityEditor.dll 111 | True 112 | 113 | 114 | ..\UnityLibraries\UnityEngine.dll 115 | True 116 | 117 | 118 | 119 | 120 | logo 121 | logo 122 | icons\logo.png 123 | 124 | 125 | 126 | 127 | 129 | 130 | 131 | 132 | 133 | 134 | OnBuildSuccess 135 | 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 archoninteractive 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://raw.githubusercontent.com/ArchonInteractive/SwissArmyLib/master/logo.png 2 | 3 | SwissArmyLib 4 | ============ 5 | 6 | .. image:: https://ci.appveyor.com/api/projects/status/sapkbwkbl5ug901u/branch/master?svg=true 7 | :alt: Build status 8 | :target: https://ci.appveyor.com/project/Phault/swissarmylib/branch/master 9 | 10 | .. image:: https://readthedocs.org/projects/swissarmylib-docs/badge/?version=latest 11 | :alt: Documentation Status 12 | :target: http://swissarmylib-docs.readthedocs.io/en/latest/?badge=latest 13 | 14 | .. image:: https://api.bintray.com/packages/phault/SwissArmyLib/development/images/download.svg 15 | :alt: Download 16 | :target: https://bintray.com/phault/SwissArmyLib/development/_latestVersion#files 17 | 18 | `API Reference `_ 19 | 20 | ---- 21 | 22 | About 23 | ----- 24 | 25 | **SwissArmyLib** is an attempt to create a collection of useful utilities with a focus on being performant. It is primarily intended for Unity projects, but feel free to rip parts out and use them for whatever you want. 26 | 27 | A very important part in the design decisions of this library was to keep the garbage generation low. This means you will probably frown a little upon the use of interfaces for callbacks, instead of just using delicious delegates. It also means using the trusty old *for* loops for iterating through collections where possible. 28 | 29 | There's a lot of libraries with some of the same features, but they're often walled off behind a restrictive or ambiguous license. 30 | This project is under the very permissive MIT license and we honestly do not care what you use it for. 31 | 32 | Features 33 | -------- 34 | 35 | * Events_ 36 | 37 | - Supports both interface and delegate listeners 38 | - Can be prioritized to control call order 39 | - Check out GlobalEvents_ if you need.. well.. global events. 40 | 41 | * Timers_ 42 | 43 | - Supports both scaled and unscaled time 44 | - Optional arbitrary args to pass in 45 | - Also uses interfaces for callbacks to avoid garbage 46 | 47 | * Coroutines_ 48 | 49 | - More performant alternative to Unity's coroutines with a very similar API. 50 | 51 | * Automata_ 52 | 53 | - `Finite State Machine`_ 54 | - `Pushdown Automaton`_ 55 | 56 | * Pooling_ 57 | 58 | - Support for both arbitrary classes and GameObjects 59 | - IPoolable_ interface for callbacks 60 | 61 | + PoolableGroup_ component in case multiple IPoolable components needs to be notified 62 | 63 | - Timed despawns 64 | 65 | * `Service Locator`_ 66 | 67 | - An implementation of the Service Locator pattern 68 | - Aware of MonoBehaviours and how to work with them 69 | - Supports scene-specific resolvers 70 | - Supports both singletons and short-lived objects 71 | 72 | + Singletons can be lazy loaded 73 | 74 | * `Managed Update Loop`_ 75 | 76 | - An update loop maintained in managed space to avoid the `overhead of Native C++ --> Managed C# `_ 77 | - Useful for non-MonoBehaviours that needs to be part of the update loop 78 | - Optional ManagedUpdateBehaviour_ class for easy usage 79 | 80 | * `Spatial Partitioning`_ 81 | 82 | - GC-friendly implementations of common space-partitioning systems 83 | 84 | * `Resource Pool`_ 85 | 86 | - Generic and flexible resource pool (health, mana, energy etc.) 87 | 88 | * Gravity 89 | 90 | - Flexible gravitational system 91 | - Useful for planet gravity, black holes, magnets and all that sort of stuff. 92 | 93 | * Misc 94 | 95 | - BetterTime_ 96 | 97 | + A wrapper for Unity's static Time class that caches the values per frame to avoid the marshal overhead. 98 | + About 4x faster than using the Time class directly, but we're talking miniscule differences here. 99 | 100 | - Shake 101 | 102 | + Useful for creating proper screen shake 103 | 104 | - `Some collection types`_ 105 | - `Some useful attributes`_ 106 | 107 | + ExecutionOrder_ 108 | 109 | * Sets a default (or forces) an execution order for a MonoBehaviour 110 | 111 | + ReadOnly_ 112 | 113 | * Makes fields uninteractable in the inspector 114 | 115 | - A few other tiny utilities 116 | 117 | Download 118 | ~~~~~~~~ 119 | Binaries for the bleeding edge can be found `here `_. 120 | Alternatively you can either `build it yourself `_ (very easily) or simply `copy the source code into your Unity project `_ and call it a day. 121 | 122 | License 123 | ~~~~~~~ 124 | `MIT `_ - Do whatever you want. :) 125 | 126 | Contributing 127 | ~~~~~~~~~~~~ 128 | Pull requests are very welcome! 129 | 130 | I might deny new features if they're too niche though, but it's still very much appreciated! 131 | 132 | If you're looking for a way to contribute, please consider helping with the documentation at `this repository `_. 133 | 134 | .. _download: https://bintray.com/phault/SwissArmyLib/development/_latestVersion#files 135 | .. _building: https://swissarmylib-docs.readthedocs.io/en/latest/Getting%20Started.html#building-the-source 136 | .. _copysource: https://swissarmylib-docs.readthedocs.io/en/latest/Getting%20Started.html#method-2-copy-source 137 | 138 | .. _Events: https://swissarmylib-docs.readthedocs.io/en/latest/Events/Event.html 139 | .. _GlobalEvents: https://swissarmylib-docs.readthedocs.io/en/latest/Events/GlobalEvents.html 140 | .. _Timers: https://swissarmylib-docs.readthedocs.io/en/latest/Events/TellMeWhen.html 141 | .. _Coroutines: https://swissarmylib-docs.readthedocs.io/en/latest/Coroutines/BetterCoroutines.html 142 | .. _Automata: https://swissarmylib-docs.readthedocs.io/en/latest/Automata/index.html 143 | .. _Finite State Machine: https://swissarmylib-docs.readthedocs.io/en/latest/Automata/Finite%20State%20Machine.html 144 | .. _Pushdown Automaton: https://swissarmylib-docs.readthedocs.io/en/latest/Automata/Pushdown%20Automaton.html 145 | .. _Pooling: https://swissarmylib-docs.readthedocs.io/en/latest/Pooling/index.html 146 | .. _IPoolable: https://swissarmylib-docs.readthedocs.io/en/latest/Pooling/IPoolable.html 147 | .. _PoolableGroup: https://swissarmylib-docs.readthedocs.io/en/latest/Pooling/PoolableGroup.html 148 | .. _Service Locator: https://swissarmylib-docs.readthedocs.io/en/latest/Utils/Service%20Locator.html 149 | .. _Managed Update Loop: https://swissarmylib-docs.readthedocs.io/en/latest/Events/ManagedUpdate.html 150 | .. _ManagedUpdateBehaviour: https://swissarmylib-docs.readthedocs.io/en/latest/Events/ManagedUpdateBehaviour.html 151 | .. _Spatial Partitioning: https://swissarmylib-docs.readthedocs.io/en/latest/Partitioning/index.html 152 | .. _Resource Pool: https://swissarmylib-docs.readthedocs.io/en/latest/Resource%20System/index.html 153 | .. _BetterTime: https://swissarmylib-docs.readthedocs.io/en/latest/Utils/BetterTime.html 154 | .. _Some collection types: https://swissarmylib-docs.readthedocs.io/en/latest/Collections/index.html 155 | .. _Some useful attributes: https://swissarmylib-docs.readthedocs.io/en/latest/Utils/Attributes/index.html 156 | .. _ExecutionOrder: https://swissarmylib-docs.readthedocs.io/en/latest/Utils/Attributes/ExecutionOrder.html 157 | .. _ReadOnly: https://swissarmylib-docs.readthedocs.io/en/latest/Utils/Attributes/ReadOnly.html 158 | -------------------------------------------------------------------------------- /UnityLibraries/README.txt: -------------------------------------------------------------------------------- 1 | According to the question: https://forum.unity3d.com/threads/unityengine-dll.17569/ 2 | and the response from Unity employees: https://forum.unity3d.com/threads/unityengine-dll.17569/#post-120067 3 | It is allowed to distribute the UnityEngine.dll in a public repository. -------------------------------------------------------------------------------- /UnityLibraries/UnityEditor.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArchonInteractive/SwissArmyLib/91c7706221e2e39b9249f3d782ae18fb5c9f3403/UnityLibraries/UnityEditor.dll -------------------------------------------------------------------------------- /UnityLibraries/UnityEditor.dll.mdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArchonInteractive/SwissArmyLib/91c7706221e2e39b9249f3d782ae18fb5c9f3403/UnityLibraries/UnityEditor.dll.mdb -------------------------------------------------------------------------------- /UnityLibraries/UnityEngine.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArchonInteractive/SwissArmyLib/91c7706221e2e39b9249f3d782ae18fb5c9f3403/UnityLibraries/UnityEngine.dll -------------------------------------------------------------------------------- /UnityLibraries/UnityEngine.dll.mdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArchonInteractive/SwissArmyLib/91c7706221e2e39b9249f3d782ae18fb5c9f3403/UnityLibraries/UnityEngine.dll.mdb -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | pull_requests: 3 | do_not_increment_build_number: true 4 | image: Visual Studio 2017 5 | configuration: 6 | - Test 7 | - Release 8 | matrix: 9 | fast_finish: true 10 | assembly_info: 11 | patch: true 12 | file: '**\AssemblyInfo.*' 13 | assembly_version: '{version}' 14 | assembly_file_version: '{version}' 15 | assembly_informational_version: '{version}' 16 | environment: 17 | SHFBROOT: C:\projects\swissarmylib\EWSoftware.SHFB.2017.5.15.0\tools\ 18 | SHFB_COMPONENTS: C:\projects\swissarmylib\EWSoftware.SHFB.NETFramework.4.7\tools\ 19 | before_build: 20 | - cmd: >- 21 | nuget restore Archon.SwissArmyLib.sln 22 | 23 | nuget install EWSoftware.SHFB -Version 2017.5.15 24 | 25 | nuget install EWSoftware.SHFB.NETFramework -Version 4.7.0 26 | build: 27 | project: Archon.SwissArmyLib.sln 28 | verbosity: minimal 29 | after_build: 30 | - ps: >- 31 | if ($env:CONFIGURATION -ne "Test") { 32 | 33 | jar -cMf "./SwissArmyLib-${env:APPVEYOR_BUILD_VERSION}.zip" -C "./bin/${env:CONFIGURATION}" . 34 | 35 | jar -cMf "./SwissArmyLib-${env:APPVEYOR_BUILD_VERSION}-Docs.zip" -C ./Documentation/Help . 36 | 37 | } 38 | test: 39 | assemblies: 40 | only: 41 | - Archon.SwissArmyLibTests\bin\Test\* 42 | artifacts: 43 | - path: SwissArmyLib-$(APPVEYOR_BUILD_VERSION).zip 44 | name: Binaries 45 | - path: SwissArmyLib-$(APPVEYOR_BUILD_VERSION)-Docs.zip 46 | name: Docs 47 | deploy: 48 | - provider: BinTray 49 | username: phault 50 | api_key: 51 | secure: ZnJnGS3aRZB0wC9Il38Y/YQLVJnZUhLUkoMh9x8tIGnJXfcjYkCuIBfPokeERMeK 52 | subject: phault 53 | repo: SwissArmyLib 54 | package: development 55 | publish: true 56 | override: true 57 | on: 58 | branch: master 59 | CONFIGURATION: Release -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArchonInteractive/SwissArmyLib/91c7706221e2e39b9249f3d782ae18fb5c9f3403/logo.png --------------------------------------------------------------------------------