Model.cpp 8.7 KB

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