Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "RingCommandContext.h"
21 :
22 : #include "lib/bits.h"
23 : #include "lib/debug.h"
24 : #include "ps/CLogger.h"
25 : #include "renderer/backend/Format.h"
26 : #include "renderer/backend/IBuffer.h"
27 : #include "renderer/backend/ITexture.h"
28 : #include "renderer/backend/vulkan/Buffer.h"
29 : #include "renderer/backend/vulkan/Device.h"
30 : #include "renderer/backend/vulkan/DeviceSelection.h"
31 : #include "renderer/backend/vulkan/Texture.h"
32 : #include "renderer/backend/vulkan/Utilities.h"
33 :
34 : #include <algorithm>
35 : #include <bit>
36 : #include <cstddef>
37 : #include <cstring>
38 : #include <limits>
39 :
40 : namespace Renderer
41 : {
42 :
43 : namespace Backend
44 : {
45 :
46 : namespace Vulkan
47 : {
48 :
49 : namespace
50 : {
51 :
52 : constexpr uint32_t INITIAL_STAGING_BUFFER_CAPACITY = 1024 * 1024;
53 : constexpr VkDeviceSize SMALL_HOST_TOTAL_MEMORY_THRESHOLD = 1024 * 1024 * 1024;
54 : constexpr uint32_t MAX_SMALL_STAGING_BUFFER_CAPACITY = 64 * 1024 * 1024;
55 : constexpr uint32_t MAX_STAGING_BUFFER_CAPACITY = 256 * 1024 * 1024;
56 :
57 : constexpr uint32_t INVALID_OFFSET = std::numeric_limits<uint32_t>::max();
58 :
59 : } // anonymous namespace
60 :
61 0 : std::unique_ptr<CRingCommandContext> CRingCommandContext::Create(
62 : CDevice* device, const size_t size, const uint32_t queueFamilyIndex,
63 : CSubmitScheduler& submitScheduler)
64 : {
65 0 : ENSURE(device);
66 :
67 0 : std::unique_ptr<CRingCommandContext> ringCommandContext{
68 0 : new CRingCommandContext{device, submitScheduler}};
69 :
70 0 : ringCommandContext->m_OptimalBufferCopyOffsetAlignment = std::max(
71 0 : 1u, static_cast<uint32_t>(device->GetChoosenPhysicalDevice().properties.limits.optimalBufferCopyOffsetAlignment));
72 : // In case of small amount of host memory it's better to make uploading
73 : // slower rather than crashing due to OOM, because memory for a
74 : // staging buffer is allocated in the host memory.
75 0 : ringCommandContext->m_MaxStagingBufferCapacity =
76 0 : device->GetChoosenPhysicalDevice().hostTotalMemory <= SMALL_HOST_TOTAL_MEMORY_THRESHOLD
77 0 : ? MAX_SMALL_STAGING_BUFFER_CAPACITY
78 : : MAX_STAGING_BUFFER_CAPACITY;
79 :
80 0 : ringCommandContext->m_Ring.resize(size);
81 0 : for (RingItem& item : ringCommandContext->m_Ring)
82 : {
83 0 : VkCommandPoolCreateInfo commandPoolCreateInfoInfo{};
84 0 : commandPoolCreateInfoInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
85 0 : commandPoolCreateInfoInfo.queueFamilyIndex = queueFamilyIndex;
86 0 : RETURN_NULLPTR_IF_NOT_VK_SUCCESS(vkCreateCommandPool(
87 : device->GetVkDevice(), &commandPoolCreateInfoInfo,
88 : nullptr, &item.commandPool));
89 :
90 0 : VkCommandBufferAllocateInfo allocateInfo{};
91 0 : allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
92 0 : allocateInfo.commandPool = item.commandPool;
93 0 : allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
94 0 : allocateInfo.commandBufferCount = 1;
95 0 : RETURN_NULLPTR_IF_NOT_VK_SUCCESS(vkAllocateCommandBuffers(
96 : device->GetVkDevice(), &allocateInfo, &item.commandBuffer));
97 0 : device->SetObjectName(
98 0 : VK_OBJECT_TYPE_COMMAND_BUFFER, item.commandBuffer, "RingCommandBuffer");
99 : }
100 :
101 0 : return ringCommandContext;
102 : }
103 :
104 0 : CRingCommandContext::CRingCommandContext(
105 0 : CDevice* device, CSubmitScheduler& submitScheduler)
106 0 : : m_Device(device), m_SubmitScheduler(submitScheduler)
107 : {
108 0 : }
109 :
110 0 : CRingCommandContext::~CRingCommandContext()
111 : {
112 0 : VkDevice device = m_Device->GetVkDevice();
113 0 : for (RingItem& item : m_Ring)
114 : {
115 0 : if (item.commandBuffer != VK_NULL_HANDLE)
116 0 : vkFreeCommandBuffers(device, item.commandPool, 1, &item.commandBuffer);
117 :
118 0 : if (item.commandPool != VK_NULL_HANDLE)
119 0 : vkDestroyCommandPool(device, item.commandPool, nullptr);
120 : }
121 0 : }
122 :
123 0 : VkCommandBuffer CRingCommandContext::GetCommandBuffer()
124 : {
125 0 : RingItem& item = m_Ring[m_RingIndex];
126 0 : if (!item.isBegan)
127 0 : Begin();
128 0 : return item.commandBuffer;
129 : }
130 :
131 0 : void CRingCommandContext::Flush()
132 : {
133 0 : RingItem& item = m_Ring[m_RingIndex];
134 0 : if (!item.isBegan)
135 : return;
136 :
137 0 : End();
138 :
139 0 : item.handle = m_SubmitScheduler.Submit(item.commandBuffer);
140 :
141 0 : m_RingIndex = (m_RingIndex + 1) % m_Ring.size();
142 : }
143 :
144 0 : void CRingCommandContext::FlushAndWait()
145 : {
146 0 : RingItem& item = m_Ring[m_RingIndex];
147 0 : ENSURE(item.isBegan);
148 :
149 0 : End();
150 :
151 0 : item.handle = m_SubmitScheduler.Submit(item.commandBuffer);
152 0 : WaitUntilFree(item);
153 0 : }
154 :
155 0 : void CRingCommandContext::ScheduleUpload(
156 : CTexture* texture, const Format dataFormat,
157 : const void* data, const size_t dataSize,
158 : const uint32_t level, const uint32_t layer)
159 : {
160 0 : const uint32_t mininumSize = 1u;
161 0 : const uint32_t width = std::max(mininumSize, texture->GetWidth() >> level);
162 0 : const uint32_t height = std::max(mininumSize, texture->GetHeight() >> level);
163 0 : ScheduleUpload(
164 : texture, dataFormat, data, dataSize,
165 : 0, 0, width, height, level, layer);
166 0 : }
167 :
168 0 : void CRingCommandContext::ScheduleUpload(
169 : CTexture* texture, const Format /*dataFormat*/,
170 : const void* data, const size_t dataSize,
171 : const uint32_t xOffset, const uint32_t yOffset,
172 : const uint32_t width, const uint32_t height,
173 : const uint32_t level, const uint32_t layer)
174 : {
175 0 : ENSURE(texture->GetType() != ITexture::Type::TEXTURE_2D_MULTISAMPLE);
176 0 : const Format format = texture->GetFormat();
177 0 : if (texture->GetType() != ITexture::Type::TEXTURE_CUBE)
178 0 : ENSURE(layer == 0);
179 0 : ENSURE(format != Format::R8G8B8_UNORM);
180 :
181 0 : const bool isCompressedFormat =
182 : format == Format::BC1_RGB_UNORM ||
183 : format == Format::BC1_RGB_SRGB ||
184 : format == Format::BC1_RGBA_UNORM ||
185 : format == Format::BC1_RGBA_SRGB ||
186 : format == Format::BC2_UNORM ||
187 : format == Format::BC2_SRGB ||
188 0 : format == Format::BC3_UNORM ||
189 : format == Format::BC3_SRGB;
190 0 : ENSURE(
191 : format == Format::R8_UNORM ||
192 : format == Format::R8G8_UNORM ||
193 : format == Format::R8G8B8A8_UNORM ||
194 : format == Format::R8G8B8A8_SRGB ||
195 : format == Format::A8_UNORM ||
196 : format == Format::L8_UNORM ||
197 : isCompressedFormat);
198 :
199 : // TODO: use a more precise format alignment.
200 0 : constexpr uint32_t formatAlignment = 16;
201 0 : const uint32_t offset = AcquireFreeSpace(dataSize, std::max(formatAlignment, m_OptimalBufferCopyOffsetAlignment));
202 :
203 0 : std::memcpy(static_cast<std::byte*>(m_StagingBuffer->GetMappedData()) + offset, data, dataSize);
204 :
205 0 : VkCommandBuffer commandBuffer = GetCommandBuffer();
206 0 : VkImage image = texture->GetImage();
207 :
208 0 : Utilities::SubmitImageMemoryBarrier(
209 : commandBuffer, image, level, layer,
210 : VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
211 : VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
212 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
213 :
214 0 : VkBufferImageCopy region{};
215 :
216 0 : region.bufferOffset = offset;
217 0 : region.bufferRowLength = 0;
218 0 : region.bufferImageHeight = 0;
219 :
220 0 : region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
221 0 : region.imageSubresource.mipLevel = level;
222 0 : region.imageSubresource.baseArrayLayer = layer;
223 0 : region.imageSubresource.layerCount = 1;
224 :
225 0 : region.imageOffset = {static_cast<int32_t>(xOffset), static_cast<int32_t>(yOffset), 0};
226 0 : region.imageExtent = {width, height, 1};
227 :
228 0 : vkCmdCopyBufferToImage(
229 : commandBuffer, m_StagingBuffer->GetVkBuffer(), image,
230 : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
231 :
232 0 : VkAccessFlags dstAccessFlags = VK_ACCESS_SHADER_READ_BIT;
233 0 : VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
234 0 : Utilities::SubmitImageMemoryBarrier(
235 : commandBuffer, image, level, layer,
236 : VK_ACCESS_TRANSFER_WRITE_BIT, dstAccessFlags,
237 : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
238 : VK_PIPELINE_STAGE_TRANSFER_BIT, dstStageMask);
239 0 : texture->SetInitialized();
240 0 : }
241 :
242 0 : void CRingCommandContext::ScheduleUpload(
243 : CBuffer* buffer, const void* data, const uint32_t dataOffset,
244 : const uint32_t dataSize)
245 : {
246 0 : constexpr uint32_t alignment = 16;
247 0 : const uint32_t offset = AcquireFreeSpace(dataSize, alignment);
248 :
249 0 : std::memcpy(static_cast<std::byte*>(m_StagingBuffer->GetMappedData()) + offset, data, dataSize);
250 :
251 0 : ScheduleUpload(buffer, dataOffset, dataSize, offset);
252 0 : }
253 :
254 0 : void CRingCommandContext::ScheduleUpload(
255 : CBuffer* buffer, const uint32_t dataOffset, const uint32_t dataSize,
256 : const UploadBufferFunction& uploadFunction)
257 : {
258 0 : constexpr uint32_t alignment = 16;
259 0 : const uint32_t offset = AcquireFreeSpace(dataSize, alignment);
260 :
261 0 : CBuffer* stagingBuffer = m_StagingBuffer->As<CBuffer>();
262 :
263 0 : uploadFunction(static_cast<uint8_t*>(stagingBuffer->GetMappedData()) + offset - dataOffset);
264 :
265 0 : ScheduleUpload(buffer, dataOffset, dataSize, offset);
266 0 : }
267 :
268 0 : void CRingCommandContext::ScheduleUpload(
269 : CBuffer* buffer, const uint32_t dataOffset, const uint32_t dataSize,
270 : const uint32_t acquiredOffset)
271 : {
272 0 : CBuffer* stagingBuffer = m_StagingBuffer->As<CBuffer>();
273 0 : VkCommandBuffer commandBuffer = GetCommandBuffer();
274 :
275 0 : VkBufferCopy region{};
276 0 : region.srcOffset = acquiredOffset;
277 0 : region.dstOffset = dataOffset;
278 0 : region.size = dataSize;
279 :
280 : // TODO: remove transfer mask from pipeline barrier, as we need to batch copies.
281 0 : VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
282 0 : VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
283 0 : if (buffer->GetType() == IBuffer::Type::VERTEX || buffer->GetType() == IBuffer::Type::INDEX)
284 : srcStageMask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
285 0 : else if (buffer->GetType() == IBuffer::Type::UNIFORM)
286 0 : srcStageMask = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
287 0 : Utilities::SubmitPipelineBarrier(
288 : commandBuffer, srcStageMask, dstStageMask);
289 :
290 : // TODO: currently we might overwrite data which triggers validation
291 : // assertion about Write-After-Write hazard.
292 0 : if (buffer->IsDynamic())
293 : {
294 0 : Utilities::SubmitBufferMemoryBarrier(
295 : commandBuffer, buffer, dataOffset, dataSize,
296 : VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
297 : VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
298 : }
299 :
300 0 : vkCmdCopyBuffer(
301 : commandBuffer, stagingBuffer->GetVkBuffer(), buffer->GetVkBuffer(), 1, ®ion);
302 :
303 0 : VkAccessFlags srcAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT;
304 0 : VkAccessFlags dstAccessFlags = 0;
305 0 : srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
306 0 : dstStageMask = 0;
307 0 : if (buffer->GetType() == IBuffer::Type::VERTEX)
308 : {
309 : dstAccessFlags = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
310 : dstStageMask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
311 : }
312 0 : else if (buffer->GetType() == IBuffer::Type::INDEX)
313 : {
314 : dstAccessFlags = VK_ACCESS_INDEX_READ_BIT;
315 : dstStageMask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
316 : }
317 0 : else if (buffer->GetType() == IBuffer::Type::UNIFORM)
318 : {
319 0 : dstAccessFlags = VK_ACCESS_UNIFORM_READ_BIT;
320 0 : dstStageMask = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
321 : }
322 0 : Utilities::SubmitBufferMemoryBarrier(
323 : commandBuffer, buffer, dataOffset, dataSize,
324 : srcAccessFlags, dstAccessFlags, srcStageMask, dstStageMask);
325 0 : }
326 :
327 0 : void CRingCommandContext::Begin()
328 : {
329 0 : RingItem& item = m_Ring[m_RingIndex];
330 0 : item.isBegan = true;
331 :
332 0 : WaitUntilFree(item);
333 :
334 0 : m_StagingBufferCurrentFirst = m_StagingBufferLast;
335 :
336 0 : ENSURE_VK_SUCCESS(vkResetCommandPool(m_Device->GetVkDevice(), item.commandPool, 0));
337 :
338 0 : VkCommandBufferBeginInfo beginInfo{};
339 0 : beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
340 0 : beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
341 0 : beginInfo.pInheritanceInfo = nullptr;
342 0 : ENSURE_VK_SUCCESS(vkBeginCommandBuffer(item.commandBuffer, &beginInfo));
343 0 : }
344 :
345 0 : void CRingCommandContext::End()
346 : {
347 0 : RingItem& item = m_Ring[m_RingIndex];
348 0 : item.isBegan = false;
349 0 : item.stagingBufferFirst = m_StagingBufferCurrentFirst;
350 0 : item.stagingBufferLast = m_StagingBufferLast;
351 :
352 0 : ENSURE_VK_SUCCESS(vkEndCommandBuffer(item.commandBuffer));
353 0 : }
354 :
355 0 : void CRingCommandContext::WaitUntilFree(RingItem& item)
356 : {
357 0 : m_SubmitScheduler.WaitUntilFree(item.handle);
358 0 : if (item.stagingBufferFirst != item.stagingBufferLast)
359 : {
360 0 : m_StagingBufferFirst = item.stagingBufferLast;
361 0 : item.stagingBufferFirst = 0;
362 0 : item.stagingBufferLast = 0;
363 : }
364 0 : }
365 :
366 0 : uint32_t CRingCommandContext::AcquireFreeSpace(
367 : const uint32_t requiredSize, const uint32_t requiredAlignment)
368 : {
369 0 : ENSURE(requiredSize <= m_MaxStagingBufferCapacity);
370 0 : const uint32_t offsetCandidate =
371 0 : GetFreeSpaceOffset(requiredSize, requiredAlignment);
372 0 : const bool needsResize =
373 0 : !m_StagingBuffer || offsetCandidate == INVALID_OFFSET;
374 0 : const bool canResize =
375 0 : !m_StagingBuffer || m_StagingBuffer->GetSize() < m_MaxStagingBufferCapacity;
376 0 : if (needsResize && canResize)
377 : {
378 0 : const uint32_t minimumRequiredCapacity = std::bit_ceil(requiredSize);
379 0 : const uint32_t newCapacity = std::min(
380 0 : std::max(m_StagingBuffer ? m_StagingBuffer->GetSize() * 2 : INITIAL_STAGING_BUFFER_CAPACITY, minimumRequiredCapacity),
381 0 : m_MaxStagingBufferCapacity);
382 0 : m_StagingBuffer = m_Device->CreateCBuffer(
383 0 : "UploadRingBuffer", IBuffer::Type::UPLOAD, newCapacity, IBuffer::Usage::TRANSFER_SRC);
384 0 : ENSURE(m_StagingBuffer);
385 0 : m_StagingBufferFirst = 0;
386 0 : m_StagingBufferCurrentFirst = 0;
387 0 : m_StagingBufferLast = requiredSize;
388 :
389 0 : for (RingItem& item : m_Ring)
390 : {
391 0 : item.stagingBufferFirst = 0;
392 0 : item.stagingBufferLast = 0;
393 : }
394 :
395 0 : return 0;
396 : }
397 0 : else if (needsResize)
398 : {
399 : // In case we can't resize we need to wait until all scheduled uploads are
400 : // completed.
401 0 : for (size_t ringIndexOffset = 1; ringIndexOffset < m_Ring.size() && GetFreeSpaceOffset(requiredSize, requiredAlignment) == INVALID_OFFSET; ++ringIndexOffset)
402 : {
403 0 : const size_t ringIndex = (m_RingIndex + ringIndexOffset) % m_Ring.size();
404 0 : RingItem& item = m_Ring[ringIndex];
405 0 : WaitUntilFree(item);
406 : }
407 : // If we still don't have a free space it means we need to flush the
408 : // current command buffer.
409 0 : const uint32_t offset = GetFreeSpaceOffset(requiredSize, requiredAlignment);
410 0 : if (offset == INVALID_OFFSET)
411 : {
412 0 : RingItem& item = m_Ring[m_RingIndex];
413 0 : if (item.isBegan)
414 0 : Flush();
415 0 : WaitUntilFree(item);
416 0 : m_StagingBufferFirst = 0;
417 0 : m_StagingBufferCurrentFirst = 0;
418 0 : m_StagingBufferLast = requiredSize;
419 0 : return 0;
420 : }
421 : else
422 : {
423 0 : m_StagingBufferLast = offset + requiredSize;
424 0 : return offset;
425 : }
426 : }
427 : else
428 : {
429 0 : m_StagingBufferLast = offsetCandidate + requiredSize;
430 0 : return offsetCandidate;
431 : }
432 : }
433 :
434 0 : uint32_t CRingCommandContext::GetFreeSpaceOffset(
435 : const uint32_t requiredSize, const uint32_t requiredAlignment) const
436 : {
437 0 : if (!m_StagingBuffer)
438 : return INVALID_OFFSET;
439 0 : const uint32_t candidateOffset =
440 0 : round_up(m_StagingBufferLast, requiredAlignment);
441 0 : const uint32_t candidateLast = candidateOffset + requiredSize;
442 0 : if (m_StagingBufferFirst <= m_StagingBufferLast)
443 : {
444 0 : if (candidateLast <= m_StagingBuffer->GetSize())
445 : return candidateOffset;
446 : // We intentionally use exclusive comparison to avoid distinguishing
447 : // completely full and completely empty staging buffers.
448 0 : else if (requiredSize < m_StagingBufferFirst)
449 : return 0; // We assume the first byte is always perfectly aligned.
450 : else
451 0 : return INVALID_OFFSET;
452 : }
453 : else
454 : {
455 0 : if (candidateLast < m_StagingBufferFirst)
456 : return candidateOffset;
457 : else
458 0 : return INVALID_OFFSET;
459 : }
460 : }
461 :
462 : } // namespace Vulkan
463 :
464 : } // namespace Backend
465 :
466 : } // namespace Renderer
|