vulkan中vertex buffer的用法

来源:互联网 发布:洗盘和出货的区别知乎 编辑:程序博客网 时间:2024/05/22 14:12
-Vulkan的资源(buffer或者image)都用descriptor表示,vertex buffer也是以descriptor的形式来分配和使用的
下面讲的是如果使用vertex buffer来向shader传递顶点数据
1.准备vertex数据
    const float vb[3][5] = {
        /*      position             texcoord */
        { -1.0f, -1.0f,  0.25f,     0.0f, 0.0f },
        {  1.0f, -1.0f,  0.25f,     1.0f, 0.0f },
        {  0.0f,  1.0f,  1.0f,      0.5f, 1.0f },
    };

2.调用vkCreateBuffer创建VkBuffer(buf),然后用vkAllocateMemory来分配device内存(men)
3.vkMapMemory将device内存map到cpu端(data)
4.memcpy(data, vb, sizeof(vb));
5.调用vkBindBufferMemory(device,buf,mem)将device内存和vkbuffer绑定
6.创建vi,VkPipelineVertexInputStateCreateInfo vi
    demo->vertices.vi.vertexAttributeDescriptionCount = 2;

    demo->vertices.vi.pVertexAttributeDescriptions = demo->vertices.vi_attrs;//vi_attrs是关键

    demo->vertices.vi_attrs[0].binding = VERTEX_BUFFER_BIND_ID;
    demo->vertices.vi_attrs[0].location = 0;
    demo->vertices.vi_attrs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
    demo->vertices.vi_attrs[0].offset = 0;
    demo->vertices.vi_attrs[1].binding = VERTEX_BUFFER_BIND_ID;
    demo->vertices.vi_attrs[1].location = 1;
    demo->vertices.vi_attrs[1].format = VK_FORMAT_R32G32_SFLOAT;
    demo->vertices.vi_attrs[1].offset = sizeof(float) * 3;

7.在create pipeline的时候传入刚创建的vi:pipeline.pVertexInputState = &vi;
8.build cmd的时候,bind之前创建的vertex buffer
    vkCmdBindVertexBuffers(demo->draw_cmd, VERTEX_BUFFER_BIND_ID, 1,&demo->vertices.buf, offsets);
    vkCmdDraw(demo->draw_cmd, 3, 1, 0, 0);
    vkCmdEndRenderPass(demo->draw_cmd);

9.在shader中使用vertex buffer
   vs #version 400
  #extension GL_ARB_separate_shader_objects : enable
  #extension GL_ARB_shading_language_420pack : enable
  layout (location = 0) in vec4 pos;
  layout (location = 1) in vec2 attr;
  layout (location = 0) out vec2 texcoord;
  void main() {
     texcoord = attr;
     gl_Position = pos;
  }
  fs #version 400
  #extension GL_ARB_separate_shader_objects : enable
  #extension GL_ARB_shading_language_420pack : enable
  layout (binding = 0) uniform sampler2D tex;
  layout (location = 0) in vec2 texcoord;
  layout (location = 0) out vec4 uFragColor;
  void main() {
     uFragColor = texture(tex, texcoord);
  }  

  comment:layout(location = attribute index) in vec3 position;

  跟glBindAttribLocation的功能类似,设置position使用哪个属性:

 static const GLfloat verts[3][2] = {
                { -0.5, -0.5 },
                {  0.5, -0.5 },
                {  0,    0.5 }   };
"attribute vec4 pos;\n"//in shader
glBindAttribLocation(program, window->gl.pos, "pos");
glVertexAttribPointer(window->gl.pos, 2, GL_FLOAT, GL_FALSE, 0, verts);
glEnableVertexAttribArray(window->gl.pos);
glDrawArrays()

0 0
原创粉丝点击