comparison src/zamikongine/shader.nim @ 19:b55d6ecde79d

did: introduce scene graph, meshs and generic vertex buffers
author Sam <sam@basx.dev>
date Mon, 09 Jan 2023 11:04:19 +0700
parents src/shader.nim@b40466fa446a
children b45a5d338cd0
comparison
equal deleted inserted replaced
18:90e117952f74 19:b55d6ecde79d
1 import std/strutils
2 import std/tables
3
4 import ./vulkan_helpers
5 import ./vulkan
6 import ./vertex
7 import ./glslang/glslang
8
9 type
10 ShaderProgram* = object
11 entryPoint*: string
12 programType*: VkShaderStageFlagBits
13 shader*: VkPipelineShaderStageCreateInfo
14
15 proc initShaderProgram*(device: VkDevice, programType: VkShaderStageFlagBits, shader: string, entryPoint: string="main"): ShaderProgram =
16 result.entryPoint = entryPoint
17 result.programType = programType
18
19 const VK_GLSL_MAP = {
20 VK_SHADER_STAGE_VERTEX_BIT: GLSLANG_STAGE_VERTEX,
21 VK_SHADER_STAGE_FRAGMENT_BIT: GLSLANG_STAGE_FRAGMENT,
22 }.toTable()
23 var code = compileGLSLToSPIRV(VK_GLSL_MAP[result.programType], shader, "<memory-shader>")
24 var createInfo = VkShaderModuleCreateInfo(
25 sType: VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
26 codeSize: uint(code.len * sizeof(uint32)),
27 pCode: if code.len > 0: addr(code[0]) else: nil,
28 )
29 var shaderModule: VkShaderModule
30 checkVkResult vkCreateShaderModule(device, addr(createInfo), nil, addr(shaderModule))
31
32 result.shader = VkPipelineShaderStageCreateInfo(
33 sType: VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
34 stage: programType,
35 module: shaderModule,
36 pName: cstring(result.entryPoint), # entry point for shader
37 )
38
39 func generateVertexShaderCode*[T](entryPoint, positionAttrName, colorAttrName: static string): string =
40 var lines: seq[string]
41 lines.add "#version 450"
42 lines.add generateGLSLDeclarations[T]()
43 lines.add "layout(location = 0) out vec3 fragColor;"
44 lines.add "void " & entryPoint & "() {"
45
46 for name, value in T().fieldPairs:
47 when typeof(value) is VertexAttribute and name == positionAttrName:
48 lines.add " gl_Position = vec4(" & name & ", 0.0, 1.0);"
49 when typeof(value) is VertexAttribute and name == colorAttrName:
50 lines.add " fragColor = " & name & ";"
51 lines.add "}"
52 return lines.join("\n")
53
54 func generateFragmentShaderCode*[T](entryPoint: static string): string =
55 var lines: seq[string]
56 lines.add "#version 450"
57 lines.add "layout(location = 0) in vec3 fragColor;"
58 lines.add "layout(location = 0) out vec4 outColor;"
59 lines.add "void " & entryPoint & "() {"
60 lines.add " outColor = vec4(fragColor, 1.0);"
61 lines.add "}"
62
63 return lines.join("\n")