ChunkPool.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using ChunkyImageLib.DataHolders;
  2. namespace ChunkyImageLib
  3. {
  4. internal class ChunkPool
  5. {
  6. public const int ChunkSize = 32;
  7. public static Vector2i ChunkSizeVec => new(ChunkSize, ChunkSize);
  8. // not thread-safe!
  9. private static ChunkPool? instance;
  10. public static ChunkPool Instance => instance ??= new ChunkPool();
  11. private List<Chunk> freeChunks = new();
  12. private HashSet<Chunk> usedChunks = new();
  13. public Chunk TransparentChunk { get; } = new Chunk();
  14. public Chunk BorrowChunk()
  15. {
  16. Chunk chunk;
  17. if (freeChunks.Count > 0)
  18. {
  19. chunk = freeChunks[^1];
  20. freeChunks.RemoveAt(freeChunks.Count - 1);
  21. }
  22. else
  23. {
  24. chunk = new Chunk();
  25. }
  26. usedChunks.Add(chunk);
  27. return chunk;
  28. }
  29. public void ReturnChunk(Chunk chunk)
  30. {
  31. if (!usedChunks.Contains(chunk))
  32. throw new Exception("This chunk wasn't borrowed");
  33. usedChunks.Remove(chunk);
  34. freeChunks.Add(chunk);
  35. MaybeDisposeChunks();
  36. }
  37. private void MaybeDisposeChunks()
  38. {
  39. for (int i = freeChunks.Count - 1; i >= 100; i++)
  40. {
  41. freeChunks[i].Dispose();
  42. freeChunks.RemoveAt(i);
  43. }
  44. }
  45. }
  46. }