| | 1 | | using System.Collections; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using UnityEngine; |
| | 4 | | using UnityEngine.Profiling; |
| | 5 | |
|
| | 6 | | namespace DCL |
| | 7 | | { |
| | 8 | | public class MemoryManager : IMemoryManager |
| | 9 | | { |
| | 10 | | private const ulong MAX_USED_MEMORY = (ulong)2600 * 1024 * 1024; // 2.6GB |
| | 11 | | private const float TIME_FOR_NEW_MEMORY_CHECK = 60.0f; |
| | 12 | |
|
| | 13 | | private Coroutine autoCleanupCoroutine; |
| | 14 | |
|
| | 15 | | private ulong memoryThresholdForCleanup = 0; |
| | 16 | | private float cleanupInterval; |
| | 17 | |
|
| | 18 | | public event System.Action OnCriticalMemory; |
| | 19 | |
|
| 40 | 20 | | public MemoryManager() |
| | 21 | | { |
| 40 | 22 | | this.memoryThresholdForCleanup = MAX_USED_MEMORY; |
| 40 | 23 | | this.cleanupInterval = TIME_FOR_NEW_MEMORY_CHECK; |
| 40 | 24 | | autoCleanupCoroutine = CoroutineStarter.Start(AutoCleanup()); |
| 40 | 25 | | } |
| | 26 | |
|
| | 27 | | public void Dispose() |
| | 28 | | { |
| 40 | 29 | | if (autoCleanupCoroutine != null) |
| 40 | 30 | | CoroutineStarter.Stop(autoCleanupCoroutine); |
| | 31 | |
|
| 40 | 32 | | autoCleanupCoroutine = null; |
| 40 | 33 | | } |
| | 34 | |
|
| | 35 | | public void Initialize() |
| | 36 | | { |
| 40 | 37 | | } |
| | 38 | |
|
| | 39 | | private bool NeedsMemoryCleanup() |
| | 40 | | { |
| 40 | 41 | | ulong usedMemory = (ulong)Profiler.GetTotalAllocatedMemoryLong() + (ulong)Profiler.GetMonoUsedSizeLong() + |
| | 42 | | (ulong)Profiler.GetAllocatedMemoryForGraphicsDriver(); |
| 40 | 43 | | return usedMemory >= this.memoryThresholdForCleanup; |
| | 44 | | } |
| | 45 | |
|
| | 46 | | private IEnumerator AutoCleanup() |
| | 47 | | { |
| 0 | 48 | | while (true) |
| | 49 | | { |
| 40 | 50 | | if (NeedsMemoryCleanup()) |
| | 51 | | { |
| 2 | 52 | | OnCriticalMemory?.Invoke(); |
| 2 | 53 | | yield return CleanPoolManager(); |
| 2 | 54 | | Resources.UnloadUnusedAssets(); |
| | 55 | | } |
| | 56 | |
|
| 40 | 57 | | yield return new WaitForSecondsRealtime(this.cleanupInterval); |
| | 58 | | } |
| | 59 | | } |
| | 60 | |
|
| | 61 | | public IEnumerator CleanPoolManager(bool forceCleanup = false, bool immediate = false) |
| | 62 | | { |
| 2 | 63 | | bool unusedOnly = true; |
| 2 | 64 | | bool nonPersistentOnly = true; |
| | 65 | |
|
| 2 | 66 | | if (forceCleanup) |
| | 67 | | { |
| 0 | 68 | | unusedOnly = false; |
| 0 | 69 | | nonPersistentOnly = false; |
| | 70 | | } |
| | 71 | |
|
| 2 | 72 | | if (immediate) |
| | 73 | | { |
| 0 | 74 | | PoolManager.i.Cleanup(unusedOnly, nonPersistentOnly); |
| | 75 | | } |
| | 76 | | else |
| | 77 | | { |
| 2 | 78 | | yield return PoolManager.i.CleanupAsync(unusedOnly, nonPersistentOnly, false); |
| | 79 | | } |
| 2 | 80 | | } |
| | 81 | | } |
| | 82 | | } |