跳到主要内容

创建mvp ubo

· 阅读需 2 分钟
苏明才
Vulkan驱动填坑狮

创建过程

  1. 创建一个uniform buffer
  2. 查找buffer memory requirements
  3. 分配、绑定buffer memory
  4. map buffer memory
  5. 拷贝mvp data to buffer memory
  6. unmap buffer memory

示例代码

glm::mat4 projection = glm::perspective(glm::radians(45.0f), 1.0f, 0.1f, 100.0f);
glm::mat4 view = glm::lookAt(
glm::vec3(-5, 3, -10), // 相机在世界坐标系中的位置
glm::vec3(0, 0, 0), // 看向的目标位置
glm::vec3(0, -1, 0) // 相机up方向向量
);
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 clip = glm::mat4(1.0f, 0.0f, 0.0f, 0.0f,
0.0f,-1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.5f, 0.0f,
0.0f, 0.0f, 0.5f, 1.0f);
glm::mat4 mvp = clip * projection * view * model;

VkBuffer ubo;
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.pNext = NULL;
buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
buf_info.size = sizeof(mvp);
buf_info.queueFamilyIndexCount = 0;
buf_info.pQueueFamilyIndices = NULL;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
buf_info.flags = 0;
vkCreateBuffer(device, &buf_info, NULL, &ubo);

VkMemoryRequirements mem_reqs;
vkGetBufferMemoryRequirements(device, ubo, &mem_reqs);

VkDeviceMemory mem;
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.pNext = NULL;
alloc_info.memoryTypeIndex = 0;
alloc_info.allocationSize = mem_reqs.size;
vkAllocateMemory(device, &alloc_info, NULL, &mem);

vkBindBufferMemory(device, ubo, mem, 0);

uint8_t *pData;
vkMapMemory(device, mem, 0, mem_reqs.size, 0, (void **)&pData);

memcpy(pData, &mvp, sizeof(mvp));

vkUnmapMemory(device, mem);