This repository has been archived by the owner on Aug 5, 2022. It is now read-only.
/
sample_info.go
1284 lines (1106 loc) · 35.1 KB
/
sample_info.go
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
package utils
import (
"bytes"
"encoding/binary"
"github.com/CannibalVox/VKng/core"
"github.com/CannibalVox/VKng/core/common"
"github.com/CannibalVox/VKng/core/core1_0"
"github.com/CannibalVox/VKng/extensions/khr_surface"
"github.com/CannibalVox/VKng/extensions/khr_swapchain"
"github.com/CannibalVox/VKng/extensions/vkng_surface_sdl2"
"github.com/cockroachdb/errors"
"github.com/go-gl/mathgl/mgl32"
"github.com/veandco/go-sdl2/sdl"
"log"
"unsafe"
)
type LayerProperties struct {
Properties *core1_0.LayerProperties
InstanceExtensions []*core1_0.ExtensionProperties
DeviceExtensions []*core1_0.ExtensionProperties
}
type SwapchainBuffer struct {
Image core1_0.Image
View core1_0.ImageView
}
type SampleInfo struct {
Loader core.Loader
Window *sdl.Window
Surface khr_surface.Surface
Prepared bool
UseStagingBuffer bool
SaveImages bool
InstanceLayerNames []string
InstanceExtensionNames []string
InstanceLayerProperties []*LayerProperties
InstanceExtensionProperties []*core1_0.ExtensionProperties
Instance core1_0.Instance
DeviceExtensionNames []string
DeviceExtensionProperties []*core1_0.ExtensionProperties
Gpus []core1_0.PhysicalDevice
Device core1_0.Device
GraphicsQueue core1_0.Queue
PresentQueue core1_0.Queue
GraphicsQueueFamilyIndex int
PresentQueueFamilyIndex int
GpuProps *core1_0.PhysicalDeviceProperties
QueueProps []*core1_0.QueueFamily
MemoryProperties *core1_0.PhysicalDeviceMemoryProperties
Framebuffer []core1_0.Framebuffer
Width, Height int
Format core1_0.Format
SwapchainImageCount int
SwapchainExtension khr_swapchain.Extension
Swapchain khr_swapchain.Swapchain
Buffers []SwapchainBuffer
ImageAcquiredSemaphore core1_0.Semaphore
CmdPool core1_0.CommandPool
Depth struct {
Format core1_0.Format
Image core1_0.Image
Mem core1_0.DeviceMemory
View core1_0.ImageView
}
Textures []*TextureObject
UniformData struct {
Buf core1_0.Buffer
Mem core1_0.DeviceMemory
BufferInfo core1_0.DescriptorBufferInfo
}
TextureData struct {
ImageInfo core1_0.DescriptorImageInfo
}
VertexBuffer struct {
Buf core1_0.Buffer
Mem core1_0.DeviceMemory
BufferInfo core1_0.DescriptorBufferInfo
}
VertexBinding core1_0.VertexInputBindingDescription
VertexAttributes []core1_0.VertexInputAttributeDescription
Projection mgl32.Mat4
View mgl32.Mat4
Model mgl32.Mat4
Clip mgl32.Mat4
MVP mgl32.Mat4
Cmd core1_0.CommandBuffer // BUffer for initialization commands
PipelineLayout core1_0.PipelineLayout
DescLayout []core1_0.DescriptorSetLayout
PipelineCache core1_0.PipelineCache
RenderPass core1_0.RenderPass
Pipeline core1_0.Pipeline
ShaderStages []core1_0.PipelineShaderStageCreateInfo
DescPool core1_0.DescriptorPool
DescSet []core1_0.DescriptorSet
//PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;
//PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;
//PFN_vkDebugReportMessageEXT dbgBreakCallback;
//std::vector<VkDebugReportCallbackEXT> debug_report_callbacks;
CurrentBuffer int
QueueFamilyCount int
Viewport core1_0.Viewport
Scissor core1_0.Rect2D
}
func (i *SampleInfo) InitWindowSize(defaultWidth, defaultHeight int) error {
i.Width = defaultWidth
i.Height = defaultHeight
return nil
}
func (i *SampleInfo) InitWindow() error {
if err := sdl.Init(sdl.INIT_VIDEO); err != nil {
return err
}
window, err := sdl.CreateWindow("Sample", 100, 100, int32(i.Width), int32(i.Height), sdl.WINDOW_SHOWN|sdl.WINDOW_VULKAN|sdl.WINDOW_RESIZABLE)
if err != nil {
return err
}
i.Window = window
return nil
}
func (i *SampleInfo) InitGlobalLayerProperties() error {
layers, _, err := i.Loader.AvailableLayers()
if err != nil {
return err
}
for _, properties := range layers {
props := &LayerProperties{
Properties: properties,
}
err = i.InitGlobalExtensionProperties(props)
if err != nil {
return err
}
i.InstanceLayerProperties = append(i.InstanceLayerProperties, props)
}
return nil
}
func (i *SampleInfo) InitGlobalExtensionProperties(layerProps *LayerProperties) error {
instanceExtensions, _, err := i.Loader.AvailableExtensionsForLayer(layerProps.Properties.LayerName)
if err != nil {
return err
}
for _, props := range instanceExtensions {
layerProps.InstanceExtensions = append(layerProps.InstanceExtensions, props)
}
return nil
}
func (i *SampleInfo) InitInstanceExtensionNames() error {
i.InstanceExtensionNames = i.Window.VulkanGetInstanceExtensions()
return nil
}
func (i *SampleInfo) InitInstance(appShortName string, next common.Options) error {
var err error
i.Instance, _, err = i.Loader.CreateInstance(nil, core1_0.InstanceCreateInfo{
ApplicationName: appShortName,
ApplicationVersion: common.CreateVersion(0, 0, 1),
EngineName: appShortName,
EngineVersion: common.CreateVersion(0, 0, 1),
APIVersion: common.Vulkan1_0,
EnabledExtensionNames: i.InstanceExtensionNames,
EnabledLayerNames: i.InstanceLayerNames,
NextOptions: common.NextOptions{
Next: next,
},
})
return err
}
func (i *SampleInfo) InitDeviceExtensionNames() error {
i.DeviceExtensionNames = []string{khr_swapchain.ExtensionName}
return nil
}
func (i *SampleInfo) InitEnumerateDevice() error {
var err error
i.Gpus, _, err = i.Instance.EnumeratePhysicalDevices()
if err != nil {
return err
}
i.QueueProps = i.Gpus[0].QueueFamilyProperties()
i.QueueFamilyCount = len(i.QueueProps)
i.MemoryProperties = i.Gpus[0].MemoryProperties()
i.GpuProps, err = i.Gpus[0].Properties()
if err != nil {
return err
}
for _, layerProps := range i.InstanceLayerProperties {
err = i.InitDeviceExtensionProperties(layerProps)
if err != nil {
return err
}
}
return nil
}
func (i *SampleInfo) InitDeviceExtensionProperties(layerProps *LayerProperties) error {
deviceExtensions, _, err := i.Gpus[0].EnumerateDeviceExtensionPropertiesForLayer(layerProps.Properties.LayerName)
if err != nil {
return err
}
for _, deviceExtension := range deviceExtensions {
layerProps.DeviceExtensions = append(layerProps.DeviceExtensions, deviceExtension)
}
return nil
}
func (i *SampleInfo) InitSwapchainExtension() error {
// Construct the surface
surfaceLoader := vkng_surface_sdl2.CreateExtensionFromInstance(i.Instance)
var err error
i.Surface, _, err = surfaceLoader.CreateSurface(i.Instance, i.Window)
if err != nil {
return err
}
// Iterate over each queue to learn whether it supports presenting:
var presentSupport []bool
for queueIndex := range i.QueueProps {
support, _, err := i.Surface.PhysicalDeviceSurfaceSupport(i.Gpus[0], queueIndex)
if err != nil {
return err
}
presentSupport = append(presentSupport, support)
}
// Search for a graphics and a present queue in the array of queue
// families, try to find one that supports both
i.GraphicsQueueFamilyIndex = -1
i.PresentQueueFamilyIndex = -1
for queueIndex, queueFamily := range i.QueueProps {
if (queueFamily.QueueFlags & core1_0.QueueGraphics) != 0 {
if i.GraphicsQueueFamilyIndex < 0 {
i.GraphicsQueueFamilyIndex = queueIndex
}
if presentSupport[queueIndex] {
i.GraphicsQueueFamilyIndex = queueIndex
i.PresentQueueFamilyIndex = queueIndex
break
}
}
}
if i.PresentQueueFamilyIndex < 0 {
// If didn't find a queue that supports both graphics and present, then
// find a separate present queue.
for queueIndex := range i.QueueProps {
if presentSupport[queueIndex] {
i.PresentQueueFamilyIndex = queueIndex
break
}
}
}
// Generate error if could not find queues that support graphics
// and present
if i.GraphicsQueueFamilyIndex < 0 || i.PresentQueueFamilyIndex < 0 {
return errors.New("could not find a queue for both graphics and present")
}
// Get the list of VkFormats that are supported:
formats, _, err := i.Surface.PhysicalDeviceSurfaceFormats(i.Gpus[0])
if err != nil {
return err
}
// If the device supports our preferred surface format, use it.
// Otherwise, use whatever the device's first reported surface
// format is.
i.Format = formats[0].Format
for _, format := range formats {
if format.Format == PreferredSurfaceFormat {
i.Format = PreferredSurfaceFormat
break
}
}
return nil
}
func (i *SampleInfo) InitDevice() error {
var err error
i.Device, _, err = i.Gpus[0].CreateDevice(nil, core1_0.DeviceCreateInfo{
QueueCreateInfos: []core1_0.DeviceQueueCreateInfo{
{
QueueFamilyIndex: i.GraphicsQueueFamilyIndex,
QueuePriorities: []float32{0.0},
},
},
EnabledExtensionNames: i.DeviceExtensionNames,
})
return err
}
func (i *SampleInfo) InitCommandPool() error {
var err error
i.CmdPool, _, err = i.Device.CreateCommandPool(nil, core1_0.CommandPoolCreateInfo{
QueueFamilyIndex: &i.GraphicsQueueFamilyIndex,
Flags: core1_0.CommandPoolCreateResetBuffer,
})
return err
}
func (i *SampleInfo) InitCommandBuffer() error {
buffers, _, err := i.Device.AllocateCommandBuffers(core1_0.CommandBufferAllocateInfo{
CommandPool: i.CmdPool,
Level: core1_0.CommandBufferLevelPrimary,
CommandBufferCount: 1,
})
if err != nil {
return err
}
i.Cmd = buffers[0]
return nil
}
func (i *SampleInfo) ExecuteBeginCommandBuffer() error {
_, err := i.Cmd.Begin(core1_0.CommandBufferBeginInfo{})
return err
}
func (i *SampleInfo) ExecuteEndCommandBuffer() error {
_, err := i.Cmd.End()
return err
}
func (i *SampleInfo) InitDeviceQueue() error {
i.GraphicsQueue = i.Device.GetQueue(i.GraphicsQueueFamilyIndex, 0)
if i.PresentQueueFamilyIndex == i.GraphicsQueueFamilyIndex {
i.PresentQueue = i.GraphicsQueue
return nil
}
i.PresentQueue = i.Device.GetQueue(i.PresentQueueFamilyIndex, 0)
return nil
}
func (i *SampleInfo) InitSwapchain(usage core1_0.ImageUsageFlags) error {
surfaceCaps, _, err := i.Surface.PhysicalDeviceSurfaceCapabilities(i.Gpus[0])
if err != nil {
return err
}
var swapchainExtent core1_0.Extent2D
if surfaceCaps.CurrentExtent.Width < 0 {
// If the surface size is undefined, the size is set to
// the size of the images requested.
swapchainExtent.Width = i.Width
swapchainExtent.Height = i.Height
if swapchainExtent.Width < surfaceCaps.MinImageExtent.Width {
swapchainExtent.Width = surfaceCaps.MinImageExtent.Width
} else if swapchainExtent.Width > surfaceCaps.MaxImageExtent.Width {
swapchainExtent.Width = surfaceCaps.MaxImageExtent.Width
}
if swapchainExtent.Height < surfaceCaps.MinImageExtent.Height {
swapchainExtent.Height = surfaceCaps.MinImageExtent.Height
} else if swapchainExtent.Height > surfaceCaps.MaxImageExtent.Height {
swapchainExtent.Height = surfaceCaps.MaxImageExtent.Height
}
} else {
// If the surface size is defined, the swap chain size must match
swapchainExtent = surfaceCaps.CurrentExtent
}
// The FIFO present mode is guaranteed by the spec to be supported
// Also note that current Android driver only supports FIFO
presentMode := khr_surface.PresentModeFIFO
// Determine the number of VkImage's to use in the swap chain.
// We need to acquire only 1 presentable image at a time.
// Asking for minImageCount images ensures that we can acquire
// 1 presentable image as long as we present it before attempting
// to acquire another.
desiredNumberOfSwapChainImages := surfaceCaps.MinImageCount
var preTransform khr_surface.SurfaceTransformFlags
if (surfaceCaps.SupportedTransforms & khr_surface.TransformIdentity) != 0 {
preTransform = khr_surface.TransformIdentity
} else {
preTransform = surfaceCaps.CurrentTransform
}
// Find a supported composite alpha mode - one of these is guaranteed to be set
compositeAlpha := khr_surface.CompositeAlphaOpaque
compositeAlphaFlags := [4]khr_surface.CompositeAlphaFlags{
khr_surface.CompositeAlphaOpaque,
khr_surface.CompositeAlphaPreMultiplied,
khr_surface.CompositeAlphaPostMultiplied,
khr_surface.CompositeAlphaInherit,
}
for i := 0; i < len(compositeAlphaFlags); i++ {
if (surfaceCaps.SupportedCompositeAlpha & compositeAlphaFlags[i]) != 0 {
compositeAlpha = compositeAlphaFlags[i]
break
}
}
i.SwapchainExtension = khr_swapchain.CreateExtensionFromDevice(i.Device)
swapchainOptions := khr_swapchain.SwapchainCreateInfo{
Surface: i.Surface,
MinImageCount: desiredNumberOfSwapChainImages,
ImageFormat: i.Format,
ImageExtent: swapchainExtent,
PreTransform: preTransform,
CompositeAlpha: compositeAlpha,
ImageArrayLayers: 1,
PresentMode: presentMode,
Clipped: true,
ImageColorSpace: khr_surface.ColorSpaceSRGBNonlinear,
ImageUsage: usage,
ImageSharingMode: core1_0.SharingModeExclusive,
}
if i.GraphicsQueueFamilyIndex != i.PresentQueueFamilyIndex {
// If the graphics and present queues are from different queue families,
// we either have to explicitly transfer ownership of images between the
// queues, or we have to create the swapchain with imageSharingMode
// as VK_SHARING_MODE_CONCURRENT
swapchainOptions.ImageSharingMode = core1_0.SharingModeConcurrent
swapchainOptions.QueueFamilyIndices = []int{
i.GraphicsQueueFamilyIndex,
i.PresentQueueFamilyIndex,
}
}
i.Swapchain, _, err = i.SwapchainExtension.CreateSwapchain(i.Device, nil, swapchainOptions)
if err != nil {
return err
}
images, _, err := i.Swapchain.SwapchainImages()
if err != nil {
return err
}
i.SwapchainImageCount = len(images)
for _, image := range images {
view, _, err := i.Device.CreateImageView(nil, core1_0.ImageViewCreateInfo{
Image: image,
ViewType: core1_0.ImageViewType2D,
Format: i.Format,
Components: core1_0.ComponentMapping{
R: core1_0.ComponentSwizzleRed,
G: core1_0.ComponentSwizzleGreen,
B: core1_0.ComponentSwizzleBlue,
A: core1_0.ComponentSwizzleAlpha,
},
SubresourceRange: core1_0.ImageSubresourceRange{
AspectMask: core1_0.ImageAspectColor,
BaseMipLevel: 0,
LevelCount: 1,
BaseArrayLayer: 0,
LayerCount: 1,
},
})
if err != nil {
return err
}
i.Buffers = append(i.Buffers, SwapchainBuffer{
Image: image,
View: view,
})
}
i.CurrentBuffer = 0
return nil
}
func (i *SampleInfo) InitDepthBuffer() error {
if i.Depth.Format == core1_0.FormatUndefined {
i.Depth.Format = core1_0.FormatD16UnsignedNormalized
}
depthFormat := i.Depth.Format
props := i.Gpus[0].FormatProperties(depthFormat)
imageOptions := core1_0.ImageCreateOptions{
ImageType: core1_0.ImageType2D,
Format: depthFormat,
Extent: core1_0.Extent3D{
Width: i.Width,
Height: i.Height,
Depth: 1,
},
MipLevels: 1,
ArrayLayers: 1,
Samples: NumSamples,
InitialLayout: core1_0.ImageLayoutUndefined,
SharingMode: core1_0.SharingModeExclusive,
Usage: core1_0.ImageUsageDepthStencilAttachment,
}
if (props.LinearTilingFeatures & core1_0.FormatFeatureDepthStencilAttachment) != 0 {
imageOptions.Tiling = core1_0.ImageTilingLinear
} else if (props.OptimalTilingFeatures & core1_0.FormatFeatureDepthStencilAttachment) != 0 {
imageOptions.Tiling = core1_0.ImageTilingOptimal
} else {
return errors.Newf("depth format %s unsupported", depthFormat)
}
var err error
i.Depth.Image, _, err = i.Device.CreateImage(nil, imageOptions)
if err != nil {
return err
}
imageMemoryReqs := i.Depth.Image.MemoryRequirements()
typeIndex, err := i.MemoryTypeFromProperties(imageMemoryReqs.MemoryTypeBits, core1_0.MemoryPropertyDeviceLocal)
if err != nil {
return err
}
i.Depth.Mem, _, err = i.Device.AllocateMemory(nil, core1_0.MemoryAllocateInfo{
AllocationSize: imageMemoryReqs.Size,
MemoryTypeIndex: typeIndex,
})
if err != nil {
return err
}
_, err = i.Depth.Image.BindImageMemory(i.Depth.Mem, 0)
if err != nil {
return err
}
i.Depth.View, _, err = i.Device.CreateImageView(nil, core1_0.ImageViewCreateInfo{
Image: i.Depth.Image,
Format: depthFormat,
Components: core1_0.ComponentMapping{
A: core1_0.ComponentSwizzleAlpha,
R: core1_0.ComponentSwizzleRed,
G: core1_0.ComponentSwizzleGreen,
B: core1_0.ComponentSwizzleBlue,
},
SubresourceRange: core1_0.ImageSubresourceRange{
AspectMask: core1_0.ImageAspectDepth,
BaseMipLevel: 0,
LevelCount: 1,
BaseArrayLayer: 0,
LayerCount: 1,
},
ViewType: core1_0.ImageViewType2D,
})
return err
}
func (i *SampleInfo) MemoryTypeFromProperties(memoryType uint32, flags core1_0.MemoryPropertyFlags) (int, error) {
for typeIndex, memType := range i.MemoryProperties.MemoryTypes {
if (memoryType & 1) != 0 {
// Type is available, does it match user properties?
if (memType.PropertyFlags & flags) == flags {
return typeIndex, nil
}
}
memoryType >>= 1
}
return 0, errors.Newf("could not find a memory type matching type request %x with flags %s", memoryType, flags)
}
func (i *SampleInfo) InitUniformBuffer() error {
fov := mgl32.DegToRad(45)
if i.Width > i.Height {
fov *= float32(i.Height) / float32(i.Width)
}
i.Projection = mgl32.Perspective(fov, float32(i.Width)/float32(i.Height), 0.1, 100)
i.View = mgl32.LookAt(-5, 3, -10, 0, 0, 0, 0, -1, 0)
i.Model = mgl32.Ident4()
i.Clip = mgl32.Mat4{1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1}
i.MVP = i.Clip.Mul4(i.Projection).Mul4(i.View).Mul4(i.Model)
var err error
i.UniformData.Buf, _, err = i.Device.CreateBuffer(nil, core1_0.BufferCreateInfo{
Usage: core1_0.BufferUsageUniformBuffer,
Size: int(unsafe.Sizeof(i.MVP)),
SharingMode: core1_0.SharingModeExclusive,
})
if err != nil {
return err
}
memReqs := i.UniformData.Buf.MemoryRequirements()
memoryTypeIndex, err := i.MemoryTypeFromProperties(memReqs.MemoryTypeBits, core1_0.MemoryPropertyHostVisible|core1_0.MemoryPropertyHostCoherent)
if err != nil {
return err
}
i.UniformData.Mem, _, err = i.Device.AllocateMemory(nil, core1_0.MemoryAllocateInfo{
AllocationSize: memReqs.Size,
MemoryTypeIndex: memoryTypeIndex,
})
if err != nil {
return err
}
memPtr, _, err := i.UniformData.Mem.Map(0, memReqs.Size, 0)
if err != nil {
return err
}
dataBuffer := unsafe.Slice((*byte)(memPtr), memReqs.Size)
buf := &bytes.Buffer{}
err = binary.Write(buf, common.ByteOrder, i.MVP)
if err != nil {
i.UniformData.Mem.Unmap()
return err
}
copy(dataBuffer, buf.Bytes())
i.UniformData.Mem.Unmap()
if err != nil {
return err
}
_, err = i.UniformData.Buf.BindBufferMemory(i.UniformData.Mem, 0)
if err != nil {
return err
}
i.UniformData.BufferInfo.Buffer = i.UniformData.Buf
i.UniformData.BufferInfo.Offset = 0
i.UniformData.BufferInfo.Range = int(unsafe.Sizeof(i.MVP))
return nil
}
func (i *SampleInfo) InitDescriptorAndPipelineLayouts(useTexture bool) error {
layoutBindings := []core1_0.DescriptorSetLayoutBinding{
{
Binding: 0,
DescriptorType: core1_0.DescriptorTypeUniformBuffer,
DescriptorCount: 1,
StageFlags: core1_0.StageVertex,
},
}
if useTexture {
layoutBindings = append(layoutBindings, core1_0.DescriptorSetLayoutBinding{
Binding: 1,
DescriptorType: core1_0.DescriptorTypeCombinedImageSampler,
DescriptorCount: 1,
StageFlags: core1_0.StageFragment,
})
}
layout, _, err := i.Device.CreateDescriptorSetLayout(nil, core1_0.DescriptorSetLayoutCreateInfo{
Bindings: layoutBindings,
})
if err != nil {
return err
}
i.DescLayout = []core1_0.DescriptorSetLayout{layout}
i.PipelineLayout, _, err = i.Device.CreatePipelineLayout(nil, core1_0.PipelineLayoutCreateInfo{
SetLayouts: []core1_0.DescriptorSetLayout{layout},
})
return err
}
func (i *SampleInfo) InitRenderPass(depthPresent, clear bool, finalLayout, initialLayout core1_0.ImageLayout) error {
attachments := []core1_0.AttachmentDescription{
{
Format: i.Format,
Samples: NumSamples,
LoadOp: core1_0.AttachmentLoadOpClear,
StoreOp: core1_0.AttachmentStoreOpStore,
StencilLoadOp: core1_0.AttachmentLoadOpDontCare,
StencilStoreOp: core1_0.AttachmentStoreOpDontCare,
InitialLayout: initialLayout,
FinalLayout: finalLayout,
},
}
if !clear {
attachments[0].LoadOp = core1_0.AttachmentLoadOpLoad
}
if depthPresent {
attachments = append(attachments, core1_0.AttachmentDescription{
Format: i.Depth.Format,
Samples: NumSamples,
LoadOp: core1_0.AttachmentLoadOpClear,
StoreOp: core1_0.AttachmentStoreOpStore,
StencilLoadOp: core1_0.AttachmentLoadOpDontCare,
StencilStoreOp: core1_0.AttachmentStoreOpStore,
InitialLayout: core1_0.ImageLayoutUndefined,
FinalLayout: core1_0.ImageLayoutDepthStencilAttachmentOptimal,
})
if !clear {
attachments[1].LoadOp = core1_0.AttachmentLoadOpDontCare
}
}
renderPassOptions := core1_0.RenderPassCreateInfo{
Attachments: attachments,
Subpasses: []core1_0.SubpassDescription{
{
PipelineBindPoint: core1_0.PipelineBindPointGraphics,
ColorAttachments: []core1_0.AttachmentReference{
{
Attachment: 0,
Layout: core1_0.ImageLayoutColorAttachmentOptimal,
},
},
},
},
SubpassDependencies: []core1_0.SubpassDependency{
{
SrcSubpass: core1_0.SubpassExternal,
DstSubpass: 0,
SrcStageMask: core1_0.PipelineStageColorAttachmentOutput,
DstStageMask: core1_0.PipelineStageColorAttachmentOutput,
SrcAccessMask: 0,
DstAccessMask: core1_0.AccessColorAttachmentWrite,
},
},
}
if depthPresent {
renderPassOptions.Subpasses[0].DepthStencilAttachment = &core1_0.AttachmentReference{
Attachment: 1,
Layout: core1_0.ImageLayoutDepthStencilAttachmentOptimal,
}
}
var err error
i.RenderPass, _, err = i.Device.CreateRenderPass(nil, renderPassOptions)
return err
}
func bytesToBytecode(b []byte) []uint32 {
byteCode := make([]uint32, len(b)/4)
for i := 0; i < len(byteCode); i++ {
byteIndex := i * 4
byteCode[i] = 0
byteCode[i] |= uint32(b[byteIndex])
byteCode[i] |= uint32(b[byteIndex+1]) << 8
byteCode[i] |= uint32(b[byteIndex+2]) << 16
byteCode[i] |= uint32(b[byteIndex+3]) << 24
}
return byteCode
}
func (i *SampleInfo) InitShaders(vertShaderBytes []byte, fragShaderBytes []byte) error {
vertShaderModule, _, err := i.Device.CreateShaderModule(nil, core1_0.ShaderModuleCreateInfo{
Code: bytesToBytecode(vertShaderBytes),
})
if err != nil {
return err
}
fragShaderModule, _, err := i.Device.CreateShaderModule(nil, core1_0.ShaderModuleCreateInfo{
Code: bytesToBytecode(fragShaderBytes),
})
if err != nil {
return err
}
i.ShaderStages = []core1_0.PipelineShaderStageCreateInfo{
{
Stage: core1_0.StageVertex,
Name: "main",
Module: vertShaderModule,
},
{
Stage: core1_0.StageFragment,
Name: "main",
Module: fragShaderModule,
},
}
return nil
}
func (i *SampleInfo) InitFramebuffers(depthPresent bool) error {
framebufferOptions := core1_0.FramebufferCreateInfo{
RenderPass: i.RenderPass,
Attachments: []core1_0.ImageView{nil},
Width: i.Width,
Height: i.Height,
Layers: 1,
}
if depthPresent {
framebufferOptions.Attachments = append(framebufferOptions.Attachments, i.Depth.View)
}
for swapchainInd := 0; swapchainInd < i.SwapchainImageCount; swapchainInd++ {
framebufferOptions.Attachments[0] = i.Buffers[swapchainInd].View
var err error
frameBuffer, _, err := i.Device.CreateFramebuffer(nil, framebufferOptions)
if err != nil {
return err
}
i.Framebuffer = append(i.Framebuffer, frameBuffer)
}
return nil
}
func (i *SampleInfo) InitVertexBuffers(vertexData any, dataSize int, dataStride int, useTexture bool) error {
var err error
i.VertexBuffer.Buf, _, err = i.Device.CreateBuffer(nil, core1_0.BufferCreateInfo{
Size: dataSize,
Usage: core1_0.BufferUsageVertexBuffer,
SharingMode: core1_0.SharingModeExclusive,
})
if err != nil {
return err
}
memReqs := i.VertexBuffer.Buf.MemoryRequirements()
memoryIndex, err := i.MemoryTypeFromProperties(memReqs.MemoryTypeBits, core1_0.MemoryPropertyHostVisible|core1_0.MemoryPropertyHostCoherent)
if err != nil {
return err
}
i.VertexBuffer.Mem, _, err = i.Device.AllocateMemory(nil, core1_0.MemoryAllocateInfo{
AllocationSize: memReqs.Size,
MemoryTypeIndex: memoryIndex,
})
if err != nil {
return err
}
i.VertexBuffer.BufferInfo.Range = memReqs.Size
i.VertexBuffer.BufferInfo.Offset = 0
vertexPtr, _, err := i.VertexBuffer.Mem.Map(0, memReqs.Size, 0)
if err != nil {
return err
}
dataBuffer := unsafe.Slice((*byte)(vertexPtr), memReqs.Size)
buf := &bytes.Buffer{}
err = binary.Write(buf, common.ByteOrder, vertexData)
if err != nil {
i.VertexBuffer.Mem.Unmap()
return err
}
copy(dataBuffer, buf.Bytes())
i.VertexBuffer.Mem.Unmap()
_, err = i.VertexBuffer.Buf.BindBufferMemory(i.VertexBuffer.Mem, 0)
if err != nil {
return err
}
i.VertexBinding = core1_0.VertexInputBindingDescription{
InputRate: core1_0.RateVertex,
Binding: 0,
Stride: dataStride,
}
i.VertexAttributes = []core1_0.VertexInputAttributeDescription{
{
Binding: 0,
Location: 0,
Offset: 0,
Format: core1_0.FormatR32G32B32A32SignedFloat,
},
{
Binding: 0,
Location: 1,
Offset: 16,
},
}
if useTexture {
i.VertexAttributes[1].Format = core1_0.FormatR32G32SignedFloat
} else {
i.VertexAttributes[1].Format = core1_0.FormatR32G32B32A32SignedFloat
}
return nil
}
func (i *SampleInfo) InitDescriptorPool(useTexture bool) error {
poolSizes := []core1_0.DescriptorPoolSize{
{
Type: core1_0.DescriptorTypeUniformBuffer,
DescriptorCount: 1,
},
}
if useTexture {
poolSizes = append(poolSizes, core1_0.DescriptorPoolSize{
Type: core1_0.DescriptorTypeCombinedImageSampler,
DescriptorCount: 1,
})
}
var err error
i.DescPool, _, err = i.Device.CreateDescriptorPool(nil, core1_0.DescriptorPoolCreateInfo{
MaxSets: 1,
PoolSizes: poolSizes,
})
return err
}
func (i *SampleInfo) InitDescriptorSet(useTexture bool) error {
descSet, _, err := i.Device.AllocateDescriptorSets(core1_0.DescriptorSetAllocateInfo{
DescriptorPool: i.DescPool,
SetLayouts: i.DescLayout,
})
if err != nil {
log.Fatalln(err)
}
i.DescSet = descSet
writes := []core1_0.WriteDescriptorSet{
{
DstSet: i.DescSet[0],
DstBinding: 0,
DstArrayElement: 0,
DescriptorType: core1_0.DescriptorTypeUniformBuffer,
BufferInfo: []core1_0.DescriptorBufferInfo{i.UniformData.BufferInfo},
},
}
if useTexture {
writes = append(writes, core1_0.WriteDescriptorSet{
DstSet: i.DescSet[0],
DstBinding: 1,
DstArrayElement: 0,
DescriptorType: core1_0.DescriptorTypeCombinedImageSampler,
ImageInfo: []core1_0.DescriptorImageInfo{i.TextureData.ImageInfo},
})
}
return i.Device.UpdateDescriptorSets(writes, nil)
}
func (i *SampleInfo) InitPipelineCache() error {
var err error
i.PipelineCache, _, err = i.Device.CreatePipelineCache(nil, core1_0.PipelineCacheCreateInfo{})
return err
}
func (i *SampleInfo) InitPipeline(depthPresent bool, vertexPresent bool) error {
pipelineOptions := core1_0.GraphicsPipelineCreateInfo{
Stages: i.ShaderStages,
VertexInputState: &core1_0.PipelineVertexInputStateCreateInfo{},
InputAssemblyState: &core1_0.PipelineInputAssemblyStateCreateInfo{
PrimitiveRestartEnable: false,
Topology: core1_0.PrimitiveTopologyTriangleList,
},
ViewportState: &core1_0.PipelineViewportStateCreateInfo{