RewindableAllocatorFactory.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Collections.Generic;
  2. using System.Runtime.CompilerServices;
  3. using Unity.Collections;
  4. #if UNITY_EDITOR
  5. using UnityEditor;
  6. #endif
  7. namespace LitMotion
  8. {
  9. internal static class RewindableAllocatorFactory
  10. {
  11. const int InitialSize = 128 * 1024;
  12. static bool isInitialized;
  13. static readonly Stack<AllocatorHelper<RewindableAllocator>> allocators = new();
  14. public static AllocatorHelper<RewindableAllocator> CreateAllocator()
  15. {
  16. Initialize();
  17. var allocatorHelper = new AllocatorHelper<RewindableAllocator>(Allocator.Persistent);
  18. allocatorHelper.Allocator.Initialize(InitialSize, true);
  19. allocators.Push(allocatorHelper);
  20. return allocatorHelper;
  21. }
  22. static void Initialize()
  23. {
  24. if (!isInitialized)
  25. {
  26. #if UNITY_EDITOR
  27. AssemblyReloadEvents.beforeAssemblyReload += Dispose;
  28. #else
  29. UnityEngine.Application.quitting += Dispose;
  30. #endif
  31. isInitialized = true;
  32. }
  33. }
  34. static void Dispose()
  35. {
  36. while (allocators.TryPop(out var allocatorHelper))
  37. {
  38. allocatorHelper.Allocator.Dispose();
  39. allocatorHelper.Dispose();
  40. }
  41. }
  42. }
  43. }