forked from Dominaezzz/kgl-vulkan-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.kt
382 lines (333 loc) · 13.8 KB
/
Main.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
import com.kgl.vulkan.Vk
import com.kgl.vulkan.enums.*
import com.kgl.vulkan.handles.*
import com.kgl.vulkan.utils.VkFlag
import com.kgl.vulkan.utils.contains
import com.kgl.vulkan.utils.or
import kotlinx.io.core.*
import sample.utils.BaseApplication
import sample.utils.readAllBytes
fun main(args: Array<String>) {
TriangleApplication().use {
it.mainLoop()
}
}
const val RESOURCE_DIR = "."
data class Vec2(val x: Float, val y: Float)
data class Vec3(val x: Float, val y: Float, val z: Float)
data class Vertex(val pos: Vec2, val color: Vec3)
class TriangleApplication : BaseApplication() {
private val vertShaderModule: ShaderModule
private val fragShaderModule: ShaderModule
private val pipelineLayout: PipelineLayout
private val renderPass: RenderPass
private val vertexBuffer: Buffer
private val vertexBufferMemory: DeviceMemory
private val indexBuffer: Buffer
private val indexBufferMemory: DeviceMemory
private lateinit var swapchainFramebuffers: List<Framebuffer>
private lateinit var graphicsPipeline: Pipeline
private lateinit var commandBuffers: List<CommandBuffer>
private val vertices = arrayOf(
Vertex(Vec2(-0.5f, -0.5f), Vec3(1.0f, 1.0f, 1.0f)),
Vertex(Vec2(0.5f, -0.5f), Vec3(1.0f, 0.0f, 0.0f)),
Vertex(Vec2(0.5f, 0.5f), Vec3(0.0f, 1.0f, 0.0f)),
Vertex(Vec2(-0.5f, 0.5f), Vec3(0.0f, 0.0f, 1.0f))
)
private val indices = ushortArrayOf(
0u, 1u, 2u,
2u, 3u, 0u
)
init {
val vertShaderCode = readAllBytes("$RESOURCE_DIR/shaders/shader.vert.spv")
val fragShaderCode = readAllBytes("$RESOURCE_DIR/shaders/shader.frag.spv")
vertShaderModule = device.createShaderModule(vertShaderCode.asUByteArray())
fragShaderModule = device.createShaderModule(fragShaderCode.asUByteArray())
pipelineLayout = device.createPipelineLayout()
renderPass = device.createRenderPass {
attachments {
description {
format = surfaceFormat.format
samples = SampleCount.`1`
loadOp = AttachmentLoadOp.CLEAR
storeOp = AttachmentStoreOp.STORE
stencilLoadOp = AttachmentLoadOp.DONT_CARE
stencilStoreOp = AttachmentStoreOp.DONT_CARE
initialLayout = ImageLayout.UNDEFINED
finalLayout = ImageLayout.PRESENT_SRC_KHR
}
}
subpasses {
description {
pipelineBindPoint = PipelineBindPoint.GRAPHICS
colorAttachments {
reference {
attachment = 0U
layout = ImageLayout.COLOR_ATTACHMENT_OPTIMAL
}
}
}
}
dependencies {
dependency {
srcSubpass = Vk.SUBPASS_EXTERNAL
dstSubpass = 0U
srcStageMask = PipelineStage.COLOR_ATTACHMENT_OUTPUT
srcAccessMask = null
dstStageMask = PipelineStage.COLOR_ATTACHMENT_OUTPUT
dstAccessMask = Access.COLOR_ATTACHMENT_READ or Access.COLOR_ATTACHMENT_WRITE
}
}
}
vertexBuffer = device.createBuffer {
size = vertices.size.toULong() * 4u * (2u + 3u)
usage = BufferUsage.VERTEX_BUFFER or BufferUsage.TRANSFER_DST
sharingMode = SharingMode.EXCLUSIVE
}
vertexBufferMemory = device.allocateMemory {
val memRequirements = vertexBuffer.memoryRequirements
allocationSize = memRequirements.size
memoryTypeIndex = findMemoryType(
memRequirements.memoryTypeBits, MemoryProperty.DEVICE_LOCAL
)
}
vertexBuffer.bindMemory(vertexBufferMemory, 0u)
indexBuffer = device.createBuffer {
size = indices.size.toULong() * 4u * (2u + 3u)
usage = BufferUsage.INDEX_BUFFER or BufferUsage.TRANSFER_DST
sharingMode = SharingMode.EXCLUSIVE
}
indexBufferMemory = device.allocateMemory {
val memRequirements = indexBuffer.memoryRequirements
allocationSize = memRequirements.size
memoryTypeIndex = findMemoryType(
memRequirements.memoryTypeBits, MemoryProperty.DEVICE_LOCAL
)
}
indexBuffer.bindMemory(indexBufferMemory, 0u)
stagingBuffer(vertices.size.toULong() * 4u * (2u + 3u)) { stagingBuffer, data ->
for (vertex in vertices) {
data.writeFloat(vertex.pos.x, ByteOrder.nativeOrder())
data.writeFloat(vertex.pos.y, ByteOrder.nativeOrder())
data.writeFloat(vertex.color.x, ByteOrder.nativeOrder())
data.writeFloat(vertex.color.y, ByteOrder.nativeOrder())
data.writeFloat(vertex.color.z, ByteOrder.nativeOrder())
}
val cmdBuf = commandPool.allocate(CommandBufferLevel.PRIMARY, 1U).single()
with(cmdBuf) {
begin { flags = CommandBufferUsage.ONE_TIME_SUBMIT }
copyBuffer(stagingBuffer, vertexBuffer) {
copy {
srcOffset = 0U
dstOffset = 0U
size = stagingBuffer.size
}
}
end()
}
graphicsQueue.submit(null) { info(null, listOf(cmdBuf)) }
graphicsQueue.waitIdle()
cmdBuf.close()
}
stagingBuffer(indices.size.toULong() * UShort.SIZE_BYTES.toUInt()) { stagingBuffer, data ->
when (ByteOrder.nativeOrder()) {
ByteOrder.BIG_ENDIAN -> data.writeFully(indices.asShortArray())
ByteOrder.LITTLE_ENDIAN -> data.writeFullyLittleEndian(indices.asShortArray())
}
val cmdBuf = commandPool.allocate(CommandBufferLevel.PRIMARY, 1U).single()
with(cmdBuf) {
begin { flags = CommandBufferUsage.ONE_TIME_SUBMIT }
copyBuffer(stagingBuffer, indexBuffer) {
copy {
srcOffset = 0U
dstOffset = 0U
size = stagingBuffer.size
}
}
end()
}
graphicsQueue.submit(null) { info(null, listOf(cmdBuf)) }
graphicsQueue.waitIdle()
cmdBuf.close()
}
onRecreateSwapchain(swapchain)
}
private inline fun stagingBuffer(size: ULong, block: (Buffer, IoBuffer) -> Unit) {
val stagingBuffer = device.createBuffer {
this.size = size
usage = BufferUsage.TRANSFER_SRC
sharingMode = SharingMode.EXCLUSIVE
}
val memory = device.allocateMemory {
val memRequirements = stagingBuffer.memoryRequirements
allocationSize = memRequirements.size
memoryTypeIndex = findMemoryType(
memRequirements.memoryTypeBits,
MemoryProperty.HOST_VISIBLE or MemoryProperty.HOST_COHERENT
)
}
stagingBuffer.bindMemory(memory, 0UL)
try {
block(stagingBuffer, memory.map(0u, memory.size))
} finally {
memory.unmap()
stagingBuffer.close()
memory.close()
}
}
private fun findMemoryType(typeFilter: UInt, properties: VkFlag<MemoryProperty>): UInt {
val memoryProperties = device.physicalDevice.memoryProperties
for ((index, type) in memoryProperties.memoryTypes.withIndex()) {
if (typeFilter and (1u shl index) != 0u && properties in type.propertyFlags) {
return index.toUInt()
}
}
throw Exception("Failed to find suitable memory type!")
}
override fun onRecreateSwapchain(swapchain: SwapchainKHR) {
val (swapchainWidth, swapchainHeight) = swapchain.imageExtent
graphicsPipeline = device.createGraphicsPipelines {
pipeline(pipelineLayout, renderPass) {
subpass = 0U
basePipelineIndex = -1
stages {
stage(ShaderStage.VERTEX, vertShaderModule) {
name = "main"
}
stage(ShaderStage.FRAGMENT, fragShaderModule) {
name = "main"
}
}
vertexInputState {
vertexBindingDescriptions {
description {
binding = 0u
stride = 4u * (2u + 3u)
inputRate = VertexInputRate.VERTEX
}
}
vertexAttributeDescriptions {
description(0U, 0U, Format.R32G32_SFLOAT, 0u)
description(1U, 0U, Format.R32G32B32_SFLOAT, 8u)
}
}
inputAssemblyState {
topology = PrimitiveTopology.TRIANGLE_LIST
primitiveRestartEnable = false
}
viewportState {
viewports {
viewport {
x = 0f
y = 0f
width = swapchainWidth.toInt().toFloat()
height = swapchainHeight.toInt().toFloat()
minDepth = 0f
maxDepth = 1f
}
}
scissors {
rect2D {
offset(0, 0)
extent(swapchainWidth, swapchainHeight)
}
}
}
rasterizationState {
depthClampEnable = false
rasterizerDiscardEnable = false
polygonMode = PolygonMode.FILL
lineWidth = 1.0f
cullMode = CullMode.BACK
frontFace = FrontFace.CLOCKWISE
depthBiasEnable = false
depthBiasConstantFactor = 0.0f
depthBiasClamp = 0.0f
depthBiasSlopeFactor = 0.0f
}
multisampleState {
sampleShadingEnable = false
rasterizationSamples = SampleCount.`1`
minSampleShading = 1.0f
alphaToCoverageEnable = false
alphaToOneEnable = false
}
colorBlendState {
logicOpEnable = false
attachments {
state {
colorWriteMask = ColorComponent.R or ColorComponent.B or ColorComponent.G or ColorComponent.A
blendEnable = true
srcColorBlendFactor = BlendFactor.SRC_ALPHA
dstColorBlendFactor = BlendFactor.ONE_MINUS_SRC_ALPHA
colorBlendOp = BlendOp.ADD
srcAlphaBlendFactor = BlendFactor.ONE
dstAlphaBlendFactor = BlendFactor.ZERO
alphaBlendOp = BlendOp.ADD
}
}
blendConstants(0f, 0f, 0f, 0f)
}
}
}.single()
swapchainFramebuffers = swapchainImageViews.map { imageView ->
device.createFramebuffer(renderPass, listOf(imageView)) {
width = swapchainWidth
height = swapchainHeight
layers = 1u
}
}
commandBuffers = commandPool.allocate(CommandBufferLevel.PRIMARY, swapchainFramebuffers.size.toUInt())
commandBuffers.forEachIndexed { index, commandBuffer ->
with(commandBuffer) {
begin { flags = CommandBufferUsage.SIMULTANEOUS_USE }
beginRenderPass(renderPass, swapchainFramebuffers[index], SubpassContents.INLINE) {
clearValues {
clearValue {
color(0f, 0f, 0f, 1f)
}
}
renderArea {
offset(0, 0)
extent(swapchainWidth, swapchainHeight)
}
}
bindPipeline(PipelineBindPoint.GRAPHICS, graphicsPipeline)
bindVertexBuffers(0u, listOf(vertexBuffer to 0uL))
bindIndexBuffer(indexBuffer, 0u, IndexType.UINT16)
drawIndexed(indices.size.toUInt(), 1u, 0u, 0, 0u)
endRenderPass()
end()
}
}
}
override fun onDestroySwapchain() {
swapchainFramebuffers.forEach { it.close() }
graphicsPipeline.close()
commandPool.free(commandBuffers)
}
override fun renderFrame(imageIndex: Int) {
device.waitForFences(listOf(inFlightFences[currentFrame]), true)
device.resetFences(listOf(inFlightFences[currentFrame]))
graphicsQueue.submit(inFlightFences[currentFrame]) {
info(
listOf(imageAvailableSemaphores[currentFrame] to PipelineStage.COLOR_ATTACHMENT_OUTPUT),
listOf(commandBuffers[imageIndex]),
listOf(renderFinishedSemaphores[currentFrame])
)
}
}
override fun close() {
device.waitIdle()
onDestroySwapchain()
indexBuffer.close()
indexBuffer.memory?.close()
vertexBuffer.close()
vertexBuffer.memory?.close()
renderPass.close()
pipelineLayout.close()
fragShaderModule.close()
vertShaderModule.close()
super.close()
}
}