创建mvp ubo
· 阅读需 2 分钟
创建过程
- 创建一个uniform buffer
- 查找buffer memory requirements
- 分配、绑定buffer memory
- map buffer memory
- 拷贝mvp data to buffer memory
- 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);