./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
287 / 339
84.7%
Branches:
74 / 150
49.3%
Functions:
30 / 34
88.2%

src/gpu/vulkan.cpp
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 #include "gpu/vulkan.h"
4
5 #include "terraingen/util/log.h"
6
7 #include <volk.h>
8
9 #include <algorithm>
10 #include <cstdlib>
11 #include <cstring>
12 #include <map>
13 #include <mutex>
14 #include <stdexcept>
15 #include <tuple>
16 #include <utility>
17
18 namespace terraingen {
19
20 namespace {
21
22 /// Throws std::runtime_error naming `what` and the result unless `result` is VK_SUCCESS.
23 3924 void Check(VkResult result, const char* what) {
24
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3924 times.
3924 if (result != VK_SUCCESS) {
25
0/3
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ Branch 7 not taken.
✗ throw std::runtime_error(std::string("Vulkan ") + what + " failed (" +
26
0/2
✗ Branch 3 not taken.
✗ Branch 6 not taken.
✗ std::to_string(static_cast<int>(result)) + ")");
27 }
28 3924 }
29
30 /// A pipeline for one kernel and buffer count.
31 struct Pipeline {
32 VkShaderModule module = VK_NULL_HANDLE;
33 VkDescriptorSetLayout setLayout = VK_NULL_HANDLE;
34 VkPipelineLayout layout = VK_NULL_HANDLE;
35 VkPipeline pipeline = VK_NULL_HANDLE;
36 };
37
38 /// Destroys what `p` holds; Vulkan ignores null handles, so a partly made pipeline is fine.
39 ✗ void DestroyPipeline(VkDevice device, const Pipeline& p) {
40 ✗ vkDestroyPipeline(device, p.pipeline, nullptr);
41 ✗ vkDestroyPipelineLayout(device, p.layout, nullptr);
42 ✗ vkDestroyDescriptorSetLayout(device, p.setLayout, nullptr);
43 ✗ vkDestroyShaderModule(device, p.module, nullptr);
44 }
45
46 35 VkShaderModule CreateShaderModule(VkDevice device, Span<const unsigned char> spirv) {
47 35 VkShaderModuleCreateInfo info{};
48 35 info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
49 35 info.codeSize = spirv.size();
50 35 info.pCode = reinterpret_cast<const std::uint32_t*>(spirv.data());
51 35 VkShaderModule module = VK_NULL_HANDLE;
52 35 Check(vkCreateShaderModule(device, &info, nullptr, &module), "shader module");
53 35 return module;
54 }
55
56 /// A layout of `bindings` storage buffers, bound in order.
57 35 VkDescriptorSetLayout CreateSetLayout(VkDevice device, std::size_t bindings) {
58 35 std::vector<VkDescriptorSetLayoutBinding> layoutBindings(bindings);
59
2/2
✓ Branch 0 taken 268 times.
✓ Branch 1 taken 35 times.
303 for (std::size_t i = 0; i < bindings; ++i) {
60 268 layoutBindings[i] = {static_cast<std::uint32_t>(i), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1,
61 VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
62 }
63 35 VkDescriptorSetLayoutCreateInfo info{};
64 35 info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
65 35 info.bindingCount = static_cast<std::uint32_t>(bindings);
66
1/1
✓ Branch 1 taken 35 times.
35 info.pBindings = layoutBindings.data();
67 35 VkDescriptorSetLayout layout = VK_NULL_HANDLE;
68
2/2
✓ Branch 1 taken 35 times.
✓ Branch 4 taken 35 times.
35 Check(vkCreateDescriptorSetLayout(device, &info, nullptr, &layout), "descriptor set layout");
69 35 return layout;
70 35 }
71
72 35 VkPipelineLayout CreatePipelineLayout(VkDevice device, VkDescriptorSetLayout setLayout,
73 std::size_t pushSize) {
74 35 const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0,
75
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 35 times.
35 static_cast<std::uint32_t>(std::max<std::size_t>(pushSize, 4))};
76 35 VkPipelineLayoutCreateInfo info{};
77 35 info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
78 35 info.setLayoutCount = 1;
79 35 info.pSetLayouts = &setLayout;
80
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 35 times.
35 info.pushConstantRangeCount = pushSize > 0 ? 1u : 0u;
81 35 info.pPushConstantRanges = &range;
82 35 VkPipelineLayout layout = VK_NULL_HANDLE;
83 35 Check(vkCreatePipelineLayout(device, &info, nullptr, &layout), "pipeline layout");
84 35 return layout;
85 }
86
87 /// The pipeline running `spirv` with `bindings` storage buffers and `pushSize` bytes of push
88 /// constants; nothing is left behind when a step fails.
89 35 Pipeline CreatePipeline(VkDevice device, Span<const unsigned char> spirv, std::size_t bindings,
90 std::size_t pushSize) {
91 35 Pipeline p;
92 35 try {
93
1/1
✓ Branch 1 taken 35 times.
35 p.module = CreateShaderModule(device, spirv);
94
1/1
✓ Branch 1 taken 35 times.
35 p.setLayout = CreateSetLayout(device, bindings);
95
1/1
✓ Branch 1 taken 35 times.
35 p.layout = CreatePipelineLayout(device, p.setLayout, pushSize);
96 35 VkComputePipelineCreateInfo info{};
97 35 info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
98 35 info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
99 35 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
100 35 info.stage.module = p.module;
101 35 info.stage.pName = "main";
102 35 info.layout = p.layout;
103
2/2
✓ Branch 1 taken 35 times.
✓ Branch 4 taken 35 times.
35 Check(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &info, nullptr, &p.pipeline),
104 "compute pipeline");
105 ✗ } catch (...) {
106
0/1
✗ Branch 1 not taken.
✗ DestroyPipeline(device, p);
107 ✗ throw;
108 }
109 35 return p;
110 }
111
112 /// A host-visible storage buffer.
113 750 struct Buffer {
114 VkBuffer buffer = VK_NULL_HANDLE;
115 VkDeviceMemory memory = VK_NULL_HANDLE;
116 void* mapped = nullptr;
117 };
118
119 /// The first memory type allowed by `bits` that has all of `flags`.
120 750 std::uint32_t MemoryType(const VkPhysicalDeviceMemoryProperties& memory, std::uint32_t bits,
121 VkMemoryPropertyFlags flags) {
122
1/2
✓ Branch 0 taken 750 times.
✗ Branch 1 not taken.
750 for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) {
123
2/4
✓ Branch 0 taken 750 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 750 times.
✗ Branch 3 not taken.
750 if ((bits & (1u << i)) != 0 && (memory.memoryTypes[i].propertyFlags & flags) == flags) {
124 750 return i;
125 }
126 }
127
0/1
✗ Branch 2 not taken.
✗ throw std::runtime_error("No host-visible, coherent Vulkan memory type");
128 }
129
130 /// The memory type for buffers the host writes and reads back: host-cached where the device has
131 /// one, since reading results back from uncached memory is many times slower, otherwise any
132 /// host-visible, coherent type.
133 750 std::uint32_t HostMemoryType(const VkPhysicalDeviceMemoryProperties& memory, std::uint32_t bits) {
134 750 constexpr VkMemoryPropertyFlags kHost =
135 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
136 750 try {
137
1/1
✓ Branch 1 taken 750 times.
750 return MemoryType(memory, bits, kHost | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
138
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ } catch (const std::runtime_error&) {
139
0/1
✗ Branch 1 not taken.
✗ return MemoryType(memory, bits, kHost);
140 }
141 }
142
143 /// Frees `buffer` and resets it, which may be partly created.
144 750 void FreeBuffer(VkDevice device, Buffer& buffer) {
145
1/2
✓ Branch 0 taken 750 times.
✗ Branch 1 not taken.
750 if (buffer.mapped != nullptr) {
146 750 vkUnmapMemory(device, buffer.memory);
147 }
148
1/2
✓ Branch 0 taken 750 times.
✗ Branch 1 not taken.
750 if (buffer.memory != VK_NULL_HANDLE) {
149 750 vkFreeMemory(device, buffer.memory, nullptr);
150 }
151
1/2
✓ Branch 0 taken 750 times.
✗ Branch 1 not taken.
750 if (buffer.buffer != VK_NULL_HANDLE) {
152 750 vkDestroyBuffer(device, buffer.buffer, nullptr);
153 }
154 750 buffer = {};
155 750 }
156
157 /// Creates a mapped, host-coherent storage buffer of `size` bytes into `buffer`, which the caller
158 /// frees even when this throws.
159 750 void MakeBuffer(VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, std::size_t size,
160 Buffer& buffer) {
161 750 VkBufferCreateInfo info{};
162 750 info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
163
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 750 times.
750 info.size = std::max<std::size_t>(size, 4);
164 750 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
165 750 info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
166 750 Check(vkCreateBuffer(device, &info, nullptr, &buffer.buffer), "buffer creation");
167 750 VkMemoryRequirements requirements;
168 750 vkGetBufferMemoryRequirements(device, buffer.buffer, &requirements);
169 750 VkMemoryAllocateInfo allocate{};
170 750 allocate.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
171 750 allocate.allocationSize = requirements.size;
172 750 allocate.memoryTypeIndex = HostMemoryType(memory, requirements.memoryTypeBits);
173 750 Check(vkAllocateMemory(device, &allocate, nullptr, &buffer.memory), "memory allocation");
174 750 Check(vkBindBufferMemory(device, buffer.buffer, buffer.memory, 0), "memory binding");
175 750 Check(vkMapMemory(device, buffer.memory, 0, VK_WHOLE_SIZE, 0, &buffer.mapped),
176 "memory mapping");
177 750 }
178
179 /// The kind of a device the driver reports as `type`.
180 ✗ DeviceKind ToDeviceKind(VkPhysicalDeviceType type) {
181
0/5
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ switch (type) {
182 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
183 return DeviceKind::Discrete;
184 ✗ case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
185 ✗ return DeviceKind::Integrated;
186 ✗ case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
187 ✗ return DeviceKind::Virtual;
188 ✗ case VK_PHYSICAL_DEVICE_TYPE_CPU:
189 ✗ return DeviceKind::Cpu;
190 ✗ default:
191 ✗ return DeviceKind::Other;
192 }
193 }
194
195 /// Opens the Vulkan loader and creates an instance with its functions loaded.
196 32 VkInstance CreateInstance() {
197
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 32 times.
32 if (volkInitialize() != VK_SUCCESS) {
198
0/3
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ Branch 8 not taken.
✗ throw std::runtime_error("no Vulkan loader found; " + VulkanInstallHint());
199 }
200 32 VkApplicationInfo app{};
201 32 app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
202 32 app.pApplicationName = "TerrainGen";
203 32 app.apiVersion = VK_API_VERSION_1_1;
204 32 VkInstanceCreateInfo instanceInfo{};
205 32 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
206 32 instanceInfo.pApplicationInfo = &app;
207 #ifdef __APPLE__
208 const char* portability = VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME;
209 instanceInfo.flags = VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
210 instanceInfo.enabledExtensionCount = 1;
211 instanceInfo.ppEnabledExtensionNames = &portability;
212 #endif
213 32 VkInstance instance = VK_NULL_HANDLE;
214 32 const VkResult created = vkCreateInstance(&instanceInfo, nullptr, &instance);
215
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32 times.
32 if (created == VK_ERROR_INCOMPATIBLE_DRIVER) {
216
0/3
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ Branch 8 not taken.
✗ throw std::runtime_error("no Vulkan driver found; " + VulkanInstallHint());
217 }
218 32 Check(created, "instance creation");
219 32 volkLoadInstance(instance);
220 32 return instance;
221 }
222
223 /// The device `TERRAINGEN_DEVICE` names, otherwise the one `PickDevice` picks.
224 32 VkPhysicalDevice ChooseDevice(VkInstance instance) {
225 32 std::uint32_t count = 0;
226 32 vkEnumeratePhysicalDevices(instance, &count, nullptr);
227 32 std::vector<VkPhysicalDevice> devices(count);
228
1/1
✓ Branch 1 taken 32 times.
32 vkEnumeratePhysicalDevices(instance, &count, devices.data());
229
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32 times.
32 if (devices.empty()) {
230
0/3
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ Branch 8 not taken.
✗ throw std::runtime_error("no Vulkan devices; " + VulkanInstallHint());
231 }
232
2/4
✓ Branch 1 taken 32 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 32 times.
✗ Branch 4 not taken.
32 if (const char* wanted = std::getenv("TERRAINGEN_DEVICE"); wanted && *wanted) {
233 32 const auto chosen = static_cast<std::size_t>(std::strtoul(wanted, nullptr, 10));
234
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32 times.
32 if (chosen >= devices.size()) {
235
0/3
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ Branch 7 not taken.
✗ throw std::runtime_error("TERRAINGEN_DEVICE " + std::string(wanted) + " is past the " +
236
0/2
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ std::to_string(devices.size()) + " Vulkan devices");
237 }
238 32 return devices[chosen];
239 }
240
0/1
✗ Branch 1 not taken.
✗ std::vector<DeviceKind> kinds(devices.size());
241 ✗ std::string names;
242
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (std::size_t i = 0; i < devices.size(); ++i) {
243 ✗ VkPhysicalDeviceProperties properties;
244
0/1
✗ Branch 1 not taken.
✗ vkGetPhysicalDeviceProperties(devices[i], &properties);
245
0/1
✗ Branch 1 not taken.
✗ kinds[i] = ToDeviceKind(properties.deviceType);
246
0/4
✗ Branch 1 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 6 not taken.
✗ names += (i == 0 ? "" : ", ") + std::string(properties.deviceName);
247 }
248
0/2
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ if (const std::optional<std::size_t> chosen = PickDevice(kinds)) {
249 ✗ return devices[*chosen];
250 }
251
0/1
✗ Branch 1 not taken.
✗ throw std::runtime_error("only software Vulkan (" + names +
252 "), which is slower than the CPU backend; set TERRAINGEN_DEVICE to "
253
0/1
✗ Branch 1 not taken.
✗ "its index to use it anyway, or " +
254
0/2
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ VulkanInstallHint());
255 32 }
256
257 /// The first queue family of `physical` that supports compute.
258 32 std::uint32_t ComputeQueueFamily(VkPhysicalDevice physical) {
259 32 std::uint32_t families = 0;
260 32 vkGetPhysicalDeviceQueueFamilyProperties(physical, &families, nullptr);
261 32 std::vector<VkQueueFamilyProperties> properties(families);
262
1/1
✓ Branch 1 taken 32 times.
32 vkGetPhysicalDeviceQueueFamilyProperties(physical, &families, properties.data());
263
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 for (std::uint32_t i = 0; i < families; ++i) {
264
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 if ((properties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) != 0) {
265 32 return i;
266 }
267 }
268
0/1
✗ Branch 2 not taken.
✗ throw std::runtime_error("the Vulkan device has no compute queue");
269 32 }
270
271 /// A logical device with one queue of `family`, with its functions loaded.
272 32 VkDevice CreateDevice(VkPhysicalDevice physical, std::uint32_t family) {
273 32 const float priority = 1.0f;
274 32 VkDeviceQueueCreateInfo queueInfo{};
275 32 queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
276 32 queueInfo.queueFamilyIndex = family;
277 32 queueInfo.queueCount = 1;
278 32 queueInfo.pQueuePriorities = &priority;
279 32 VkDeviceCreateInfo deviceInfo{};
280 32 deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
281 32 deviceInfo.queueCreateInfoCount = 1;
282 32 deviceInfo.pQueueCreateInfos = &queueInfo;
283 32 VkDevice device = VK_NULL_HANDLE;
284 32 Check(vkCreateDevice(physical, &deviceInfo, nullptr, &device), "device creation");
285 32 volkLoadDevice(device);
286 32 return device;
287 }
288
289 32 VkCommandPool CreateCommandPool(VkDevice device, std::uint32_t family) {
290 32 VkCommandPoolCreateInfo poolInfo{};
291 32 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
292 32 poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
293 32 poolInfo.queueFamilyIndex = family;
294 32 VkCommandPool pool = VK_NULL_HANDLE;
295 32 Check(vkCreateCommandPool(device, &poolInfo, nullptr, &pool), "command pool");
296 32 return pool;
297 }
298
299 /// The objects of one `Run`, released when it goes out of scope however the run ends.
300 struct RunResources {
301 VkDevice device;
302 VkCommandPool pool;
303 std::vector<Buffer> buffers;
304 VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
305 VkCommandBuffer command = VK_NULL_HANDLE;
306 VkFence fence = VK_NULL_HANDLE;
307
308 86 RunResources(VkDevice owner, VkCommandPool commandPool, std::size_t count)
309 172 : device(owner), pool(commandPool), buffers(count) {}
310 RunResources(const RunResources&) = delete;
311 RunResources& operator=(const RunResources&) = delete;
312
313 86 ~RunResources() {
314
1/2
✓ Branch 0 taken 86 times.
✗ Branch 1 not taken.
86 if (fence != VK_NULL_HANDLE) {
315 86 vkDestroyFence(device, fence, nullptr);
316 }
317
1/2
✓ Branch 0 taken 86 times.
✗ Branch 1 not taken.
86 if (command != VK_NULL_HANDLE) {
318 86 vkFreeCommandBuffers(device, pool, 1, &command);
319 }
320
1/2
✓ Branch 0 taken 86 times.
✗ Branch 1 not taken.
86 if (descriptorPool != VK_NULL_HANDLE) {
321 86 vkDestroyDescriptorPool(device, descriptorPool, nullptr);
322 }
323
2/2
✓ Branch 0 taken 750 times.
✓ Branch 1 taken 86 times.
836 for (Buffer& buffer : buffers) {
324 750 FreeBuffer(device, buffer);
325 }
326 86 }
327 };
328
329 /// Creates a device buffer for each host buffer and copies the host data into it.
330 86 void UploadBuffers(Span<const DeviceBuffer> host, const VkPhysicalDeviceMemoryProperties& memory,
331 RunResources& run) {
332
2/2
✓ Branch 0 taken 750 times.
✓ Branch 1 taken 86 times.
836 for (std::size_t i = 0; i < host.size(); ++i) {
333 750 MakeBuffer(run.device, memory, host[i].bytes.size(), run.buffers[i]);
334 750 std::memcpy(run.buffers[i].mapped, host[i].bytes.data(), host[i].bytes.size());
335 }
336 86 }
337
338 /// A descriptor set binding the run's buffers as storage buffers 0, 1, ...
339 86 VkDescriptorSet BindBuffers(const Pipeline& pipeline, RunResources& run) {
340 86 VkDescriptorPoolSize poolSize{
341 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
342
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 86 times.
86 static_cast<std::uint32_t>(std::max<std::size_t>(run.buffers.size(), 1))};
343 86 VkDescriptorPoolCreateInfo poolInfo{};
344 86 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
345 86 poolInfo.maxSets = 1;
346 86 poolInfo.poolSizeCount = 1;
347 86 poolInfo.pPoolSizes = &poolSize;
348 86 Check(vkCreateDescriptorPool(run.device, &poolInfo, nullptr, &run.descriptorPool),
349 "descriptor pool");
350 86 VkDescriptorSetAllocateInfo setInfo{};
351 86 setInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
352 86 setInfo.descriptorPool = run.descriptorPool;
353 86 setInfo.descriptorSetCount = 1;
354 86 setInfo.pSetLayouts = &pipeline.setLayout;
355 86 VkDescriptorSet set = VK_NULL_HANDLE;
356 86 Check(vkAllocateDescriptorSets(run.device, &setInfo, &set), "descriptor set");
357 86 std::vector<VkDescriptorBufferInfo> infos(run.buffers.size());
358
1/1
✓ Branch 1 taken 86 times.
86 std::vector<VkWriteDescriptorSet> writes(run.buffers.size());
359
2/2
✓ Branch 0 taken 750 times.
✓ Branch 1 taken 86 times.
836 for (std::size_t i = 0; i < run.buffers.size(); ++i) {
360 750 infos[i] = {run.buffers[i].buffer, 0, VK_WHOLE_SIZE};
361 750 writes[i] = {};
362 750 writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
363 750 writes[i].dstSet = set;
364 750 writes[i].dstBinding = static_cast<std::uint32_t>(i);
365 750 writes[i].descriptorCount = 1;
366 750 writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
367 750 writes[i].pBufferInfo = &infos[i];
368 }
369
1/1
✓ Branch 1 taken 86 times.
86 vkUpdateDescriptorSets(run.device, static_cast<std::uint32_t>(writes.size()), writes.data(), 0,
370 nullptr);
371 86 return set;
372 86 }
373
374 /// Records the dispatch, then a barrier making its writes visible to the host.
375 86 void RecordDispatch(const Pipeline& pipeline, VkDescriptorSet set,
376 Span<const std::byte> pushConstants, std::array<std::uint32_t, 3> groups,
377 RunResources& run) {
378 86 VkCommandBufferAllocateInfo commandInfo{};
379 86 commandInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
380 86 commandInfo.commandPool = run.pool;
381 86 commandInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
382 86 commandInfo.commandBufferCount = 1;
383 86 Check(vkAllocateCommandBuffers(run.device, &commandInfo, &run.command), "command buffer");
384 86 VkCommandBufferBeginInfo begin{};
385 86 begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
386 86 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
387 86 Check(vkBeginCommandBuffer(run.command, &begin), "command recording");
388 86 vkCmdBindPipeline(run.command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.pipeline);
389 86 vkCmdBindDescriptorSets(run.command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.layout, 0, 1,
390 &set, 0, nullptr);
391
1/2
✓ Branch 0 taken 86 times.
✗ Branch 1 not taken.
86 if (!pushConstants.empty()) {
392 86 vkCmdPushConstants(run.command, pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0,
393 86 static_cast<std::uint32_t>(pushConstants.size()), pushConstants.data());
394 }
395 86 vkCmdDispatch(run.command, groups[0], groups[1], groups[2]);
396 86 VkMemoryBarrier barrier{};
397 86 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
398 86 barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
399 86 barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
400 86 vkCmdPipelineBarrier(run.command, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
401 VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr);
402 86 Check(vkEndCommandBuffer(run.command), "command recording");
403 86 }
404
405 86 void SubmitAndWait(VkQueue queue, RunResources& run) {
406 86 VkFenceCreateInfo fenceInfo{};
407 86 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
408 86 Check(vkCreateFence(run.device, &fenceInfo, nullptr, &run.fence), "fence");
409 86 VkSubmitInfo submit{};
410 86 submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
411 86 submit.commandBufferCount = 1;
412 86 submit.pCommandBuffers = &run.command;
413 86 Check(vkQueueSubmit(queue, 1, &submit, run.fence), "submission");
414 86 Check(vkWaitForFences(run.device, 1, &run.fence, VK_TRUE, UINT64_MAX), "wait");
415 86 }
416
417 /// Copies the output buffers back to the host.
418 86 void DownloadOutputs(const RunResources& run, Span<const DeviceBuffer> host) {
419
2/2
✓ Branch 0 taken 750 times.
✓ Branch 1 taken 86 times.
836 for (std::size_t i = 0; i < host.size(); ++i) {
420
2/2
✓ Branch 1 taken 86 times.
✓ Branch 2 taken 664 times.
750 if (host[i].output != nullptr) {
421 86 std::memcpy(host[i].output, run.buffers[i].mapped, host[i].bytes.size());
422 }
423 }
424 86 }
425
426 } // namespace
427
428 /// The instance, device and cached pipelines; destroys whatever was created, so a partly opened
429 /// device is released as a fully opened one is.
430 struct VulkanCompute::State {
431 VkInstance instance = VK_NULL_HANDLE;
432 VkPhysicalDevice physical = VK_NULL_HANDLE;
433 VkDevice device = VK_NULL_HANDLE;
434 VkQueue queue = VK_NULL_HANDLE;
435 std::uint32_t family = 0;
436 VkCommandPool pool = VK_NULL_HANDLE;
437 VkPhysicalDeviceMemoryProperties memory{};
438 std::uint32_t maxPushConstants = 0;
439 std::string name;
440 std::mutex mutex;
441 /// Pipelines keyed by kernel code, binding count and push-constant size, which all shape the
442 /// pipeline layout.
443 std::map<std::tuple<const unsigned char*, std::size_t, std::size_t>, Pipeline> pipelines;
444
445 32 State() = default;
446 State(const State&) = delete;
447 State& operator=(const State&) = delete;
448
449 ✗ ~State() {
450
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (device != VK_NULL_HANDLE) {
451 ✗ vkDeviceWaitIdle(device);
452
0/2
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ for (const auto& [key, p] : pipelines) {
453 ✗ DestroyPipeline(device, p);
454 }
455
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (pool != VK_NULL_HANDLE) {
456 ✗ vkDestroyCommandPool(device, pool, nullptr);
457 }
458 ✗ vkDestroyDevice(device, nullptr);
459 }
460
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (instance != VK_NULL_HANDLE) {
461 ✗ vkDestroyInstance(instance, nullptr);
462 }
463 }
464
465 /// Opens the device: instance, physical device, queue, logical device and command pool.
466 32 void Open() {
467 32 instance = CreateInstance();
468 32 physical = ChooseDevice(instance);
469 32 VkPhysicalDeviceProperties properties;
470 32 vkGetPhysicalDeviceProperties(physical, &properties);
471 32 name = properties.deviceName;
472 32 maxPushConstants = properties.limits.maxPushConstantsSize;
473 32 vkGetPhysicalDeviceMemoryProperties(physical, &memory);
474 32 family = ComputeQueueFamily(physical);
475 32 device = CreateDevice(physical, family);
476 32 vkGetDeviceQueue(device, family, 0, &queue);
477 32 pool = CreateCommandPool(device, family);
478 32 }
479
480 /// The pipeline of `spirv` with `bindings` buffers and `pushSize` bytes of push constants,
481 /// created on first use.
482 86 const Pipeline& CachedPipeline(Span<const unsigned char> spirv, std::size_t bindings,
483 std::size_t pushSize) {
484 86 const auto key = std::make_tuple(spirv.data(), bindings, pushSize);
485 86 auto found = pipelines.find(key);
486
2/2
✓ Branch 0 taken 51 times.
✓ Branch 1 taken 35 times.
86 if (found != pipelines.end()) {
487 51 return found->second;
488 }
489
2/2
✓ Branch 1 taken 35 times.
✓ Branch 4 taken 35 times.
35 return pipelines.emplace(key, CreatePipeline(device, spirv, bindings, pushSize))
490 35 .first->second;
491 }
492 };
493
494 6 std::optional<std::size_t> PickDevice(Span<const DeviceKind> kinds) {
495 14 for (const DeviceKind kind :
496
2/2
✓ Branch 0 taken 18 times.
✓ Branch 1 taken 2 times.
20 {DeviceKind::Discrete, DeviceKind::Integrated, DeviceKind::Virtual, DeviceKind::Other}) {
497
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 14 times.
18 const auto found = std::find(kinds.begin(), kinds.end(), kind);
498
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 14 times.
18 if (found != kinds.end()) {
499 4 return static_cast<std::size_t>(found - kinds.begin());
500 }
501 }
502 2 return std::nullopt;
503 }
504
505 1 std::string VulkanInstallHint() {
506 #if defined(__APPLE__)
507 return "install MoltenVK (brew install molten-vk) or the Vulkan SDK from vulkan.lunarg.com";
508 #elif defined(_WIN32)
509 return "install or update the GPU driver, which provides the Vulkan loader (vulkan-1.dll)";
510 #else
511 1 return "install the Vulkan loader and a GPU driver (on Debian and Ubuntu: sudo apt install "
512 "libvulkan1, with the NVIDIA driver or mesa-vulkan-drivers); in Docker on an NVIDIA "
513 1 "GPU, include graphics in NVIDIA_DRIVER_CAPABILITIES";
514 #endif
515 }
516
517 32 VulkanCompute::VulkanCompute(std::unique_ptr<State> state) : m_state(std::move(state)) {}
518
519 ✗ VulkanCompute::~VulkanCompute() = default;
520
521 32 std::unique_ptr<VulkanCompute> VulkanCompute::Open() {
522 32 auto state = std::make_unique<State>();
523
1/1
✓ Branch 1 taken 32 times.
32 state->Open();
524
1/1
✓ Branch 1 taken 32 times.
64 return std::unique_ptr<VulkanCompute>(new VulkanCompute(std::move(state)));
525 32 }
526
527 104 const std::string& VulkanCompute::DeviceName() const {
528 104 return m_state->name;
529 }
530
531 169 bool VulkanCompute::CanRun(const KernelProgram& program) const {
532 169 return !program.spirv.empty();
533 }
534
535 88 void VulkanCompute::Run(const KernelProgram& program, Span<const DeviceBuffer> buffers,
536 Span<const std::byte> pushConstants, const Dispatch& dispatch) {
537
2/2
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 87 times.
88 State& s = *m_state;
538
2/2
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 87 times.
88 if (!CanRun(program)) {
539
1/1
✓ Branch 2 taken 1 time.
1 throw std::runtime_error("The kernel has no SPIR-V for Vulkan");
540 }
541
2/2
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 86 times.
87 if (pushConstants.size() > s.maxPushConstants) {
542
1/1
✓ Branch 2 taken 1 time.
1 throw std::runtime_error("Push constants exceed the device's limit");
543 }
544 86 const std::lock_guard lock(s.mutex);
545 86 const Pipeline& pipeline =
546
1/1
✓ Branch 1 taken 86 times.
86 s.CachedPipeline(program.spirv, buffers.size(), pushConstants.size());
547
1/1
✓ Branch 1 taken 86 times.
86 RunResources run(s.device, s.pool, buffers.size());
548
1/1
✓ Branch 1 taken 86 times.
86 UploadBuffers(buffers, s.memory, run);
549
1/1
✓ Branch 1 taken 86 times.
86 const VkDescriptorSet set = BindBuffers(pipeline, run);
550
1/1
✓ Branch 1 taken 86 times.
86 RecordDispatch(pipeline, set, pushConstants, dispatch.groups, run);
551
1/1
✓ Branch 1 taken 86 times.
86 SubmitAndWait(s.queue, run);
552 86 DownloadOutputs(run, buffers);
553 86 }
554
555 } // namespace terraingen
556