StackGpuAllocator.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. {
  9. // Forward
  10. class StackGpuAllocatorChunk;
  11. /// @addtogroup graphics
  12. /// @{
  13. /// The user defined output of an allocation.
  14. class StackGpuAllocatorMemory
  15. {
  16. };
  17. /// The user defined methods to allocate memory.
  18. class StackGpuAllocatorInterface
  19. {
  20. public:
  21. virtual ~StackGpuAllocatorInterface()
  22. {
  23. }
  24. /// Allocate memory. Should be thread safe.
  25. virtual ANKI_USE_RESULT Error allocate(PtrSize size, StackGpuAllocatorMemory*& mem) = 0;
  26. /// Free memory. Should be thread safe.
  27. virtual void free(StackGpuAllocatorMemory* mem) = 0;
  28. /// If the current chunk of the linear allocator is of size N then the next chunk will be of size N*scale+bias.
  29. virtual void getChunkGrowInfo(F32& scale, PtrSize& bias, PtrSize& initialSize) = 0;
  30. virtual U32 getMaxAlignment() = 0;
  31. };
  32. /// The output of an allocation.
  33. class StackGpuAllocatorHandle
  34. {
  35. friend class StackGpuAllocator;
  36. public:
  37. StackGpuAllocatorMemory* m_memory = nullptr;
  38. PtrSize m_offset = 0;
  39. explicit operator Bool() const
  40. {
  41. return m_memory != nullptr;
  42. }
  43. };
  44. /// Linear based allocator.
  45. class StackGpuAllocator : public NonCopyable
  46. {
  47. public:
  48. StackGpuAllocator() = default;
  49. ~StackGpuAllocator();
  50. void init(GenericMemoryPoolAllocator<U8> alloc, StackGpuAllocatorInterface* iface);
  51. /// Allocate memory.
  52. ANKI_USE_RESULT Error allocate(PtrSize size, StackGpuAllocatorHandle& handle);
  53. /// Reset all the memory chunks. Not thread safe.
  54. void reset();
  55. StackGpuAllocatorInterface* getInterface() const
  56. {
  57. ANKI_ASSERT(m_iface);
  58. return m_iface;
  59. }
  60. private:
  61. using Chunk = StackGpuAllocatorChunk;
  62. GenericMemoryPoolAllocator<U8> m_alloc;
  63. StackGpuAllocatorInterface* m_iface = nullptr;
  64. Chunk* m_chunkListHead = nullptr;
  65. Atomic<Chunk*> m_crntChunk = {nullptr};
  66. Mutex m_lock;
  67. F32 m_scale = 0.0;
  68. PtrSize m_bias = 0;
  69. PtrSize m_initialSize = 0;
  70. U32 m_alignment = 0;
  71. };
  72. /// @}
  73. } // end namespace anki