Model.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. #include "Model.h"
  2. #include "stb_image.h"
  3. #include <iostream>
  4. #include <fstream>
  5. #include <string>
  6. #include <algorithm>
  7. #include <cmath>
  8. //Prototypes
  9. std::vector<std::string> split(std::string str, std::string sep);
  10. std::string replace(std::string str, std::string toReplace, std::string replacement);
  11. std::string toLower(std::string data);
  12. Model::Model(std::string fileName)
  13. {
  14. std::string dirName = fileName;
  15. if (dirName.rfind("/") != std::string::npos)
  16. dirName = dirName.substr(0, dirName.rfind("/"));
  17. if (dirName.rfind("\\") != std::string::npos)
  18. dirName = dirName.substr(0, dirName.rfind("\\"));
  19. if (fileName == dirName)
  20. dirName = "";
  21. std::ifstream pFile(fileName.c_str());
  22. if (!pFile.is_open())
  23. {
  24. std::cout << "Could not open file " << fileName << std::endl;
  25. return;
  26. }
  27. ObjGroup* currentGroup = new ObjGroup();
  28. currentGroup->materialIndex = -1;
  29. while (!pFile.eof())
  30. {
  31. std::string line;
  32. std::getline(pFile, line);
  33. line = replace(line, "\t", " ");
  34. while (line.find(" ") != std::string::npos)
  35. line = replace(line, " ", " ");
  36. if (line == "")
  37. continue;
  38. if (line[0] == ' ')
  39. line = line.substr(1);
  40. if (line == "")
  41. continue;
  42. if (line[line.length() - 1] == ' ')
  43. line = line.substr(0, line.length() - 1);
  44. if (line == "")
  45. continue;
  46. if (line[0] == '#')
  47. continue;
  48. std::vector<std::string> params = split(line, " ");
  49. params[0] = toLower(params[0]);
  50. if (params[0] == "v")
  51. vertices.push_back(Vec3f((float)atof(params[1].c_str()), (float)atof(params[2].c_str()), (float)atof(params[3].c_str())));
  52. else if (params[0] == "vn")
  53. normals.push_back(Vec3f((float)atof(params[1].c_str()), (float)atof(params[2].c_str()), (float)atof(params[3].c_str())));
  54. else if (params[0] == "vt")
  55. texcoords.push_back(Vec2f((float)atof(params[1].c_str()), (float)atof(params[2].c_str())));
  56. else if (params[0] == "f")
  57. {
  58. for (size_t ii = 4; ii <= params.size(); ii++)
  59. {
  60. Face face;
  61. for (size_t i = ii - 3; i < ii; i++) //magische forlus om van quads triangles te maken ;)
  62. {
  63. VertexIndex vertex;
  64. std::vector<std::string> indices = split(params[i == (ii - 3) ? 1 : i], "/");
  65. if (indices.size() >= 1) //er is een positie
  66. vertex.position = atoi(indices[0].c_str()) - 1;
  67. if (indices.size() == 2) //alleen texture
  68. vertex.texcoord = atoi(indices[1].c_str()) - 1;
  69. if (indices.size() == 3) //v/t/n of v//n
  70. {
  71. if (indices[1] != "")
  72. vertex.texcoord = atoi(indices[1].c_str()) - 1;
  73. vertex.normal = atoi(indices[2].c_str()) - 1;
  74. }
  75. face.vertices.push_back(vertex);
  76. }
  77. currentGroup->faces.push_back(face);
  78. }
  79. }
  80. else if (params[0] == "s")
  81. {//smoothing
  82. }
  83. else if (params[0] == "mtllib")
  84. {
  85. loadMaterialFile(dirName + "/" + params[1], dirName);
  86. }
  87. else if (params[0] == "usemtl")
  88. {
  89. if (currentGroup->faces.size() != 0)
  90. groups.push_back(currentGroup);
  91. currentGroup = new ObjGroup();
  92. currentGroup->materialIndex = -1;
  93. for (size_t i = 0; i < materials.size(); i++)
  94. {
  95. MaterialInfo* info = materials[i];
  96. if (info->name == params[1])
  97. {
  98. currentGroup->materialIndex = i;
  99. break;
  100. }
  101. }
  102. if (currentGroup->materialIndex == -1)
  103. std::cout << "Could not find material name " << params[1] << std::endl;
  104. }
  105. }
  106. groups.push_back(currentGroup);
  107. minVertex = vertices[0];
  108. maxVertex = vertices[0];
  109. for (auto v : vertices)
  110. {
  111. for (int i = 0; i < 3; i++)
  112. {
  113. minVertex[i] = fmin(minVertex[i], v[i]);
  114. maxVertex[i] = fmax(maxVertex[i], v[i]);
  115. }
  116. }
  117. center = (minVertex + maxVertex) / 2.0f;
  118. radius = 0;
  119. for (auto v : vertices)
  120. radius = fmax(radius, (center.x - v.x) * (center.x - v.x) + (center.z - v.z) * (center.z - v.z));
  121. radius = sqrt(radius);
  122. for (ObjGroup *group : groups)
  123. {
  124. Optimise(group);
  125. }
  126. }
  127. void Model::Optimise(ObjGroup *t)
  128. {
  129. for (Face &face : t->faces)
  130. {
  131. for (auto &vertex : face.vertices)
  132. {
  133. t->VertexArray.push_back(Vertex(vertices[vertex.position].x, vertices[vertex.position].y, vertices[vertex.position].z,
  134. normals[vertex.normal].x, normals[vertex.normal].y, normals[vertex.normal].z,
  135. texcoords[vertex.texcoord].x, texcoords[vertex.texcoord].y));
  136. }
  137. }
  138. }
  139. void Model::draw()
  140. {
  141. glEnableClientState(GL_VERTEX_ARRAY);
  142. glEnableClientState(GL_NORMAL_ARRAY);
  143. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  144. for (auto &g : groups)
  145. {
  146. if (materials[g->materialIndex]->hasTexture)
  147. {
  148. glEnable(GL_TEXTURE_2D);
  149. materials[g->materialIndex]->texture->bind();
  150. }
  151. else
  152. {
  153. glDisable(GL_TEXTURE_2D);
  154. float color[4] = { 1, 0, 0, 1 };
  155. if (materials[g->materialIndex]->hasDiffuse)
  156. {
  157. memcpy(color, materials[g->materialIndex]->diffuseColor.v, 3 * sizeof(float));
  158. glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
  159. }
  160. else if (materials[g->materialIndex]->hasAmbient)
  161. {
  162. memcpy(color, materials[g->materialIndex]->ambientColor.v, 3 * sizeof(float));
  163. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
  164. }
  165. else if (materials[g->materialIndex]->hasSpecular)
  166. {
  167. memcpy(color, materials[g->materialIndex]->specularColor.v, 3 * sizeof(float));
  168. glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
  169. }
  170. }
  171. glVertexPointer(3, GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 0);
  172. glNormalPointer(GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 3);
  173. glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), ((float*)g->VertexArray.data()) + 6);
  174. glDrawArrays(GL_TRIANGLES, 0, g->VertexArray.size());
  175. }
  176. glDisableClientState(GL_VERTEX_ARRAY);
  177. glDisableClientState(GL_NORMAL_ARRAY);
  178. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  179. }
  180. void Model::loadMaterialFile(std::string fileName, std::string dirName)
  181. {
  182. std::ifstream pFile(fileName.c_str());
  183. if (!pFile.is_open())
  184. {
  185. std::cout << "Could not open file " << fileName << std::endl;
  186. return;
  187. }
  188. MaterialInfo* currentMaterial = NULL;
  189. while (!pFile.eof())
  190. {
  191. std::string line;
  192. std::getline(pFile, line);
  193. line = replace(line, "\t", " ");
  194. while (line.find(" ") != std::string::npos)
  195. line = replace(line, " ", " ");
  196. if (line == "")
  197. continue;
  198. if (line[0] == ' ')
  199. line = line.substr(1);
  200. if (line == "")
  201. continue;
  202. if (line[line.length() - 1] == ' ')
  203. line = line.substr(0, line.length() - 1);
  204. if (line == "")
  205. continue;
  206. if (line[0] == '#')
  207. continue;
  208. std::vector<std::string> params = split(line, " ");
  209. params[0] = toLower(params[0]);
  210. if (params[0] == "newmtl")
  211. {
  212. if (currentMaterial != NULL)
  213. {
  214. materials.push_back(currentMaterial);
  215. }
  216. currentMaterial = new MaterialInfo();
  217. currentMaterial->name = params[1];
  218. }
  219. else if (params[0] == "map_kd")
  220. {
  221. currentMaterial->hasTexture = true;
  222. currentMaterial->texture = new Texture(dirName + "/" + params[1]);
  223. }
  224. else if (params[0] == "kd")
  225. {
  226. currentMaterial->hasDiffuse = true;
  227. currentMaterial->diffuseColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  228. }
  229. else if (params[0] == "ka")
  230. {
  231. currentMaterial->hasAmbient = true;
  232. currentMaterial->ambientColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  233. }
  234. else if (params[0] == "ks")
  235. {
  236. currentMaterial->hasSpecular = true;
  237. currentMaterial->specularColor = Vec3f(atof(params[1].c_str()), atof(params[2].c_str()), atof(params[3].c_str()));
  238. }
  239. else
  240. std::cout << "Didn't parse " << params[0] << " in material file" << std::endl;
  241. }
  242. if (currentMaterial != NULL)
  243. materials.push_back(currentMaterial);
  244. }
  245. Model::MaterialInfo::MaterialInfo()
  246. {
  247. hasTexture = false;
  248. }
  249. Model::Texture::Texture(const std::string & fileName)
  250. {
  251. int width, height, bpp;
  252. stbi_set_flip_vertically_on_load(true);
  253. unsigned char* imgData = stbi_load(fileName.c_str(), &width, &height, &bpp, 4);
  254. glGenTextures(1, &index);
  255. glBindTexture(GL_TEXTURE_2D, index);
  256. glTexImage2D(GL_TEXTURE_2D,
  257. 0, //level
  258. GL_RGBA, //internal format
  259. width, //width
  260. height, //height
  261. 0, //border
  262. GL_RGBA, //data format
  263. GL_UNSIGNED_BYTE, //data type
  264. imgData); //data
  265. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  266. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  267. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  268. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  269. stbi_image_free(imgData);
  270. }
  271. void Model::Texture::bind()
  272. {
  273. glBindTexture(GL_TEXTURE_2D, index);
  274. }
  275. std::string replace(std::string str, std::string toReplace, std::string replacement)
  276. {
  277. size_t index = 0;
  278. while (true)
  279. {
  280. index = str.find(toReplace, index);
  281. if (index == std::string::npos)
  282. break;
  283. str.replace(index, toReplace.length(), replacement);
  284. ++index;
  285. }
  286. return str;
  287. }
  288. std::vector<std::string> split(std::string str, std::string sep)
  289. {
  290. std::vector<std::string> ret;
  291. size_t index;
  292. while (true)
  293. {
  294. index = str.find(sep);
  295. if (index == std::string::npos)
  296. break;
  297. ret.push_back(str.substr(0, index));
  298. str = str.substr(index + 1);
  299. }
  300. ret.push_back(str);
  301. return ret;
  302. }
  303. inline std::string toLower(std::string data)
  304. {
  305. std::transform(data.begin(), data.end(), data.begin(), ::tolower);
  306. return data;
  307. }
  308. std::map<std::string, std::pair<Model*, int>> Model::cache;
  309. Model* Model::load(const std::string &fileName)
  310. {
  311. if (cache.find(fileName) == cache.end())
  312. cache[fileName] = std::pair<Model*, int>(new Model(fileName), 0);
  313. cache[fileName].second++;
  314. return cache[fileName].first;
  315. }
  316. void Model::unload(Model* model)
  317. {
  318. for (auto m : cache)
  319. {
  320. if (m.second.first == model)
  321. {
  322. m.second.second--;
  323. if (m.second.second == 0)
  324. {
  325. delete m.second.first;
  326. cache.erase(cache.find(m.first));
  327. }
  328. }
  329. }
  330. }
  331. Model::~Model(void)
  332. {
  333. for (auto m : cache)
  334. {
  335. delete m.second.first;
  336. }
  337. }