-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.cpp
More file actions
58 lines (48 loc) · 1.89 KB
/
Model.cpp
File metadata and controls
58 lines (48 loc) · 1.89 KB
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
#include "Model.hpp"
#include <cassert>
#include <cstring>
namespace engine {
std::vector<VkVertexInputBindingDescription> Model::Vertex::getBindingDescriptions() {
std::vector<VkVertexInputBindingDescription> bindingDescriptions(1);
bindingDescriptions[0].binding = 0;
bindingDescriptions[0].stride = sizeof(Vertex);
bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescriptions;
}
std::vector<VkVertexInputAttributeDescription> Model::Vertex::getAttributeDescriptions() {
return {
{0,0,VK_FORMAT_R32G32_SFLOAT,offsetof(Vertex, position)},
{1,0,VK_FORMAT_R32G32B32_SFLOAT,offsetof(Vertex, color)}
};
}
Model::Model(Device& device, const std::vector<Vertex>& vertices) : m_device{ device } {
createVertexBuffers(vertices);
}
Model::~Model() {
vkDestroyBuffer(m_device.device(), vertexBuffer, nullptr);
vkFreeMemory(m_device.device(), vertexBufferMemory, nullptr);
}
void Model::createVertexBuffers(const std::vector<Vertex>& vertices) {
vertexCount = static_cast<uint32_t>(vertices.size());
assert(vertexCount >= 3 && "Vertex count must be at least 3");
VkDeviceSize bufferSize = sizeof(vertices[0]) * vertexCount;
m_device.createBuffer(
bufferSize,
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
vertexBuffer,
vertexBufferMemory);
void* data;
vkMapMemory(m_device.device(), vertexBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, vertices.data(), static_cast<uint32_t>(bufferSize));
vkUnmapMemory(m_device.device(), vertexBufferMemory);
}
void Model::bind(VkCommandBuffer commandBuffer) {
VkBuffer buffers[] = { vertexBuffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(commandBuffer, 0, 1, buffers, offsets);
}
void Model::draw(VkCommandBuffer commandBuffer) {
vkCmdDraw(commandBuffer, vertexCount, 1, 0, 0);
}
} // namespace engine