StackGpuAllocator.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Gr/Common.h>
  7. namespace anki {
  8. // Forward
  9. class StackGpuAllocatorChunk;
  10. /// @addtogroup graphics
  11. /// @{
  12. /// The user defined output of an allocation.
  13. class StackGpuAllocatorMemory
  14. {
  15. };
  16. /// The user defined methods to allocate memory.
  17. class StackGpuAllocatorInterface
  18. {
  19. public:
  20. virtual ~StackGpuAllocatorInterface()
  21. {
  22. }
  23. /// Allocate memory. Should be thread safe.
  24. virtual ANKI_USE_RESULT Error allocate(PtrSize size, StackGpuAllocatorMemory*& mem) = 0;
  25. /// Free memory. Should be thread safe.
  26. virtual void free(StackGpuAllocatorMemory* mem) = 0;
  27. /// If the current chunk of the linear allocator is of size N then the next chunk will be of size N*scale+bias.
  28. virtual void getChunkGrowInfo(F32& scale, PtrSize& bias, PtrSize& initialSize) = 0;
  29. virtual U32 getMaxAlignment() = 0;
  30. };
  31. /// The output of an allocation.
  32. class StackGpuAllocatorHandle
  33. {
  34. friend class StackGpuAllocator;
  35. public:
  36. StackGpuAllocatorMemory* m_memory = nullptr;
  37. PtrSize m_offset = 0;
  38. explicit operator Bool() const
  39. {
  40. return m_memory != nullptr;
  41. }
  42. };
  43. /// Linear based allocator.
  44. class StackGpuAllocator
  45. {
  46. public:
  47. StackGpuAllocator() = default;
  48. StackGpuAllocator(const StackGpuAllocator&) = delete; // Non-copyable
  49. ~StackGpuAllocator();
  50. StackGpuAllocator& operator=(const StackGpuAllocator&) = delete; // Non-copyable
  51. void init(GenericMemoryPoolAllocator<U8> alloc, StackGpuAllocatorInterface* iface);
  52. /// Allocate memory.
  53. ANKI_USE_RESULT Error allocate(PtrSize size, StackGpuAllocatorHandle& handle);
  54. /// Reset all the memory chunks. Not thread safe.
  55. void reset();
  56. StackGpuAllocatorInterface* getInterface() const
  57. {
  58. ANKI_ASSERT(m_iface);
  59. return m_iface;
  60. }
  61. private:
  62. using Chunk = StackGpuAllocatorChunk;
  63. GenericMemoryPoolAllocator<U8> m_alloc;
  64. StackGpuAllocatorInterface* m_iface = nullptr;
  65. Chunk* m_chunkListHead = nullptr;
  66. Atomic<Chunk*> m_crntChunk = {nullptr};
  67. Mutex m_lock;
  68. F32 m_scale = 0.0;
  69. PtrSize m_bias = 0;
  70. PtrSize m_initialSize = 0;
  71. U32 m_alignment = 0;
  72. };
  73. /// @}
  74. } // end namespace anki