1 /*
2 * Copyright © 2017 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23 #ifndef VK_UTIL_H
24 #define VK_UTIL_H
25
26 /* common inlines and macros for vulkan drivers */
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <vulkan/vulkan.h>
31
32 #include <functional>
33 #include <optional>
34
35 #include "common/vk_struct_id.h"
36
37 struct vk_struct_common {
38 VkStructureType sType;
39 struct vk_struct_common *pNext;
40 };
41
42 struct vk_struct_chain_iterator {
43 vk_struct_common *value;
44 };
45
46 #define vk_foreach_struct(__iter, __start) \
47 for (struct vk_struct_common *__iter = \
48 (struct vk_struct_common *)(__start); \
49 __iter; __iter = __iter->pNext)
50
51 #define vk_foreach_struct_const(__iter, __start) \
52 for (const struct vk_struct_common *__iter = \
53 (const struct vk_struct_common *)(__start); \
54 __iter; __iter = __iter->pNext)
55
56 /**
57 * A wrapper for a Vulkan output array. A Vulkan output array is one that
58 * follows the convention of the parameters to
59 * vkGetPhysicalDeviceQueueFamilyProperties().
60 *
61 * Example Usage:
62 *
63 * VkResult
64 * vkGetPhysicalDeviceQueueFamilyProperties(
65 * VkPhysicalDevice physicalDevice,
66 * uint32_t* pQueueFamilyPropertyCount,
67 * VkQueueFamilyProperties* pQueueFamilyProperties)
68 * {
69 * VK_OUTARRAY_MAKE(props, pQueueFamilyProperties,
70 * pQueueFamilyPropertyCount);
71 *
72 * vk_outarray_append(&props, p) {
73 * p->queueFlags = ...;
74 * p->queueCount = ...;
75 * }
76 *
77 * vk_outarray_append(&props, p) {
78 * p->queueFlags = ...;
79 * p->queueCount = ...;
80 * }
81 *
82 * return vk_outarray_status(&props);
83 * }
84 */
85 struct __vk_outarray {
86 /** May be null. */
87 void *data;
88
89 /**
90 * Capacity, in number of elements. Capacity is unlimited (UINT32_MAX) if
91 * data is null.
92 */
93 uint32_t cap;
94
95 /**
96 * Count of elements successfully written to the array. Every write is
97 * considered successful if data is null.
98 */
99 uint32_t *filled_len;
100
101 /**
102 * Count of elements that would have been written to the array if its
103 * capacity were sufficient. Vulkan functions often return VK_INCOMPLETE
104 * when `*filled_len < wanted_len`.
105 */
106 uint32_t wanted_len;
107 };
108
__vk_outarray_init(struct __vk_outarray * a,void * data,uint32_t * len)109 static inline void __vk_outarray_init(struct __vk_outarray *a, void *data,
110 uint32_t *len) {
111 a->data = data;
112 a->cap = *len;
113 a->filled_len = len;
114 *a->filled_len = 0;
115 a->wanted_len = 0;
116
117 if (a->data == NULL) a->cap = UINT32_MAX;
118 }
119
__vk_outarray_status(const struct __vk_outarray * a)120 static inline VkResult __vk_outarray_status(const struct __vk_outarray *a) {
121 if (*a->filled_len < a->wanted_len)
122 return VK_INCOMPLETE;
123 else
124 return VK_SUCCESS;
125 }
126
__vk_outarray_next(struct __vk_outarray * a,size_t elem_size)127 static inline void *__vk_outarray_next(struct __vk_outarray *a,
128 size_t elem_size) {
129 void *p = NULL;
130
131 a->wanted_len += 1;
132
133 if (*a->filled_len >= a->cap) return NULL;
134
135 if (a->data != NULL)
136 p = ((uint8_t *)a->data) + (*a->filled_len) * elem_size;
137
138 *a->filled_len += 1;
139
140 return p;
141 }
142
143 #define vk_outarray(elem_t) \
144 struct { \
145 struct __vk_outarray base; \
146 elem_t meta[]; \
147 }
148
149 #define vk_outarray_typeof_elem(a) __typeof__((a)->meta[0])
150 #define vk_outarray_sizeof_elem(a) sizeof((a)->meta[0])
151
152 #define vk_outarray_init(a, data, len) \
153 __vk_outarray_init(&(a)->base, (data), (len))
154
155 #define VK_OUTARRAY_MAKE(name, data, len) \
156 vk_outarray(__typeof__((data)[0])) name; \
157 vk_outarray_init(&name, (data), (len))
158
159 #define vk_outarray_status(a) __vk_outarray_status(&(a)->base)
160
161 #define vk_outarray_next(a) \
162 ((vk_outarray_typeof_elem(a) *)__vk_outarray_next( \
163 &(a)->base, vk_outarray_sizeof_elem(a)))
164
165 /**
166 * Append to a Vulkan output array.
167 *
168 * This is a block-based macro. For example:
169 *
170 * vk_outarray_append(&a, elem) {
171 * elem->foo = ...;
172 * elem->bar = ...;
173 * }
174 *
175 * The array `a` has type `vk_outarray(elem_t) *`. It is usually declared with
176 * VK_OUTARRAY_MAKE(). The variable `elem` is block-scoped and has type
177 * `elem_t *`.
178 *
179 * The macro unconditionally increments the array's `wanted_len`. If the array
180 * is not full, then the macro also increment its `filled_len` and then
181 * executes the block. When the block is executed, `elem` is non-null and
182 * points to the newly appended element.
183 */
184 #define vk_outarray_append(a, elem) \
185 for (vk_outarray_typeof_elem(a) *elem = vk_outarray_next(a); elem != NULL; \
186 elem = NULL)
187
__vk_find_struct(void * start,VkStructureType sType)188 static inline void *__vk_find_struct(void *start, VkStructureType sType) {
189 vk_foreach_struct(s, start) {
190 if (s->sType == sType) return s;
191 }
192
193 return NULL;
194 }
195
196 template <class T, class H>
vk_find_struct(H * head)197 T *vk_find_struct(H *head) {
198 (void)vk_get_vk_struct_id<H>::id;
199 return static_cast<T *>(__vk_find_struct(static_cast<void *>(head),
200 vk_get_vk_struct_id<T>::id));
201 }
202
203 template <class T, class H>
vk_find_struct(const H * head)204 const T *vk_find_struct(const H *head) {
205 (void)vk_get_vk_struct_id<H>::id;
206 return static_cast<const T *>(
207 __vk_find_struct(const_cast<void *>(static_cast<const void *>(head)),
208 vk_get_vk_struct_id<T>::id));
209 }
210
211 uint32_t vk_get_driver_version(void);
212
213 uint32_t vk_get_version_override(void);
214
215 #define VK_EXT_OFFSET (1000000000UL)
216 #define VK_ENUM_EXTENSION(__enum) \
217 ((__enum) >= VK_EXT_OFFSET ? ((((__enum)-VK_EXT_OFFSET) / 1000UL) + 1) : 0)
218 #define VK_ENUM_OFFSET(__enum) \
219 ((__enum) >= VK_EXT_OFFSET ? ((__enum) % 1000) : (__enum))
220
221 template <class T>
vk_make_orphan_copy(const T & vk_struct)222 T vk_make_orphan_copy(const T &vk_struct) {
223 T copy = vk_struct;
224 copy.pNext = NULL;
225 return copy;
226 }
227
228 template <class T>
vk_make_chain_iterator(T * vk_struct)229 vk_struct_chain_iterator vk_make_chain_iterator(T *vk_struct) {
230 vk_get_vk_struct_id<T>::id;
231 vk_struct_chain_iterator result = {
232 reinterpret_cast<vk_struct_common *>(vk_struct)};
233 return result;
234 }
235
236 template <class T>
vk_append_struct(vk_struct_chain_iterator * i,T * vk_struct)237 void vk_append_struct(vk_struct_chain_iterator *i, T *vk_struct) {
238 vk_get_vk_struct_id<T>::id;
239
240 vk_struct_common *p = i->value;
241 if (p->pNext) {
242 ::abort();
243 }
244
245 p->pNext = reinterpret_cast<vk_struct_common *>(vk_struct);
246 vk_struct->pNext = NULL;
247
248 *i = vk_make_chain_iterator(vk_struct);
249 }
250
251 #define VK_CHECK(x) \
252 do { \
253 VkResult err = x; \
254 if (err != VK_SUCCESS) { \
255 ::fprintf(stderr, "%s(%u) %s: %s failed, error code = %d\n", \
256 __FILE__, __LINE__, __FUNCTION__, #x, err); \
257 ::abort(); \
258 } \
259 } while (0)
260
261 namespace vk_util {
262 class CRTPBase {};
263
264 template <class T, class U = CRTPBase>
265 class FindMemoryType : public U {
266 protected:
findMemoryType(uint32_t typeFilter,VkMemoryPropertyFlags properties)267 std::optional<uint32_t> findMemoryType(
268 uint32_t typeFilter, VkMemoryPropertyFlags properties) const {
269 const T &self = static_cast<const T &>(*this);
270 VkPhysicalDeviceMemoryProperties memProperties;
271 self.m_vk.vkGetPhysicalDeviceMemoryProperties(self.m_vkPhysicalDevice,
272 &memProperties);
273
274 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
275 if ((typeFilter & (1 << i)) &&
276 (memProperties.memoryTypes[i].propertyFlags & properties) ==
277 properties) {
278 return i;
279 }
280 }
281 return std::nullopt;
282 }
283 };
284
285 template <class T, class U = CRTPBase>
286 class RunSingleTimeCommand : public U {
287 protected:
runSingleTimeCommands(VkQueue queue,std::function<void (const VkCommandBuffer & commandBuffer)> f)288 void runSingleTimeCommands(
289 VkQueue queue,
290 std::function<void(const VkCommandBuffer &commandBuffer)> f) const {
291 const T &self = static_cast<const T &>(*this);
292 VkCommandBuffer cmdBuff;
293 VkCommandBufferAllocateInfo cmdBuffAllocInfo = {
294 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
295 .commandPool = self.m_vkCommandPool,
296 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
297 .commandBufferCount = 1};
298 VK_CHECK(self.m_vk.vkAllocateCommandBuffers(
299 self.m_vkDevice, &cmdBuffAllocInfo, &cmdBuff));
300 VkCommandBufferBeginInfo beginInfo = {
301 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
302 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
303 VK_CHECK(self.m_vk.vkBeginCommandBuffer(cmdBuff, &beginInfo));
304 f(cmdBuff);
305 VK_CHECK(self.m_vk.vkEndCommandBuffer(cmdBuff));
306 VkSubmitInfo submitInfo = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
307 .commandBufferCount = 1,
308 .pCommandBuffers = &cmdBuff};
309 VK_CHECK(
310 self.m_vk.vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
311 VK_CHECK(self.m_vk.vkQueueWaitIdle(queue));
312 self.m_vk.vkFreeCommandBuffers(self.m_vkDevice, self.m_vkCommandPool, 1,
313 &cmdBuff);
314 }
315 };
316 template <class T, class U = CRTPBase>
317 class RecordImageLayoutTransformCommands : public U {
318 protected:
recordImageLayoutTransformCommands(VkCommandBuffer cmdBuff,VkImage image,VkImageLayout oldLayout,VkImageLayout newLayout)319 void recordImageLayoutTransformCommands(VkCommandBuffer cmdBuff,
320 VkImage image,
321 VkImageLayout oldLayout,
322 VkImageLayout newLayout) const {
323 const T &self = static_cast<const T &>(*this);
324 VkImageMemoryBarrier imageBarrier = {
325 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
326 .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
327 .dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
328 .oldLayout = oldLayout,
329 .newLayout = newLayout,
330 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
331 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
332 .image = image,
333 .subresourceRange{.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
334 .baseMipLevel = 0,
335 .levelCount = 1,
336 .baseArrayLayer = 0,
337 .layerCount = 1}};
338 self.m_vk.vkCmdPipelineBarrier(cmdBuff,
339 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
340 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0,
341 nullptr, 0, nullptr, 1, &imageBarrier);
342 }
343 };
344 } // namespace vk_util
345
346 #endif /* VK_UTIL_H */
347