BsFrameAlloc.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #pragma once
  2. #include "BsPrerequisitesUtil.h"
  3. namespace BansheeEngine
  4. {
  5. /**
  6. * @brief Frame allocator. Performs very fast allocations but can only free all of its memory at once.
  7. * Perfect for allocations that last just a single frame.
  8. *
  9. * @note Not thread safe with an exception. "alloc" and "clear" methods need to be called from the same thread.
  10. * "dealloc" is thread safe and can be called from any thread.
  11. */
  12. class BS_UTILITY_EXPORT FrameAlloc
  13. {
  14. private:
  15. class MemBlock
  16. {
  17. public:
  18. MemBlock(UINT32 size);
  19. ~MemBlock();
  20. UINT8* alloc(UINT8 amount);
  21. void clear();
  22. UINT8* mData;
  23. UINT32 mFreePtr;
  24. UINT32 mSize;
  25. };
  26. public:
  27. FrameAlloc(UINT32 blockSize = 1024 * 1024);
  28. ~FrameAlloc();
  29. /**
  30. * @brief Allocates a new block of memory of the specified size.
  31. *
  32. * @param amount Amount of memory to allocate, in bytes.
  33. *
  34. * @note Not thread safe.
  35. */
  36. UINT8* alloc(UINT32 amount);
  37. /**
  38. * @brief Deallocates a previously allocated block of memory.
  39. *
  40. * @note No deallocation is actually done here. This method is only used for debug purposes
  41. * so it is easier to track down memory leaks and corruption.
  42. *
  43. * Thread safe.
  44. */
  45. void dealloc(UINT8* data);
  46. /**
  47. * @brief Deallocates all allocated memory.
  48. *
  49. * @note Not thread safe.
  50. */
  51. void clear();
  52. private:
  53. UINT32 mBlockSize;
  54. Vector<MemBlock*> mBlocks;
  55. MemBlock* mFreeBlock;
  56. std::atomic<UINT32> mTotalAllocBytes;
  57. MemBlock* allocBlock(UINT32 wantedSize);
  58. void deallocBlock(MemBlock* block);
  59. };
  60. }