Buffer.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /**
  2. * Copyright (c) 2006-2023 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "Buffer.h"
  21. #include "Graphics.h"
  22. namespace love
  23. {
  24. namespace graphics
  25. {
  26. namespace vulkan
  27. {
  28. static VkBufferUsageFlags getUsageBit(BufferUsage mode)
  29. {
  30. switch (mode)
  31. {
  32. case BUFFERUSAGE_VERTEX: return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  33. case BUFFERUSAGE_INDEX: return VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
  34. case BUFFERUSAGE_UNIFORM: return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
  35. case BUFFERUSAGE_TEXEL: return VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
  36. case BUFFERUSAGE_SHADER_STORAGE: return VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  37. case BUFFERUSAGE_INDIRECT_ARGUMENTS: return VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  38. default:
  39. throw love::Exception("unsupported BufferUsage mode");
  40. }
  41. }
  42. static VkBufferUsageFlags getVulkanUsageFlags(BufferUsageFlags flags)
  43. {
  44. VkBufferUsageFlags vkFlags = 0;
  45. for (int i = 0; i < BUFFERUSAGE_MAX_ENUM; i++)
  46. {
  47. BufferUsageFlags flag = static_cast<BufferUsageFlags>(1u << i);
  48. if (flags & flag)
  49. vkFlags |= getUsageBit((BufferUsage)i);
  50. }
  51. return vkFlags;
  52. }
  53. Buffer::Buffer(love::graphics::Graphics *gfx, const Settings &settings, const std::vector<DataDeclaration> &format, const void *data, size_t size, size_t arraylength)
  54. : love::graphics::Buffer(gfx, settings, format, size, arraylength)
  55. , zeroInitialize(settings.zeroInitialize)
  56. , initialData(data)
  57. , vgfx(dynamic_cast<Graphics*>(gfx))
  58. , usageFlags(settings.usageFlags)
  59. {
  60. loadVolatile();
  61. }
  62. bool Buffer::loadVolatile()
  63. {
  64. allocator = vgfx->getVmaAllocator();
  65. VkBufferCreateInfo bufferInfo{};
  66. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  67. bufferInfo.size = getSize();
  68. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | getVulkanUsageFlags(usageFlags);
  69. VmaAllocationCreateInfo allocCreateInfo{};
  70. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  71. if (dataUsage == BUFFERDATAUSAGE_READBACK)
  72. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  73. auto result = vmaCreateBuffer(allocator, &bufferInfo, &allocCreateInfo, &buffer, &allocation, &allocInfo);
  74. if (result != VK_SUCCESS)
  75. throw love::Exception("failed to create buffer");
  76. if (zeroInitialize)
  77. vkCmdFillBuffer(vgfx->getCommandBufferForDataTransfer(), buffer, 0, VK_WHOLE_SIZE, 0);
  78. if (initialData)
  79. fill(0, size, initialData);
  80. if (usageFlags & BUFFERUSAGEFLAG_TEXEL)
  81. {
  82. VkBufferViewCreateInfo bufferViewInfo{};
  83. bufferViewInfo.buffer = buffer;
  84. bufferViewInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  85. bufferViewInfo.format = Vulkan::getVulkanVertexFormat(getDataMember(0).decl.format);
  86. bufferViewInfo.range = VK_WHOLE_SIZE;
  87. if (vkCreateBufferView(vgfx->getDevice(), &bufferViewInfo, nullptr, &bufferView) != VK_SUCCESS)
  88. throw love::Exception("failed to create texel buffer view");
  89. }
  90. VkMemoryPropertyFlags memoryProperties;
  91. vmaGetAllocationMemoryProperties(allocator, allocation, &memoryProperties);
  92. if (memoryProperties & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  93. coherent = true;
  94. else
  95. coherent = false;
  96. if (!debugName.empty() && vgfx->getEnabledOptionalInstanceExtensions().debugInfo)
  97. {
  98. auto device = vgfx->getDevice();
  99. VkDebugUtilsObjectNameInfoEXT nameInfo{};
  100. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  101. nameInfo.objectType = VK_OBJECT_TYPE_BUFFER;
  102. nameInfo.objectHandle = (uint64_t)buffer;
  103. nameInfo.pObjectName = debugName.c_str();
  104. vkSetDebugUtilsObjectNameEXT(device, &nameInfo);
  105. }
  106. return true;
  107. }
  108. void Buffer::unloadVolatile()
  109. {
  110. if (buffer == VK_NULL_HANDLE)
  111. return;
  112. auto device = vgfx->getDevice();
  113. vgfx->queueCleanUp(
  114. [device=device, allocator=allocator, buffer=buffer, allocation=allocation, bufferView=bufferView](){
  115. vkDeviceWaitIdle(device);
  116. vmaDestroyBuffer(allocator, buffer, allocation);
  117. if (bufferView)
  118. vkDestroyBufferView(device, bufferView, nullptr);
  119. });
  120. buffer = VK_NULL_HANDLE;
  121. bufferView = VK_NULL_HANDLE;
  122. }
  123. Buffer::~Buffer()
  124. {
  125. unloadVolatile();
  126. }
  127. ptrdiff_t Buffer::getHandle() const
  128. {
  129. return (ptrdiff_t) buffer;
  130. }
  131. ptrdiff_t Buffer::getTexelBufferHandle() const
  132. {
  133. return (ptrdiff_t) bufferView;
  134. }
  135. void *Buffer::map(MapType map, size_t offset, size_t size)
  136. {
  137. if (size == 0)
  138. return nullptr;
  139. if (map == MAP_WRITE_INVALIDATE && (isImmutable() || dataUsage == BUFFERDATAUSAGE_READBACK))
  140. return nullptr;
  141. if (map == MAP_READ_ONLY && dataUsage != BUFFERDATAUSAGE_READBACK)
  142. return nullptr;
  143. mappedRange = Range(offset, size);
  144. if (!Range(0, getSize()).contains(mappedRange))
  145. return nullptr;
  146. if (dataUsage == BUFFERDATAUSAGE_READBACK)
  147. {
  148. if (!coherent)
  149. vmaInvalidateAllocation(allocator, allocation, offset, size);
  150. char *data = (char*)allocInfo.pMappedData;
  151. return (void*) (data + offset);
  152. }
  153. else
  154. {
  155. VkBufferCreateInfo bufferInfo{};
  156. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  157. bufferInfo.size = size;
  158. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  159. VmaAllocationCreateInfo allocInfo{};
  160. allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  161. allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  162. if (vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &stagingBuffer, &stagingAllocation, &stagingAllocInfo) != VK_SUCCESS)
  163. throw love::Exception("failed to create staging buffer");
  164. return stagingAllocInfo.pMappedData;
  165. }
  166. }
  167. bool Buffer::fill(size_t offset, size_t size, const void *data)
  168. {
  169. if (size == 0 || isImmutable() || dataUsage == BUFFERDATAUSAGE_READBACK)
  170. return false;
  171. if (!Range(0, getSize()).contains(Range(offset, size)))
  172. return false;
  173. VkBufferCreateInfo bufferInfo{};
  174. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  175. bufferInfo.size = size;
  176. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  177. VmaAllocationCreateInfo allocInfo{};
  178. allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  179. allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  180. VkBuffer fillBuffer;
  181. VmaAllocation fillAllocation;
  182. VmaAllocationInfo fillAllocInfo;
  183. if (vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &fillBuffer, &fillAllocation, &fillAllocInfo) != VK_SUCCESS)
  184. throw love::Exception("failed to create fill buffer");
  185. memcpy(fillAllocInfo.pMappedData, data, size);
  186. VkMemoryPropertyFlags memoryProperties;
  187. vmaGetAllocationMemoryProperties(allocator, fillAllocation, &memoryProperties);
  188. if (~memoryProperties & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  189. vmaFlushAllocation(allocator, fillAllocation, 0, size);
  190. VkBufferCopy bufferCopy{};
  191. bufferCopy.srcOffset = 0;
  192. bufferCopy.dstOffset = offset;
  193. bufferCopy.size = size;
  194. vkCmdCopyBuffer(vgfx->getCommandBufferForDataTransfer(), fillBuffer, buffer, 1, &bufferCopy);
  195. vgfx->queueCleanUp([allocator = allocator, fillBuffer = fillBuffer, fillAllocation = fillAllocation]() {
  196. vmaDestroyBuffer(allocator, fillBuffer, fillAllocation);
  197. });
  198. return true;
  199. }
  200. void Buffer::unmap(size_t usedoffset, size_t usedsize)
  201. {
  202. if (dataUsage != BUFFERDATAUSAGE_READBACK)
  203. {
  204. VkBufferCopy bufferCopy{};
  205. bufferCopy.srcOffset = usedoffset - mappedRange.getOffset();
  206. bufferCopy.dstOffset = usedoffset;
  207. bufferCopy.size = usedsize;
  208. VkMemoryPropertyFlags memoryProperties;
  209. vmaGetAllocationMemoryProperties(allocator, stagingAllocation, &memoryProperties);
  210. if (~memoryProperties & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  211. vmaFlushAllocation(allocator, stagingAllocation, bufferCopy.srcOffset, usedsize);
  212. vkCmdCopyBuffer(vgfx->getCommandBufferForDataTransfer(), stagingBuffer, buffer, 1, &bufferCopy);
  213. vgfx->queueCleanUp([allocator = allocator, stagingBuffer = stagingBuffer, stagingAllocation = stagingAllocation]() {
  214. vmaDestroyBuffer(allocator, stagingBuffer, stagingAllocation);
  215. });
  216. }
  217. }
  218. void Buffer::clear(size_t offset, size_t size)
  219. {
  220. if (isImmutable())
  221. throw love::Exception("Cannot clear an immutable Buffer.");
  222. else if (isMapped())
  223. throw love::Exception("Cannot clear a mapped Buffer.");
  224. else if (offset + size > getSize())
  225. throw love::Exception("The given offset and size parameters to clear() are not within the Buffer's size.");
  226. else if (offset % 4 != 0 || size % 4 != 0)
  227. throw love::Exception("clear() must be used with offset and size parameters that are multiples of 4 bytes.");
  228. vkCmdFillBuffer(vgfx->getCommandBufferForDataTransfer(), buffer, offset, size, 0);
  229. }
  230. void Buffer::copyTo(love::graphics::Buffer *dest, size_t sourceoffset, size_t destoffset, size_t size)
  231. {
  232. auto commandBuffer = vgfx->getCommandBufferForDataTransfer();
  233. VkBufferCopy bufferCopy{};
  234. bufferCopy.srcOffset = sourceoffset;
  235. bufferCopy.dstOffset = destoffset;
  236. bufferCopy.size = size;
  237. vkCmdCopyBuffer(commandBuffer, buffer, (VkBuffer) dest->getHandle(), 1, &bufferCopy);
  238. }
  239. } // vulkan
  240. } // graphics
  241. } // love