-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path10 Texture 3d.kt
689 lines (576 loc) · 24.3 KB
/
10 Texture 3d.kt
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
/*
* Vulkan Example - 3D texture loading (and generation using perlin noise) example
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
package vulkan.basics
import glm_.L
import glm_.b
import glm_.func.rad
import glm_.glm
import glm_.mat4x4.Mat4
import glm_.set
import glm_.vec2.Vec2
import glm_.vec3.Vec3
import glm_.vec3.Vec3i
import glm_.vec4.Vec4
import kool.bufferBig
import kool.cap
import kool.free
import kool.stak
import org.lwjgl.system.MemoryUtil.*
import org.lwjgl.vulkan.VkDescriptorImageInfo
import org.lwjgl.vulkan.VkPipelineVertexInputStateCreateInfo
import org.lwjgl.vulkan.VkVertexInputAttributeDescription
import org.lwjgl.vulkan.VkVertexInputBindingDescription
import uno.kotlin.buffers.indices
import vkk.*
import vulkan.VERTEX_BUFFER_BIND_ID
import vulkan.assetPath
import vulkan.base.*
import java.util.concurrent.ThreadLocalRandom
import java.util.stream.IntStream
import kotlin.system.measureTimeMillis
fun main(args: Array<String>) {
Texture3d().apply {
setupWindow()
initVulkan()
prepare()
renderLoop()
destroy()
}
}
private class Texture3d : VulkanExampleBase() {
/** Vertex layout for this example */
object Vertex : Bufferizable() {
lateinit var pos: Vec3
lateinit var uv: Vec2
@Order(2)
lateinit var normal: Vec3
}
/** Fractal noise generator based on perlin noise above */
class FractalNoise {
val octaves = 6
var frequency = 0f
var amplitude = 0f
var persistence = 0.5f
fun noise(v: Vec3): Float {
var sum = 0f
frequency = 1f
amplitude = 1f
var max = 0f
for (i in 0 until octaves) {
sum += glm.perlin(v * frequency) * amplitude
max += amplitude
amplitude *= persistence
frequency *= 2f
}
sum /= max
return (sum + 1f) / 2f
}
}
/** Contains all Vulkan objects that are required to store and use a 3D texture */
object texture {
var sampler = VkSampler(NULL)
var image = VkImage(NULL)
var imageLayout = VkImageLayout.UNDEFINED
var deviceMemory = VkDeviceMemory(NULL)
var view = VkImageView(NULL)
lateinit var descriptor: VkDescriptorImageInfo
var format = VkFormat.UNDEFINED
val extent = Vec3i()
var mipLevels = 0
}
object models {
val cube = Model()
}
object vertices {
lateinit var inputState: VkPipelineVertexInputStateCreateInfo
lateinit var inputBinding: VkVertexInputBindingDescription
lateinit var inputAttributes: VkVertexInputAttributeDescription.Buffer
}
val vertexBuffer = Buffer()
val indexBuffer = Buffer()
var indexCount = 0
val uniformBufferVS = Buffer()
object uboVS : Bufferizable() {
lateinit var projection: Mat4
@Order(1)
lateinit var model: Mat4
lateinit var viewPos: Vec4
@Order(3)
var depth = 0f
}
object pipelines {
var solid = VkPipeline(NULL)
}
var pipelineLayout = VkPipelineLayout(NULL)
var descriptorSet = VkDescriptorSet(NULL)
var descriptorSetLayout = VkDescriptorSetLayout(NULL)
init {
zoom = -2.5f
rotation(0f, 15f, 0f)
title = "3D textures"
// settings.overlay = true
// srand((unsigned int) time (NULL))
}
override fun destroy() {
// Clean up used Vulkan resources
// Note : Inherited destructor cleans up resources stored in base class
destroyTextureImage()
device.apply {
destroyPipeline(pipelines.solid)
destroyPipelineLayout(pipelineLayout)
destroyDescriptorSetLayout(descriptorSetLayout)
}
vertexBuffer.destroy()
indexBuffer.destroy()
uniformBufferVS.destroy()
super.destroy()
}
/** Prepare all Vulkan resources for the 3D texture (including descriptors)
* Does not fill the texture with data */
fun prepareNoiseTexture(width: Int, height: Int, depth: Int) {
// A 3D texture is described as width x height x depth
texture.extent.put(width, height, depth) // TODO glm
texture.mipLevels = 1
texture.format = VkFormat.R8_UNORM
// Format support check
// 3D texture support in Vulkan is mandatory (in contrast to OpenGL) so no need to check if it's supported
val formatProperties = physicalDevice getFormatProperties texture.format
// Check if format supports transfer
if (formatProperties.optimalTilingFeatures hasnt VkFormatFeature.TRANSFER_DST_BIT) {
System.err.println("Error: Device does not support flag TRANSFER_DST for selected texture format!")
return
}
// Check if GPU supports requested 3D texture dimensions
val maxImageDimension3D = vulkanDevice.properties.limits.maxImageDimension3D
if (width > maxImageDimension3D || height > maxImageDimension3D || depth > maxImageDimension3D) {
System.out.println("Error: Requested texture dimensions is greater than supported 3D texture dimension!")
return
}
// Create optimal tiled target image
val imageCreateInfo = vk.ImageCreateInfo {
imageType = VkImageType.`3D`
format = texture.format
mipLevels = texture.mipLevels
arrayLayers = 1
samples = VkSampleCount.`1_BIT`
tiling = VkImageTiling.OPTIMAL
sharingMode = VkSharingMode.EXCLUSIVE
extent(texture.extent)
// Set initial layout of the image to undefined
initialLayout = VkImageLayout.UNDEFINED
usage = VkImageUsage.TRANSFER_DST_BIT or VkImageUsage.SAMPLED_BIT
}
texture.image = device createImage imageCreateInfo
// Device local memory to back up image
val memReqs = device getImageMemoryRequirements texture.image
val memAllocInfo = vk.MemoryAllocateInfo {
allocationSize = memReqs.size
memoryTypeIndex = vulkanDevice.getMemoryType(memReqs.memoryTypeBits, VkMemoryProperty.DEVICE_LOCAL_BIT)
}
texture.deviceMemory = device allocateMemory memAllocInfo
device.bindImageMemory(texture.image, texture.deviceMemory, VkDeviceSize(0))
// Create sampler
val sampler = vk.SamplerCreateInfo {
minMagFilter = VkFilter.LINEAR
mipmapMode = VkSamplerMipmapMode.LINEAR
addressModeUVW = VkSamplerAddressMode.CLAMP_TO_EDGE
mipLodBias = 0f
compareOp = VkCompareOp.NEVER
minLod = 0f
maxLod = 0f
maxAnisotropy = 1f
anisotropyEnable = false
borderColor = VkBorderColor.FLOAT_OPAQUE_WHITE
}
texture.sampler = device createSampler sampler
// Create image view
val view = vk.ImageViewCreateInfo {
image = texture.image
viewType = VkImageViewType.`3D`
format = texture.format
components(VkComponentSwizzle.R, VkComponentSwizzle.G, VkComponentSwizzle.B, VkComponentSwizzle.A)
subresourceRange.apply {
aspectMask = VkImageAspect.COLOR_BIT.i
baseMipLevel = 0
baseArrayLayer = 0
layerCount = 1
levelCount = 1
}
}
texture.view = device createImageView view
// Fill image descriptor image info to be used descriptor set setup
texture.descriptor = vk.DescriptorImageInfo {
imageLayout = VkImageLayout.SHADER_READ_ONLY_OPTIMAL
imageView = texture.view
this.sampler = texture.sampler
}
updateNoiseTexture()
}
/** Generate randomized noise and upload it to the 3D texture using staging */
fun updateNoiseTexture() {
val ext = texture.extent
val texMemSize = VkDeviceSize(ext.x * ext.y * ext.z.L)
val data = bufferBig(texMemSize)
val adr = memAddress(data)
for (i in data.indices)
memPutByte(adr + i, i.b)
// Generate perlin based noise
println("Generating ${ext.x} x ${ext.y} x ${ext.z} noise texture...")
// auto tStart = std ::chrono::high_resolution_clock::now()
/* Maximum value that can be returned by the rand function:
define RAND_MAX 0x7fff
0111 1111 1111 1111
*/
fun rand() = ThreadLocalRandom.current().nextInt() ushr 1
val time = measureTimeMillis {
val FRACTAL = true
val noiseScale = rand() % 10 + 4f
val parallel = true
if (!parallel)
for (z in 0 until ext.z) {
println(z)
for (y in 0 until ext.y)
for (x in 0 until ext.x) {
println("x $x, y $y, z $z")
val v = Vec3(x, y, z) / ext
var n = when {
FRACTAL -> FractalNoise().noise(v * noiseScale)
else -> 20f * glm.perlin(v)
}
n -= glm.floor(n)
data[x + y * ext.x + z * ext.x * ext.y] = glm.floor(n * 255).b
}
}
else {
// runBlocking {
// for (z in 0 until 1) {
// println(z)
//// for (z in 0 until 1) {
// for (y in 0 until 1)
// for (x in 0 until 100) {
// launch {
// val v = Vec3(x, y, z) / texture.extent
// var n = when {
// FRACTAL -> FractalNoise().noise(v * noiseScale)
// else -> 20f * glm.perlin(v)
// }
// n -= glm.floor(n)
//
// val offset = x + y * texture.extent.x + z * texture.extent.x * texture.extent.y
// println("$adr, "+offset)
// memPutByte(adr + offset, glm.floor(n * 255).b)
//// data[x + y * texture.extent.x + z * texture.extent.x * texture.extent.y] = glm.floor(n * 255).b
// }
// }
// }
// }
IntStream
.range(0, ext.x * ext.y * ext.z)
.parallel()
.forEach {
val z = it / (ext.x * ext.y)
val remainder = it - z * ext.x * ext.y
val y = remainder / ext.x
val x = remainder % ext.x
val v = Vec3(x, y, z) / ext
var n = when {
FRACTAL -> FractalNoise().noise(v * noiseScale)
else -> 20f * glm.perlin(v)
}
n -= glm.floor(n)
data[x + y * ext.x + z * ext.x * ext.y] = glm.floor(n * 255).b
}
//
// val channel = Channel<ProcessingRequest>()
//
// val processingPool = newThreadPool
//
// launch(processingPool) { for (request in channel) doProcessing(it) }
//
//
//
// for ...
//
// for ...
//
// channel.sendBlocking(ProcessingRequest(...))
}
}
println("Done in ${time}ms")
// Create a host-visible staging buffer that contains the raw image data
// Buffer object
val bufferCreateInfo = vk.BufferCreateInfo {
size = texMemSize
usage = VkBufferUsage.TRANSFER_SRC_BIT.i
sharingMode = VkSharingMode.EXCLUSIVE
}
val stagingBuffer: VkBuffer = device createBuffer bufferCreateInfo
// Allocate host visible memory for data upload
val memReqs = device getBufferMemoryRequirements stagingBuffer
val memAllocInfo = vk.MemoryAllocateInfo {
allocationSize = memReqs.size
memoryTypeIndex = vulkanDevice.getMemoryType(memReqs.memoryTypeBits, VkMemoryProperty.HOST_VISIBLE_BIT or VkMemoryProperty.HOST_COHERENT_BIT)
}
val stagingMemory = device allocateMemory memAllocInfo
device.bindBufferMemory(stagingBuffer, stagingMemory)
// Copy texture data into staging buffer
device.mappingMemory(stagingMemory, VkDeviceSize(0), memReqs.size) { mapped ->
memCopy(memAddress(data), mapped, texMemSize)
}
val copyCmd = super.createCommandBuffer(VkCommandBufferLevel.PRIMARY, true)
// The sub resource range describes the regions of the image we will be transitioned
val subresourceRange = vk.ImageSubresourceRange {
aspectMask = VkImageAspect.COLOR_BIT.i
baseMipLevel = 0
levelCount = 1
layerCount = 1
}
// Optimal image will be used as destination for the copy, so we must transfer from our
// initial undefined image layout to the transfer destination layout
tools.setImageLayout(
copyCmd,
texture.image,
VkImageLayout.UNDEFINED,
VkImageLayout.TRANSFER_DST_OPTIMAL,
subresourceRange)
// Copy 3D noise data to texture
// Setup buffer copy regions
val bufferCopyRegion = vk.BufferImageCopy {
imageSubresource.apply {
aspectMask = VkImageAspect.COLOR_BIT.i
mipLevel = 0
baseArrayLayer = 0
layerCount = 1
}
imageExtent(texture.extent)
}
copyCmd.copyBufferToImage(
stagingBuffer,
texture.image,
VkImageLayout.TRANSFER_DST_OPTIMAL,
bufferCopyRegion)
// Change texture image layout to shader read after all mip levels have been copied
texture.imageLayout = VkImageLayout.SHADER_READ_ONLY_OPTIMAL
tools.setImageLayout(
copyCmd,
texture.image,
VkImageLayout.TRANSFER_DST_OPTIMAL,
texture.imageLayout,
subresourceRange)
super.flushCommandBuffer(copyCmd, queue, true)
// Clean up staging resources
data.free()
device freeMemory stagingMemory
device destroyBuffer stagingBuffer
}
/** Free all Vulkan resources used a texture object */
fun destroyTextureImage() {
device.apply {
if (texture.view.L != NULL)
destroyImageView(texture.view)
if (texture.image.L != NULL)
destroyImage(texture.image)
if (texture.sampler.L != NULL)
destroySampler(texture.sampler)
if (texture.deviceMemory.L != NULL)
freeMemory(texture.deviceMemory)
}
}
override fun buildCommandBuffers() {
val cmdBufInfo = vk.CommandBufferBeginInfo()
val clearValues = vk.ClearValue(2).also {
it[0].color(defaultClearColor)
it[1].depthStencil(1f, 0)
}
val renderPassBeginInfo = vk.RenderPassBeginInfo {
renderPass = [email protected]
renderArea.apply {
offset(0)
extent(size)
}
this.clearValues = clearValues
}
for (i in drawCmdBuffers.indices) {
// Set target frame buffer
renderPassBeginInfo.framebuffer(frameBuffers[i].L)
drawCmdBuffers[i].apply {
begin(cmdBufInfo)
beginRenderPass(renderPassBeginInfo, VkSubpassContents.INLINE)
setViewport(size)
setScissor(size)
bindDescriptorSets(VkPipelineBindPoint.GRAPHICS, pipelineLayout, descriptorSet)
bindPipeline(VkPipelineBindPoint.GRAPHICS, pipelines.solid)
bindVertexBuffers(VERTEX_BUFFER_BIND_ID, vertexBuffer.buffer)
bindIndexBuffer(indexBuffer.buffer, VkDeviceSize(0), VkIndexType.UINT32)
drawIndexed(indexCount, 1, 0, 0, 0)
drawUI()
endRenderPass()
end()
}
}
}
fun draw() {
super.prepareFrame()
// Command buffer to be sumitted to the queue
submitInfo.commandBuffer = drawCmdBuffers[currentBuffer]
// Submit to queue
queue submit submitInfo
super.submitFrame()
}
fun generateQuad() = stak {
// Setup vertices for a single uv-mapped quad made from two triangles
val vertices = it.floats(
+1f, +1f, 0f, 1f, 1f, 0f, 0f, 1f,
-1f, +1f, 0f, 0f, 1f, 0f, 0f, 1f,
-1f, -1f, 0f, 0f, 0f, 0f, 0f, 1f,
+1f, -1f, 0f, 1f, 0f, 0f, 0f, 1f)
// Setup indices
val indices = it.ints(0, 1, 2, 2, 3, 0)
indexCount = indices.cap
// Create buffers
// For the sake of simplicity we won't stage the vertex data to the gpu memory
// Vertex buffer
vulkanDevice.createBuffer(
VkBufferUsage.VERTEX_BUFFER_BIT.i,
VkMemoryProperty.HOST_VISIBLE_BIT or VkMemoryProperty.HOST_COHERENT_BIT,
vertexBuffer,
vertices)
// Index buffer
vulkanDevice.createBuffer(
VkBufferUsage.INDEX_BUFFER_BIT.i,
VkMemoryProperty.HOST_VISIBLE_BIT or VkMemoryProperty.HOST_COHERENT_BIT,
indexBuffer,
indices)
}
fun setupVertexDescriptions() {
// Binding description
vertices.inputBinding = vk.VertexInputBindingDescription(VERTEX_BUFFER_BIND_ID, Vertex.size, VkVertexInputRate.VERTEX)
// Attribute descriptions
// Describes memory layout and shader positions
vertices.inputAttributes = vk.VertexInputAttributeDescription(
// Location 0 : Position
VERTEX_BUFFER_BIND_ID, 0, VkFormat.R32G32B32_SFLOAT, Vertex.offsetOf("pos"),
// Location 1 : Texture coordinates
VERTEX_BUFFER_BIND_ID, 1, VkFormat.R32G32_SFLOAT, Vertex.offsetOf("uv"),
// Location 1 : Vertex normal
VERTEX_BUFFER_BIND_ID, 2, VkFormat.R32G32B32_SFLOAT, Vertex.offsetOf("normal"))
vertices.inputState = vk.PipelineVertexInputStateCreateInfo {
vertexBindingDescription = vertices.inputBinding
vertexAttributeDescriptions = vertices.inputAttributes
}
}
fun setupDescriptorPool() {
// Example uses one ubo and one image sampler
val poolSizes = vk.DescriptorPoolSize(
VkDescriptorType.UNIFORM_BUFFER, 1,
VkDescriptorType.COMBINED_IMAGE_SAMPLER, 1)
val descriptorPoolInfo = vk.DescriptorPoolCreateInfo(poolSizes, 2)
descriptorPool = device createDescriptorPool descriptorPoolInfo
}
fun setupDescriptorSetLayout() {
val setLayoutBindings = vk.DescriptorSetLayoutBinding(
// Binding 0 : Vertex shader uniform buffer
VkDescriptorType.UNIFORM_BUFFER, VkShaderStage.VERTEX_BIT.i, 0,
// Binding 1 : Fragment shader image sampler
VkDescriptorType.COMBINED_IMAGE_SAMPLER, VkShaderStage.FRAGMENT_BIT.i, 1)
val descriptorLayout = vk.DescriptorSetLayoutCreateInfo(setLayoutBindings)
descriptorSetLayout = device createDescriptorSetLayout descriptorLayout
val pipelineLayoutCreateInfo = vk.PipelineLayoutCreateInfo(descriptorSetLayout)
pipelineLayout = device createPipelineLayout pipelineLayoutCreateInfo
}
fun setupDescriptorSet() {
val allocInfo = vk.DescriptorSetAllocateInfo(descriptorPool, descriptorSetLayout)
descriptorSet = device allocateDescriptorSets allocInfo
val writeDescriptorSets = vk.WriteDescriptorSet(
// Binding 0 : Vertex shader uniform buffer
descriptorSet, VkDescriptorType.UNIFORM_BUFFER, 0, uniformBufferVS.descriptor,
// Binding 1 : Fragment shader texture sampler
descriptorSet, VkDescriptorType.COMBINED_IMAGE_SAMPLER, 1, texture.descriptor)
device updateDescriptorSets writeDescriptorSets
}
fun preparePipelines() {
val inputAssemblyState = vk.PipelineInputAssemblyStateCreateInfo(VkPrimitiveTopology.TRIANGLE_LIST, 0, false)
val rasterizationState = vk.PipelineRasterizationStateCreateInfo(VkPolygonMode.FILL, VkCullMode.NONE.i, VkFrontFace.CLOCKWISE)
val blendAttachmentState = vk.PipelineColorBlendAttachmentState(0xf, false)
val colorBlendState = vk.PipelineColorBlendStateCreateInfo(blendAttachmentState)
val depthStencilState = vk.PipelineDepthStencilStateCreateInfo(true, true, VkCompareOp.LESS_OR_EQUAL)
val viewportState = vk.PipelineViewportStateCreateInfo(1, 1)
val multisampleState = vk.PipelineMultisampleStateCreateInfo(VkSampleCount.`1_BIT`)
val dynamicStateEnables = listOf(VkDynamicState.VIEWPORT, VkDynamicState.SCISSOR)
val dynamicState = vk.PipelineDynamicStateCreateInfo(dynamicStateEnables)
// Load shaders
val shaderStages = vk.PipelineShaderStageCreateInfo(2).also {
it[0].loadShader("$assetPath/shaders/texture3d/texture3d.vert.spv", VkShaderStage.VERTEX_BIT)
it[1].loadShader("$assetPath/shaders/texture3d/texture3d.frag.spv", VkShaderStage.FRAGMENT_BIT)
}
val pipelineCreateInfo = vk.GraphicsPipelineCreateInfo(pipelineLayout, renderPass).also {
it.vertexInputState = vertices.inputState
it.inputAssemblyState = inputAssemblyState
it.rasterizationState = rasterizationState
it.colorBlendState = colorBlendState
it.multisampleState = multisampleState
it.viewportState = viewportState
it.depthStencilState = depthStencilState
it.dynamicState = dynamicState
it.stages = shaderStages
}
pipelines.solid = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo)
}
/** Prepare and initialize uniform buffer containing shader uniforms */
fun prepareUniformBuffers() {
// Vertex shader uniform buffer block
vulkanDevice.createBuffer(
VkBufferUsage.UNIFORM_BUFFER_BIT.i,
VkMemoryProperty.HOST_VISIBLE_BIT or VkMemoryProperty.HOST_COHERENT_BIT,
uniformBufferVS,
VkDeviceSize(uboVS.size.L))
updateUniformBuffers()
}
fun updateUniformBuffers(viewchanged: Boolean = true) {
if (viewchanged) {
uboVS.projection = glm.perspective(60f.rad, size.aspect, 0.001f, 256f)
val viewMatrix = glm.translate(Mat4(1f), 0f, 0f, zoom)
uboVS.model = viewMatrix * glm.translate(Mat4(1f), cameraPos)
.rotateAssign(rotation.x.rad, 1f, 0f, 0f)
.rotateAssign(rotation.y.rad, 0f, 1f, 0f)
.rotateAssign(rotation.z.rad, 0f, 0f, 1f)
uboVS.viewPos = Vec4(0f, 0f, -zoom, 0f)
} else {
uboVS.depth += frameTimer * 0.15f
if (uboVS.depth > 1f)
uboVS.depth = uboVS.depth - 1f
}
uniformBufferVS.mapping { mapped -> uboVS to mapped }
}
override fun prepare() {
super.prepare()
generateQuad()
setupVertexDescriptions()
prepareUniformBuffers()
prepareNoiseTexture(128, 128, 128)
setupDescriptorSetLayout()
preparePipelines()
setupDescriptorPool()
setupDescriptorSet()
buildCommandBuffers()
prepared = true
window.show()
}
override fun render() {
if (!prepared)
return
draw()
if (!paused || camera.updated)
updateUniformBuffers()
}
override fun UIOverlay.onUpdate() {
if (header("Settings"))
if (button("Generate new texture"))
updateNoiseTexture()
}
}