/
vulkanobject.py
2566 lines (2089 loc) · 89.9 KB
/
vulkanobject.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''Vulkan objects modules
This module contains the *High* level Vulkan object. It's not that *high*
level, you need to understand fully Vulkan to use theses objects.
This module must be use by Vulkan expert and is very complicated to work with.
You will see a lot of namedtuple here, they are used to better document the
object arguments. Instead of passing a dict whith unknow keys, you pass a
documented namedtuple, I think it's better.
If you want to understand internal Vulkan functions, you can hack around this
module.
**Note: All classes, functions, tuples of this module are sorted
alphabetically.**
**Note: In this module, when it's needed, the parameter type is indicated. If
the type begins with Vk..., it means a real Vulkan object and not an
object in this module.**
'''
from collections import namedtuple
from contextlib import contextmanager
import logging
import pyshaderc
import vulkan as vk # pylint: disable=import-error
from vulk.exception import VulkError
from vulk import vulkanconstant as vc
from vulk.util import mipmap_size, next_multiple
logger = logging.getLogger()
# ----------
# FUNCTIONS
# ----------
def btov(b):
'''Convert boolean to Vulkan boolean'''
return vk.VK_TRUE if b else vk.VK_FALSE
def find_memory_type(context, type_filter, properties):
'''
Graphics cards can offer different types of memory to allocate from.
Each type of memory varies in terms of allowed operations and performance
characteristics. We need to combine the requirements of the memory and our
own application requirements to find the right type of memory to use.
*Parameters:*
- `context`: The `VulkContext`
- `type_filter`: Bit field of the memory types that are suitable
for the memory (int)
- `properties`: `MemoryProperty` Vulkan constant, type of
memory we want
**Todo: I made a bitwise comparaison with `type_filter`, I have to test
it to be sure it's working**
'''
cache_properties = vk.vkGetPhysicalDeviceMemoryProperties(
context.physical_device)
for i, memory_type in enumerate(cache_properties.memoryTypes):
# TODO: Test type_filter
if (type_filter & (1 << i)) and \
(memory_type.propertyFlags & properties) == properties:
return i
msg = "Can't find suitable memory type"
logger.critical(msg)
raise VulkError(msg)
@contextmanager
def immediate_buffer(context, commandpool=None):
'''
Manage creation and destruction of commandbuffer for one time submit.
If commandpool is not given, it is created here.
*Parameters:*
- `context`: `VulkContext`
- `commandpool`: `CommandPool` (optional)
'''
own_commandpool = False
if not commandpool:
commandpool = CommandPool(
context, context.queue_family_indices['graphic'],
vc.CommandPoolCreate.TRANSIENT)
own_commandpool = True
try:
commandbuffers = commandpool.allocate_buffers(
context, vc.CommandBufferLevel.PRIMARY, 1)
flags = vc.CommandBufferUsage.ONE_TIME_SUBMIT
with commandbuffers[0].bind(flags) as cmd:
yield cmd
finally:
submit = vk.VkSubmitInfo(
sType=vk.VK_STRUCTURE_TYPE_SUBMIT_INFO,
waitSemaphoreCount=0,
pWaitSemaphores=None,
pWaitDstStageMask=None,
commandBufferCount=1,
pCommandBuffers=[c.commandbuffer for c in commandbuffers],
signalSemaphoreCount=0,
pSignalSemaphores=None
)
vk.vkQueueSubmit(context.graphic_queue, 1, [submit], None)
vk.vkQueueWaitIdle(context.graphic_queue)
commandpool.free_buffers(context, commandbuffers)
if own_commandpool:
commandpool.destroy(context)
def submit_to_graphic_queue(context, submits):
'''
Convenient function to submit commands to graphic queue
*Parameters:*
- `context`: `VulkContext`
- `submits`: `list` of `SubmitInfo`
'''
submit_to_queue(context.graphic_queue, submits)
def submit_to_queue(queue, submits):
'''
Submit commands to queue
*Parameters:*
- `queue`: `VkQueue`
- `submits`: `list` of `SubmitInfo`
'''
vk_submits = []
for s in submits:
wait_stages = None
if s.wait_stages:
wait_stages = [st.value for st in s.wait_stages]
wait_semaphores = None
if s.wait_semaphores:
wait_semaphores = [sem.semaphore for sem in s.wait_semaphores]
signal_semaphores = None
if s.signal_semaphores:
signal_semaphores = [sem.semaphore for sem in s.signal_semaphores]
vk_submits.append(vk.VkSubmitInfo(
sType=vk.VK_STRUCTURE_TYPE_SUBMIT_INFO,
waitSemaphoreCount=len(s.wait_semaphores),
pWaitSemaphores=wait_semaphores,
pWaitDstStageMask=wait_stages,
commandBufferCount=len(s.commandbuffers),
pCommandBuffers=[c.commandbuffer for c in s.commandbuffers],
signalSemaphoreCount=len(s.signal_semaphores),
pSignalSemaphores=signal_semaphores
))
vk.vkQueueSubmit(queue, len(vk_submits), vk_submits, None)
def update_descriptorsets(context, writes, copies):
'''
Update the contents of a descriptor set object
*Parameters:*
- `context`: `VulkContext`
- `writes`: `list` of `WriteDescriptorSet`
- `copies`: `list` of `CopyDescriptorSet`
**Todo: `copies` is unusable currently**
**Todo: Only `DescriptorBufferInfo` supported**
'''
def get_type(t, descriptors):
result = {'pImageInfo': None, 'pBufferInfo': None,
'pTexelBufferView': None}
vk_descriptors = []
if t in (vk.VK_DESCRIPTOR_TYPE_SAMPLER,
vk.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
vk.VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
vk.VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
vk.VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT):
for d in descriptors:
vk_descriptors.append(vk.VkDescriptorImageInfo(
sampler=d.sampler.sampler,
imageView=d.view.imageview,
imageLayout=d.layout.value
))
result['pImageInfo'] = vk_descriptors
elif t in (vk.VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
vk.VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER):
result['pTexelBufferView'] = [d.view for d in descriptors]
elif t in (vk.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
vk.VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
vk.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
vk.VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC):
for d in descriptors:
vk_descriptors.append(vk.VkDescriptorBufferInfo(
buffer=d.buffer.buffer,
offset=d.offset,
range=d.range
))
result['pBufferInfo'] = vk_descriptors
return result
vk_writes = []
for w in writes:
vk_writes.append(vk.VkWriteDescriptorSet(
sType=vk.VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
dstSet=w.set.descriptorset,
dstBinding=w.binding,
dstArrayElement=w.set_offset,
descriptorCount=len(w.descriptors),
descriptorType=w.type.value,
**get_type(w.type.value, w.descriptors)
))
# TODO: copies must be implemented
vk.vkUpdateDescriptorSets(context.device, len(vk_writes),
vk_writes, len(copies), None)
# ----------
# NAMED TUPLES
# ----------
AttachmentDescription = namedtuple('AttachmentDescription',
['format', 'samples', 'load', 'store',
'stencil_load', 'stencil_store',
'initial_layout', 'final_layout'])
AttachmentDescription.__doc__ = '''
AttachmentDescription describes the attachment.
*Parameters:*
- `format`: `Format` vulk constant
- `samples`: `SampleCount` vulk constant
- `load`: `AttachmentLoadOp` vulk constant
- `store`: `AttachmentStoreOp` vulk constant
- `stencil_load`: `AttachmentLoadOp` vulk constant
- `stencil_store`: `AttachmentStoreOp` vulk constant
- `initial_layout`: `ImageLayout` vulk constant
- `final_layout`: `ImageLayout` vulk constant
'''
AttachmentReference = namedtuple('AttachmentReference', ['index', 'layout'])
AttachmentReference.__doc__ = '''
AttachmentReference links an attachment index with a layout.
*Parameters:*
- `index`: Index of attachment description
- `layout`: `ImageLayout` vulk constant
'''
DescriptorBufferInfo = namedtuple('DescriptorBufferInfo',
['buffer', 'offset', 'range'])
DescriptorBufferInfo.__doc__ = '''
Structure specifying descriptor buffer info
*Parameters:*
- `buffer`: `Buffer` ressource
- `offset`: Offset in bytes from the start of buffer
- `range`: Size in bytes that is used for this descriptor update
'''
DescriptorImageInfo = namedtuple('DescriptorImageInfo',
['sampler', 'view', 'layout'])
DescriptorImageInfo.__doc__ = '''
Structure specifying descriptor image info
*Parameters:*
- `sampler`: `Sampler` ressource
- `view`: `ImageView`
- `layout`: `ImageLayout` vulk constant
'''
DescriptorPoolSize = namedtuple('DescriptorPoolSize', ['type', 'count'])
DescriptorPoolSize.__doc__ = '''
Structure specifying descriptor pool size.
*Parameters:*
- `type`: `DescriptorType` vulk constant
- `count`: Number of descriptors of that type to allocate
'''
DescriptorSetLayoutBinding = namedtuple('DescriptorSetLayoutBinding',
['binding', 'type', 'count',
'stage', 'immutable_samplers'])
DescriptorSetLayoutBinding.__doc__ = '''
Structure specifying a descriptor set layout binding.
*Parameters:*
- `binding`: Binding number of this entry and corresponds to a resource
of the same binding number in the shader stages
- `type`: `DescriptorType` specifying which type of resource descriptors
are used for this binding
- `count`: Number of descriptors contained in the binding,
accessed in a shader as an array
- `stage`: `ShaderStage` vulk constant specifying which pipeline shader
stages can access a resource for this binding
- `immutable_samplers`: Immutable `Sampler` (can be `None`)
'''
Extent2D = namedtuple('Extent2D', ['width', 'height'])
Extent2D.__doc__ = '''
*Parameters:*
- `width`: Width
- `height`: Height
'''
Extent3D = namedtuple('Extent3D', ['width', 'height', 'depth'])
Extent3D.__doc__ = '''
*Parameters:*
- `width`: Width
- `height`: Height
- `depth`: Depth
'''
ImageSubresourceRange = namedtuple('ImageSubresourceRange',
['aspect', 'base_miplevel', 'level_count',
'base_layer', 'layer_count'])
ImageSubresourceRange.__doc__ = '''
`ImageSubresourceRange` object describes what the image's purpose is and
which part of the image should be accessed.
*Parameters:*
- `aspect`: `ImageAspect` vulk constant indicating which aspect(s) of the
image are included in the view
- `base_miplevel`: The first mipmap level accessible to the view
- `level_count`: Number of mipmap levels (starting from base_miplevel)
accessible to the view
- `base_layer`: First array layer accessible to the view
- `layer_count`: Number of array layers (starting from base_layer)
accessible to the view
'''
Offset2D = namedtuple('Offset2D', ['x', 'y'])
Offset2D.__doc__ = '''
*Parameters:*
- `x`: x offset
- `y`: y offset
'''
PipelineColorBlendAttachmentState = namedtuple(
'PipelineColorBlendAttachmentState',
['enable', 'src_color', 'dst_color', 'color_op',
'src_alpha', 'dst_alpha', 'alpha_op', 'color_mask']
)
PipelineColorBlendAttachmentState.__doc__ = '''
*Parameters:*
- `enable`: Enable blending
- `src_color`: `BlendFactor` vulk constant for source color
- `dst_color`: `BlendFactor` vulk constant for destination color
- `color_op`: `BlendOp` vulk constant Operation on color
- `src_alpha`: `BlendFactor` vulk constant for source alpha
- `dst_alpha`: `BlendFactor` vulk constant for destination alpha
- `alpha_op`: `BlendOp` vulk constant operation on alpha
- `color_mask`: `ColorComponent` vulk constant selecting which of the
R, G, B, and A components are enabled for writing
'''
PipelineColorBlendState = namedtuple('PipelineColorBlendState',
['op_enable', 'op', 'attachments',
'constants'])
PipelineColorBlendState.__doc__ = '''
*Parameters:*
- `op_enable`: Enable bitwise combination
- `op`: `LogicOp` vulk constant operation to perform
- `attachments`: List of blend attachments for each framebuffer
- `constants`: Constants depending on blend factor (`list` of 4 `float`)
'''
PipelineDepthStencilState = namedtuple(
'PipelineDepthStencilState',
['depth_test_enable', 'depth_write_enable', 'depth_bounds_test_enable',
'depth_compare', 'stencil_test_enable', 'front', 'back', 'min', 'max']
)
PipelineDepthStencilState.__doc__ = '''
*Parameters:*
- `depth_test_enable`: Enable depth test
- `depth_write_enable`: Enable depth write
- `depth_bounds_test_enable`: Enable bounds test
- `depth_compare`: `CompareOp` vulk constant condition to overwrite depth
- `stencil_test_enable`: Enable stencil test
- `front`: Control stencil parameter (`StencilOpState`)
- `back`: Control stencil parameter (`StencilOpState`)
- `min`: Define the min value in depth bound test (`float`)
- `max`: Define the max value in depth bound test (`float`)
'''
PipelineDynamicState = namedtuple('PipelineDynamicState', 'states')
PipelineDynamicState.__doc__ = '''
- `states`: List of `VkDynamicState`
'''
PipelineInputAssemblyState = namedtuple('PipelineInputAssemblyState',
'topology')
PipelineInputAssemblyState.__doc__ = '''
*Parameters:*
- `topology`: `PrimitiveTopology` vulk constant to use when drawing
'''
PipelineMultisampleState = namedtuple('PipelineMultisampleState',
['shading_enable', 'samples',
'min_sample_shading'])
PipelineMultisampleState.__doc__ = '''
*Parameters:*
- `shading_enable`: Enable multisampling (`boolean`)
- `samples`: Number of samples, `SampleCount` vulk constant
- `min_sample_shading`: Minimum of sample (`float`)
'''
PipelineRasterizationState = namedtuple(
'PipelineRasterizationState',
['depth_clamp_enable', 'polygon_mode', 'line_width', 'cull_mode',
'front_face', 'depth_bias_constant', 'depth_bias_clamp',
'depth_bias_slope']
)
PipelineRasterizationState.__doc__ = '''
*Parameters:*
- `depth_clamp_enable`: Whether to enable depth clamping (`boolean`)
- `polygon_mode`: Which `PolygonMode` vulk constant to use
- `line_width`: Width of line (`float`)
- `cull_mode`: The way of culling, `CullMode` vulk constant
- `front_face`: `FrontFace` vulk constant
- `depth_bias_constant`: Constant to add to depth (`float`)
- `depth_bias_clamp`: Max depth bias (`float`)
- `depth_bias_slope`: Factor to slope (`float`)
'''
PipelineShaderStage = namedtuple('PipelineShaderStage', ['module', 'stage'])
PipelineShaderStage.__doc__ = '''
*Parameters:*
- `module`: The `ShaderModule` to bind
- `stage`: `ShaderStage` vulk constant
'''
PipelineVertexInputState = namedtuple('PipelineVertexInputState',
['bindings', 'attributes'])
PipelineVertexInputState.__doc__ = '''
*Parameters:*
- `bindings`: List of `VertexInputBindingDescription`
- `attributes`: List of `VertexInputAttributeDescription`
**Note: `bindings` and `attributes` can be empty `list`**
'''
PipelineViewportState = namedtuple('PipelineViewportState',
['viewports', 'scissors'])
PipelineViewportState.__doc__ = '''
The PipelineViewportState object contains viewports and scissors.
*Parameters:*
- `viewports`: `list` of `Viewport`
- `scissors`: `list` of `Rect2D`
'''
Rect2D = namedtuple('Rect2d', ['offset', 'extent'])
Rect2D.__doc__ = '''
2D surface with offset.
*Parameters:*
- `offset`: `Offset2D` object
- `extent`: `Extent2D` object
'''
SubmitInfo = namedtuple('SubmitInfo', ['wait_semaphores', 'wait_stages',
'signal_semaphores', 'commandbuffers'])
SubmitInfo.__doc__ = '''
Submit information when submitting to queue
*Parameters:*
- `wait_semaphores`: `list` of `Semaphore` to wait on
- `wait_stages`: `list` of `PipelineStage` vulk constant at which each
corresponding semaphore wait will occur. Must be the
same size as `wait_semaphores`
- `signal_semaphores`: `list` of `Semaphore` to signal when commands
are finished
- `commandbuffers`: `list` of `CommandBuffer` to execute
'''
SubpassDependency = namedtuple('SubpassDependency',
['src_subpass', 'src_stage', 'src_access',
'dst_subpass', 'dst_stage', 'dst_access'])
SubpassDependency.__doc__ = '''
SubpassDependency describes all dependencies of the subpass.
*Parameters:*
- `src_subpass`: Source subpass `int` or `SUBPASS_EXTERNAL` vulk constant
- `src_stage`: Source stage `PipelineStage` vulk constant
- `src_access`: Source `Access` vulk constant
- `dst_subpass`: Destination subpass `int` or
`SUBPASS_EXTERNAL` vulk constant
- `dst_stage`: Destination stage `PipelineStage` vulk constant
- `dst_access`: Destination `Access` vulk constant
'''
SubpassDescription = namedtuple('SubpassDescription',
['colors', 'inputs', 'resolves',
'preserves', 'depth_stencil'])
SubpassDescription.__doc__ = '''
`SubpassDescription` describes all attachments in the subpass.
All parameters are of type `AttachmentReference`. If you don't want
an attachment, set it to an empty list.
*Parameters:*
- `colors`: `list` of colors attachments
- `inputs`: `list` of inputs attachments
- `resolves`: `list` of resolves attachments (must be the same
size as inputs)
- `preserves`: `list` of preserves attachments
- `depth_stencil`: `list` containing only one attachment
'''
VertexInputAttributeDescription = namedtuple('VertexInputAttributeDescription',
['location', 'binding', 'format',
'offset'])
VertexInputAttributeDescription.__doc__ = '''
Structure specifying vertex input attribute description
*Parameters:*
- `location`: Shader binding location number for this attribute (`int`)
- `binding`: Binding number which this attribute takes its data from
- `format`: `Format` vulk constant of the vertex attribute data
- `offset`: Byte offset of this attribute relative to the start of an
element in the vertex input binding (`int`)
'''
VertexInputBindingDescription = namedtuple('VertexInputBindingDescription',
['binding', 'stride', 'rate'])
VertexInputBindingDescription.__doc__ = '''
Structure specifying vertex input binding description
*Parameters:*
- `binding`: Binding number (`int`)
- `stride`: Distance in bytes between two consecutive elements within
the buffer (`int`)
- `rate`: `VertexInputRate` vulk constant
'''
Viewport = namedtuple('Viewport', ['x', 'y', 'width', 'height',
'min_depth', 'max_depth'])
Viewport.__doc__ = '''
Structure specifying a viewport
*Parameters:*
- `x`: X upper left corner
- `y`: Y upper left corner
- `width`: Viewport width
- `height`: Viewport height
- `min_depth`: Depth range for the viewport
- `max_depth`: Depth range for the viewport
**Note: `min_depth` and `max_depth` must be between 0.0 and 1.0**
'''
WriteDescriptorSet = namedtuple('WriteDescriptorSet',
['set', 'binding', 'set_offset',
'type', 'descriptors'])
WriteDescriptorSet.__doc__ = '''
Structure specifying the parameters of a descriptor set write operation
*Parameters:*
- `set`: Destination `DescriptorSet` set to update
- `binding`: Descriptor binding within that set
- `set_offset`: Offset to start with in the descriptor
- `type`: Type of descriptor `DescriptorType` vulk constant
- `descriptors`: `list` of `DescriptorBufferInfo` or `DescriptorImageInfo`
or `BufferView` depending on `type`
**Note: The descriptor type must correspond to the `type` parameter**
'''
# ----------
# CLASSES
# ----------
class Buffer():
"""`Buffer` wrap a `VkBuffer` and a `VkMemory`"""
def __init__(self, context, flags, size, usage, sharing_mode,
queue_families, memory_properties):
"""Create a new buffer
Creating a buffer is made of several steps:
- Create the buffer
- Allocate the memory
- Bind the memory to the buffer
Args:
context (VulkContext)
flags (BufferCreate): Set sparse properties
size(int): Buffer size in bytes
usage (BufferUsage): All usages available for this buffer
sharing_mode (SharingMode): Shared between queues
queue_families (list): List of queue families accessing this
buffer (ignored if sharingMode is not
`CONCURRENT` - can be [])
memory_properties (MemoryProperty): Type of memory for this buffer
"""
self.memory_properties = memory_properties.value
self.size = size
# Create VkBuffer
buffer_create = vk.VkBufferCreateInfo(
sType=vk.VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
flags=flags.value,
size=self.size,
usage=usage.value,
sharingMode=sharing_mode.value,
queueFamilyIndexCount=len(queue_families),
pQueueFamilyIndices=queue_families if queue_families else None
)
self.buffer = vk.vkCreateBuffer(context.device, buffer_create, None)
# Get memory requirements
requirements = vk.vkGetBufferMemoryRequirements(context.device,
self.buffer)
alloc_info = vk.VkMemoryAllocateInfo(
sType=vk.VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
allocationSize=requirements.size,
memoryTypeIndex=find_memory_type(
context,
requirements.memoryTypeBits,
self.memory_properties
)
)
# Create memory
self.memory = vk.vkAllocateMemory(context.device, alloc_info, None)
# Bind device memory to the buffer
vk.vkBindBufferMemory(context.device, self.buffer, self.memory, 0)
def copy_to(self, cmd, dst_buffer):
"""Copy this buffer to the destination buffer
Commands to copy are registered in the commandbuffer but it's up to
you to start and submit the command buffer to the execution queue.
Args:
cmd (CommandBufferRegister): used to register commands
dst_buffer (Buffer): Destination buffer
**Note: Buffers must have the same size**
"""
if self.size != dst_buffer.size:
msg = "Buffers must have the same size"
logger.error(msg)
raise VulkError(msg)
region = vk.VkBufferCopy(
srcOffset=0,
dstOffset=0,
size=self.size
)
cmd.copy_buffer(self, dst_buffer, [region])
def copy_to_image(self, cmd, dst_image, mip_infos):
"""Copy this buffer to the destination image
Commands to copy are registered in the commandbuffer but it's up to
you to start and submit the command buffer to the execution queue.
Args:
cmd (CommandBufferRegister): used to register commands
dst_image (Image): Destination image
mip_infos (list): List containing for each mipmap a dict like
{'offset':, 'size':, 'width':, 'height':}
**Note: Layout of destination image must be `TRANSFERT_DST_OPTIMAL`.
It's up to you.**
"""
regions = []
for mip_level, info in enumerate(mip_infos):
subresource = vk.VkImageSubresourceLayers(
aspectMask=vc.ImageAspect.COLOR,
baseArrayLayer=0,
mipLevel=mip_level,
layerCount=1
)
extent = vk.VkExtent3D(width=info['width'], height=info['height'],
depth=dst_image.depth)
offset = vk.VkOffset3D(x=0, y=0, z=0)
region = vk.VkBufferImageCopy(
bufferOffset=info['offset'],
bufferRowLength=0,
bufferImageHeight=0,
imageSubresource=subresource,
imageOffset=offset,
imageExtent=extent
)
regions.append(region)
dst_layout = vc.ImageLayout.TRANSFER_DST_OPTIMAL
cmd.copy_buffer_to_image(self, dst_image, dst_layout, regions)
@contextmanager
def bind(self, context, offset=0, size=0):
"""Map this buffer to upload data in it
This function is a context manager and must be called with `with`.
It return a python buffer and let you do what you want with it,
be careful!
Args:
context (VulkContext)
offset (int): Where to begin uploading in buffer
size (int): Max size to write into the buffer (0 = all)
**Warning: Buffer memory must be host visible**
"""
size = size or self.size
compatible_memories = {vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
vk.VK_MEMORY_PROPERTY_HOST_CACHED_BIT}
if not any([self.memory_properties & m for m in compatible_memories]):
msg = "Can't map this buffer, memory must be host visible"
logger.error(msg)
raise VulkError(msg)
try:
data = vk.vkMapMemory(context.device, self.memory, offset,
size, 0)
yield data
finally:
vk.vkUnmapMemory(context.device, self.memory)
class ClearColorValue():
'''ClearValue for color clearing'''
def __init__(self, float32=None, uint32=None, int32=None):
'''
Take only one value depending on the type you want.
`list` must be of size 4.
*Parameters:*
- `float32`: Type `float`
- `uint32`: Type `uint`
- `int32`: Type `int`
'''
t = (float32, uint32, int32)
# Set to list
for v in t:
v = [] if v is None else v
# Check that only one value is set
if sum(1 for i in t if i) != 1:
msg = "Only one value in [float32, uint32, int32] must be given"
logger.error(msg)
raise VulkError(msg)
# Check size of value (must be 4)
if len(next(iter([v for v in t if t]))) != 4:
msg = "Value must be a list of 4 elements"
logger.error(msg)
raise VulkError(msg)
if float32:
clear = vk.VkClearColorValue(float32=float32)
if uint32:
clear = vk.VkClearColorValue(uint32=uint32)
if int32:
clear = vk.VkClearColorValue(int32=int32)
self.clear = clear
class ClearDepthStencilValue():
'''ClearValue for depth and stencil clearing'''
def __init__(self, depth, stencil):
'''
*Parameters:*
- `depth`: Value in [0.0, 1.0]
- `stencil`; `int` value
'''
self.clear = vk.VkClearDepthStencilValue(depth=depth, stencil=stencil)
class CommandBuffer():
'''
Commands in Vulkan, like drawing operations and memory transfers, are not
executed directly using function calls. You have to record all of the
operations you want to perform in command buffer objects. The advantage of
this is that all of the hard work of setting up the drawing commands can
be done in advance and in multiple threads. After that, you just have to
tell Vulkan to execute the commands in the main loop.
Commands are executed directly from the `CommandBufferRegister` subclass.
The naming convention is simple:
`vkCmd[CommandName]` becomes `command_name`
'''
def __init__(self, commandbuffer):
'''
This object must be initialized with an existing `VkCommandBuffer`
because it is generated from `CommandPool`.
*Parameters:*
- `commandbuffer`: `VkCommandBuffer`
'''
self.commandbuffer = commandbuffer
def reset(self, flags=vc.CommandBufferReset.NONE):
'''
Reset the command buffer
*Parameters:*
- `flags`: `CommandBufferReset` vulk constant, default to 0
'''
vk.vkResetCommandBuffer(self.commandbuffer, flags)
@contextmanager
def bind(self, flags=vc.CommandBufferUsage.NONE):
'''
Bind this buffer to register command.
*Parameters:*
- `flags`: `CommandBufferUsage` vulk constant, default to 0
*Returns:*
`CommandBufferRegister` object
**Todo: `pInheritanceInfo` must be implemented**
'''
commandbuffer_begin_create = vk.VkCommandBufferBeginInfo(
sType=vk.VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
flags=flags.value,
pInheritanceInfo=None
)
try:
vk.vkBeginCommandBuffer(
self.commandbuffer,
commandbuffer_begin_create)
yield CommandBufferRegister(self.commandbuffer)
finally:
vk.vkEndCommandBuffer(self.commandbuffer)
class CommandBufferRegister():
'''
Allow to call command on command buffer.
`CommandBufferRegister` is not in charge of begin and end the command
buffer. You should not use it directly but with `bind` method of
`CommandBuffer`.
'''
def __init__(self, commandbuffer):
'''
*Parameters:*
- `commandbuffer`: The `VkCommandBuffer`
'''
self.commandbuffer = commandbuffer
def begin_renderpass(self, renderpass, framebuffer, renderarea,
clears, contents=vc.SubpassContents.INLINE):
'''
Begin a new renderpass
*Parameters:*
- `renderpass`: The `RenderPass` to begin an instance of
- `framebuffer`: The `Framebuffer` containing the attachments that
are used with the render pass
- `renderarea`: `Rect2D` size to render
- `clears`: `list` of `ClearValue` for each `Framebuffer`
- `contents`: `SubpassContents` vulk constant (default: `INLINE`)
'''
vk_renderarea = vk.VkRect2D(
offset=vk.VkOffset2D(
x=renderarea.offset.x,
y=renderarea.offset.y),
extent=vk.VkExtent2D(
width=renderarea.extent.width,
height=renderarea.extent.height)
)
vk_clearvalues = []
for c in clears:
if isinstance(c, ClearColorValue):
vk_clearvalues.append(vk.VkClearValue(color=c.clear))
elif isinstance(c, ClearDepthStencilValue):
vk_clearvalues.append(vk.VkClearValue(depthStencil=c.clear))
else:
msg = "Unknown clear value"
logger.error(msg)
raise VulkError(msg)
renderpass_begin = vk.VkRenderPassBeginInfo(
sType=vk.VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
renderPass=renderpass.renderpass,
framebuffer=framebuffer.framebuffer,
renderArea=vk_renderarea,
clearValueCount=len(vk_clearvalues),
pClearValues=vk_clearvalues
)
vk.vkCmdBeginRenderPass(self.commandbuffer, renderpass_begin,
contents)
def bind_descriptor_sets(self, layout, first, descriptors, offsets,
bind_point=vc.PipelineBindPoint.GRAPHICS):
'''
Binds descriptor sets to this `CommandBuffer`
*Parameters:*
- `layout`: `PipelineLayout`
- `first`: Number of the first descriptor set to be bound
- `descriptors`: `list` of `DescriptorSet`
- `offsets`: `list` of dynamic offsets
- `bind_point`: `PipelineBindPoint` vulk constant (default: GRAPHICS)
'''
vk_descriptors = [d.descriptorset for d in descriptors]
vk.vkCmdBindDescriptorSets(
self.commandbuffer, bind_point, layout.layout, first,
len(vk_descriptors), vk_descriptors, len(offsets),
offsets if offsets else None)
def bind_pipeline(self, pipeline,
bind_point=vc.PipelineBindPoint.GRAPHICS):
'''
Bind the pipeline to this `CommandBuffer`.
*Parameters:*
- `pipeline`: The `Pipeline` to bind