-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.cpp
248 lines (198 loc) · 7.38 KB
/
model.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#include "model.hpp"
#include <tiny_obj_loader.h>
#include <fmt/core.h>
#include <cppitertools/itertools.hpp>
#include <filesystem>
#include <glm/gtx/hash.hpp>
#include <unordered_map>
namespace std {
template <>struct hash<Vertex> {
size_t operator()(Vertex const& vertex) const noexcept {
std::size_t h1{std::hash<glm::vec3>()(vertex.position)};
std::size_t h2{std::hash<glm::vec3>()(vertex.normal)};
std::size_t h3{std::hash<glm::vec2>()(vertex.texCoord)};
return h1 ^ h2 ^ h3;
}
};
}
Model::~Model() {
glDeleteTextures(1, &m_diffuseTexture);
glDeleteBuffers(1, &m_EBO);
glDeleteBuffers(1, &m_VBO);
glDeleteVertexArrays(1, &m_VAO);
}
void Model::computeNormals() {
for (auto& vertex : m_vertices) {
vertex.normal = glm::zero<glm::vec3>();
}
for (const auto offset : iter::range<int>(0, m_indices.size(), 3)) {
Vertex& a{m_vertices.at(m_indices.at(offset + 0))};
Vertex& b{m_vertices.at(m_indices.at(offset + 1))};
Vertex& c{m_vertices.at(m_indices.at(offset + 2))};
const auto edge1{b.position - a.position};
const auto edge2{c.position - b.position};
glm::vec3 normal{glm::cross(edge1, edge2)};
a.normal += normal;
b.normal += normal;
c.normal += normal;
}
for (auto& vertex : m_vertices) {
vertex.normal = glm::normalize(vertex.normal);
}
m_hasNormals = true;
}
void Model::createBuffers() {
glDeleteBuffers(1, &m_EBO);
glDeleteBuffers(1, &m_VBO);
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertices[0]) * m_vertices.size(), m_vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &m_EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_indices[0]) * m_indices.size(), m_indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void Model::loadDiffuseTexture(std::string_view path) {
if (!std::filesystem::exists(path)) return;
glDeleteTextures(1, &m_diffuseTexture);
m_diffuseTexture = abcg::opengl::loadTexture(path);
}
void Model::loadFromFile(std::string_view path, bool standardize) {
auto basePath{std::filesystem::path{path}.parent_path().string() + "/"};
tinyobj::ObjReaderConfig readerConfig;
readerConfig.mtl_search_path = basePath;
tinyobj::ObjReader reader;
if (!reader.ParseFromFile(path.data(), readerConfig)) {
if (!reader.Error().empty()) {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to load model {} ({})", path, reader.Error()))};
}
throw abcg::Exception{
abcg::Exception::Runtime(fmt::format("Failed to load model {}", path))};
}
if (!reader.Warning().empty()) {
fmt::print("\nWarning: {}\n", reader.Warning());
}
const auto& attrib{reader.GetAttrib()};
const auto& shapes{reader.GetShapes()};
const auto& materials{reader.GetMaterials()};
m_vertices.clear();
m_indices.clear();
m_hasNormals = false;
m_hasTexCoords = false;
std::unordered_map<Vertex, GLuint> hash{};
for (const auto& shape : shapes) {
for (const auto offset : iter::range(shape.mesh.indices.size())) {
tinyobj::index_t index{shape.mesh.indices.at(offset)};
std::size_t startIndex{static_cast<size_t>(3 * index.vertex_index)};
float vx{attrib.vertices.at(startIndex + 0)};
float vy{attrib.vertices.at(startIndex + 1)};
float vz{attrib.vertices.at(startIndex + 2)};
float nx{};
float ny{};
float nz{};
if (index.normal_index >= 0) {
m_hasNormals = true;
startIndex = 3 * index.normal_index;
nx = attrib.normals.at(startIndex + 0);
ny = attrib.normals.at(startIndex + 1);
nz = attrib.normals.at(startIndex + 2);
}
float tu{};
float tv{};
if (index.texcoord_index >= 0) {
m_hasTexCoords = true;
startIndex = 2 * index.texcoord_index;
tu = attrib.texcoords.at(startIndex + 0);
tv = attrib.texcoords.at(startIndex + 1);
}
Vertex vertex{};
vertex.position = {vx, vy, vz};
vertex.normal = {nx, ny, nz};
vertex.texCoord = {tu, tv};
if (hash.count(vertex) == 0) {
hash[vertex] = m_vertices.size();
m_vertices.push_back(vertex);
}
m_indices.push_back(hash[vertex]);
}
}
if (!materials.empty()) {
const auto& mat{materials.at(0)};
m_Ka = glm::vec4(mat.ambient[0], mat.ambient[1], mat.ambient[2], 1);
m_Kd = glm::vec4(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2], 1);
m_Ks = glm::vec4(mat.specular[0], mat.specular[1], mat.specular[2], 1);
m_shininess = mat.shininess;
if (!mat.diffuse_texname.empty())
loadDiffuseTexture(basePath + mat.diffuse_texname);
} else {
m_Ka = {0.1f, 0.1f, 0.1f, 1.0f};
m_Kd = {0.7f, 0.7f, 0.7f, 1.0f};
m_Ks = {1.0f, 1.0f, 1.0f, 1.0f};
m_shininess = 25.0f;
}
if (standardize) {
this->standardize();
}
if (!m_hasNormals) {
computeNormals();
}
createBuffers();
}
void Model::render() const {
int numTriangles = getNumTriangles();
glBindVertexArray(m_VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_diffuseTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
GLsizei numIndices = (numTriangles < 0) ? m_indices.size() : numTriangles * 3;
glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
}
void Model::setupVAO(GLuint program) {
glDeleteVertexArrays(1, &m_VAO);
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
GLint positionAttribute{glGetAttribLocation(program, "inPosition")};
if (positionAttribute >= 0) {
glEnableVertexAttribArray(positionAttribute);
glVertexAttribPointer(positionAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
}
GLint normalAttribute{glGetAttribLocation(program, "inNormal")};
if (normalAttribute >= 0) {
glEnableVertexAttribArray(normalAttribute);
GLsizei offset{sizeof(glm::vec3)};
glVertexAttribPointer(normalAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offset));
}
GLint texCoordAttribute{glGetAttribLocation(program, "inTexCoord")};
if (texCoordAttribute >= 0) {
glEnableVertexAttribArray(texCoordAttribute);
GLsizei offset{sizeof(glm::vec3) + sizeof(glm::vec3)};
glVertexAttribPointer(texCoordAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offset));
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Model::standardize() {
glm::vec3 max(std::numeric_limits<float>::lowest());
glm::vec3 min(std::numeric_limits<float>::max());
for (const auto& vertex : m_vertices) {
max.x = std::max(max.x, vertex.position.x);
max.y = std::max(max.y, vertex.position.y);
max.z = std::max(max.z, vertex.position.z);
min.x = std::min(min.x, vertex.position.x);
min.y = std::min(min.y, vertex.position.y);
min.z = std::min(min.z, vertex.position.z);
}
const auto center{(min + max) / 2.0f};
const auto scaling{2.0f / glm::length(max - min)};
for (auto& vertex : m_vertices) {
vertex.position = (vertex.position - center) * scaling;
}
}