CSEngine
Loading...
Searching...
No Matches
DrawableStaticMeshComponent.cpp
1#include "DrawableStaticMeshComponent.h"
2#include "../OGLDef.h"
3#include <vector>
4
5#include <iostream>
6
7using namespace CSE;
8
9COMPONENT_CONSTRUCTOR(DrawableStaticMeshComponent) {}
10
11
12DrawableStaticMeshComponent::~DrawableStaticMeshComponent() = default;
13
14
15void DrawableStaticMeshComponent::Init() {
16}
17
18
19void DrawableStaticMeshComponent::Tick(float elapsedTime) {
20}
21
22
23void DrawableStaticMeshComponent::Exterminate() {
24
25 // const GLuint vertexBuffer = m_meshId.m_vertexBuffer;
26 // const GLuint indexBuffer = m_meshId.m_indexBuffer;
27
28 // glDeleteBuffers(1, &vertexBuffer);
29 // glDeleteBuffers(1, &indexBuffer);
30}
31
32
33bool DrawableStaticMeshComponent::SetMesh(const SISurface& meshSurface) {
34
35 if (m_meshId.m_vertexSize != -1 || m_meshId.m_vertexBuffer != -1) return false;
36
37 if (meshSurface.m_meshId.m_vertexSize != -1
38 || meshSurface.m_meshId.m_vertexBuffer != -1) {
39 m_meshId = meshSurface.m_meshId;
40 return true;
41
42 }
43
44 CreateMeshBuffers(meshSurface);
45
46 return true;
47}
48
49
50void DrawableStaticMeshComponent::CreateMeshBuffers(const SISurface& surface) {
51 // Create the VAO for the VBO
52 GLuint vertexArray;
53 glGenVertexArrays(1, &vertexArray);
54 glBindVertexArray(vertexArray);
55
56 // Create the VBO for the vertices.
57 std::vector<float> vertices;
58 surface.GenerateVertices(vertices);
59 GLuint vertexBuffer;
60 glGenBuffers(1, &vertexBuffer);
61 glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
62 glBufferData(GL_ARRAY_BUFFER,
63 vertices.size() * sizeof(vertices[0]),
64 &vertices[0],
65 GL_STATIC_DRAW);
66
67
68 // Create a new VBO for the indices if needed.
69 int vertexCount = surface.GetVertexCount();
70 int indexCount = surface.GetTriangleIndexCount();
71 GLuint indexBuffer;
72
73
74 // Set exception to not using indices when index count is 0 or lower.
75 if (indexCount < 0) {
76 indexBuffer = 0;
77 indexCount = -1;
78
79 } else {
80 std::vector<GLushort> indices(indexCount);
81 surface.GenerateTriangleIndices(indices);
82 glGenBuffers(1, &indexBuffer);
83 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
84 glBufferData(GL_ELEMENT_ARRAY_BUFFER,
85 indexCount * 3 * sizeof(GLushort),
86 &indices[0],
87 GL_STATIC_DRAW);
88 }
89
90
91 //Pulling data
92 surface.m_meshId.m_vertexBuffer = vertexBuffer;
93 surface.m_meshId.m_vertexSize = vertexCount;
94 surface.m_meshId.m_indexBuffer = indexBuffer;
95 surface.m_meshId.m_indexSize = indexCount;
96 surface.m_meshId.m_vertexArray = vertexArray;
97
98 m_meshId = surface.m_meshId;
99
100 //Unbinding
101 glBindBuffer(GL_ARRAY_BUFFER, 0);
102 glBindVertexArray(0);
103}
104
105SComponent* DrawableStaticMeshComponent::Clone(SGameObject* object) {
106 INIT_COMPONENT_CLONE(DrawableStaticMeshComponent, comp);
107
108 comp->m_meshId = m_meshId;
109 return comp;
110}