💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

498 lines
15 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. * Copyright (C) 2017 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper Source Code.
  5. *
  6. * Antkeeper Source Code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper Source Code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "model-loader.hpp"
  20. #include "material-loader.hpp"
  21. #include <fstream>
  22. template <typename T>
  23. inline static void read8(T* result, unsigned char** data)
  24. {
  25. std::uint8_t temp = (*data)[0];
  26. *result = *reinterpret_cast<T*>(&temp);
  27. *data += 1;
  28. }
  29. template <typename T>
  30. inline static void read16(T* result, unsigned char** data)
  31. {
  32. std::uint16_t temp = ((*data)[0] << 0) | ((*data)[1] << 8);
  33. *result = *reinterpret_cast<T*>(&temp);
  34. *data += 2;
  35. }
  36. template <typename T>
  37. inline static void read32(T* result, unsigned char** data)
  38. {
  39. std::uint32_t temp = ((*data)[0] << 0) | ((*data)[1] << 8) | ((*data)[2] << 16) | ((*data)[3] << 24);
  40. *result = *reinterpret_cast<T*>(&temp);
  41. *data += 4;
  42. }
  43. inline static void readString(std::string* result, unsigned char** data)
  44. {
  45. result->resize((*data)[0]);
  46. for (std::size_t i = 0; i < result->size(); ++i)
  47. {
  48. (*result)[i] = (*data)[i + 1];
  49. }
  50. *data += result->size() + 1;
  51. }
  52. ModelLoader::ModelLoader():
  53. materialLoader(nullptr)
  54. {}
  55. ModelLoader::~ModelLoader()
  56. {}
  57. Model* ModelLoader::load(const std::string& filename)
  58. {
  59. // Open file
  60. std::ifstream file(filename.c_str(), std::ifstream::in | std::ifstream::binary | std::ifstream::ate);
  61. if (!file.is_open())
  62. {
  63. std::cerr << std::string("ModelLoader::load(): Failed to open model file \"") << filename << std::string("\"") << std::endl;
  64. return nullptr;
  65. }
  66. // Allocate file data buffer
  67. int filesize = file.tellg();
  68. unsigned char* buffer = new unsigned char[filesize];
  69. // Read file data into buffer
  70. file.seekg(0, file.beg);
  71. file.read(reinterpret_cast<char*>(&buffer[0]), filesize);
  72. unsigned char* bufferOffset = &buffer[0];
  73. // Close file
  74. file.close();
  75. // Allocate model data
  76. ModelData* modelData = new ModelData();
  77. SkeletonData* skeletonData = nullptr;
  78. // Allocate material groups
  79. read32(&modelData->groupCount, &bufferOffset);
  80. modelData->groups = new MaterialGroup[modelData->groupCount];
  81. // Read material groups (and calculate triangle count)
  82. std::uint32_t triangleCount = 0;
  83. for (std::size_t i = 0; i < modelData->groupCount; ++i)
  84. {
  85. MaterialGroup* group = &modelData->groups[i];
  86. readString(&group->materialName, &bufferOffset);
  87. read32(&group->indexOffset, &bufferOffset);
  88. read32(&group->triangleCount, &bufferOffset);
  89. // Read bounds
  90. Vector3 min;
  91. Vector3 max;
  92. read32(&min.x, &bufferOffset);
  93. read32(&min.y, &bufferOffset);
  94. read32(&min.z, &bufferOffset);
  95. read32(&max.x, &bufferOffset);
  96. read32(&max.y, &bufferOffset);
  97. read32(&max.z, &bufferOffset);
  98. group->bounds.setMin(min);
  99. group->bounds.setMax(max);
  100. triangleCount += group->triangleCount;
  101. }
  102. // Read vertex format and count
  103. read32(&modelData->vertexFormat, &bufferOffset);
  104. read32(&modelData->vertexCount, &bufferOffset);
  105. // Read bounds
  106. Vector3 min;
  107. Vector3 max;
  108. read32(&min.x, &bufferOffset);
  109. read32(&min.y, &bufferOffset);
  110. read32(&min.z, &bufferOffset);
  111. read32(&max.x, &bufferOffset);
  112. read32(&max.y, &bufferOffset);
  113. read32(&max.z, &bufferOffset);
  114. modelData->bounds.setMin(min);
  115. modelData->bounds.setMax(max);
  116. // Calculate vertex size
  117. std::uint32_t vertexSize =
  118. 3 // Position
  119. + 3 // Normal
  120. + 2 * ((modelData->vertexFormat & UV) != 0) // UV
  121. + 4 * ((modelData->vertexFormat & TANGENT) != 0) // Tangent
  122. + 4 * ((modelData->vertexFormat & TANGENT) != 0) // Bitangent
  123. + 4 * ((modelData->vertexFormat & WEIGHTS) != 0) // Indices
  124. + 4 * ((modelData->vertexFormat & WEIGHTS) != 0); // Weights
  125. // Allocate vertex data
  126. modelData->vertexData = new float[modelData->vertexCount * vertexSize];
  127. // Read vertex data
  128. float* vertexDataOffset = &modelData->vertexData[0];
  129. for (std::size_t i = 0; i < modelData->vertexCount; ++i)
  130. {
  131. for (std::size_t j = 0; j < vertexSize; ++j)
  132. {
  133. read32(vertexDataOffset, &bufferOffset);
  134. ++vertexDataOffset;
  135. }
  136. }
  137. // Allocate index data
  138. std::uint32_t indexCount = triangleCount * 3;
  139. modelData->indexData = new std::uint32_t[indexCount];
  140. // Read index data
  141. for (std::size_t i = 0; i < indexCount; ++i)
  142. {
  143. read32(&modelData->indexData[i], &bufferOffset);
  144. }
  145. // Read skeleton data
  146. if (modelData->vertexFormat & WEIGHTS)
  147. {
  148. // Allocate skeleton data
  149. skeletonData = new SkeletonData();
  150. skeletonData->animations = nullptr;
  151. // Read bone count
  152. read16(&skeletonData->boneCount, &bufferOffset);
  153. // Allocate bones
  154. skeletonData->bones = new BoneData[skeletonData->boneCount];
  155. // Read bones
  156. for (std::size_t i = 0; i < skeletonData->boneCount; ++i)
  157. {
  158. BoneData* bone = &skeletonData->bones[i];
  159. bone->children = nullptr;
  160. readString(&bone->name, &bufferOffset);
  161. read16(&bone->parent, &bufferOffset);
  162. read16(&bone->childCount, &bufferOffset);
  163. bone->children = new std::uint16_t[bone->childCount];
  164. for (std::size_t j = 0; j < bone->childCount; ++j)
  165. {
  166. read16(&bone->children[j], &bufferOffset);
  167. }
  168. read32(&bone->translation.x, &bufferOffset);
  169. read32(&bone->translation.y, &bufferOffset);
  170. read32(&bone->translation.z, &bufferOffset);
  171. read32(&bone->rotation.w, &bufferOffset);
  172. read32(&bone->rotation.x, &bufferOffset);
  173. read32(&bone->rotation.y, &bufferOffset);
  174. read32(&bone->rotation.z, &bufferOffset);
  175. read32(&bone->length, &bufferOffset);
  176. }
  177. // Read animation count
  178. read16(&skeletonData->animationCount, &bufferOffset);
  179. if (skeletonData->animationCount != 0)
  180. {
  181. // Allocate animations
  182. skeletonData->animations = new AnimationData[skeletonData->animationCount];
  183. // Read animations
  184. for (std::size_t i = 0; i < skeletonData->animationCount; ++i)
  185. {
  186. AnimationData* animation = &skeletonData->animations[i];
  187. // Read animation name
  188. readString(&animation->name, &bufferOffset);
  189. // Read time frame
  190. read32(&animation->startTime, &bufferOffset);
  191. read32(&animation->endTime, &bufferOffset);
  192. // Read channel count
  193. read16(&animation->channelCount, &bufferOffset);
  194. // Allocate channels
  195. animation->channels = new ChannelData[animation->channelCount];
  196. // Read channels
  197. for (std::size_t j = 0; j < animation->channelCount; ++j)
  198. {
  199. ChannelData* channel = &animation->channels[j];
  200. // Read channel ID
  201. read16(&channel->id, &bufferOffset);
  202. // Read keyframe count
  203. read16(&channel->keyFrameCount, &bufferOffset);
  204. // Allocate keyframes
  205. channel->keyFrames = new KeyFrameData[channel->keyFrameCount];
  206. // Read keyframes
  207. for (std::size_t k = 0; k < channel->keyFrameCount; ++k)
  208. {
  209. KeyFrameData* keyFrame = &channel->keyFrames[k];
  210. // Read keyframe time
  211. read32(&keyFrame->time, &bufferOffset);
  212. // Read keyframe translation
  213. read32(&keyFrame->transform.translation.x, &bufferOffset);
  214. read32(&keyFrame->transform.translation.y, &bufferOffset);
  215. read32(&keyFrame->transform.translation.z, &bufferOffset);
  216. // Read keyframe rotation
  217. read32(&keyFrame->transform.rotation.w, &bufferOffset);
  218. read32(&keyFrame->transform.rotation.x, &bufferOffset);
  219. read32(&keyFrame->transform.rotation.y, &bufferOffset);
  220. read32(&keyFrame->transform.rotation.z, &bufferOffset);
  221. // Read keyframe scale
  222. read32(&keyFrame->transform.scale.x, &bufferOffset);
  223. read32(&keyFrame->transform.scale.y, &bufferOffset);
  224. read32(&keyFrame->transform.scale.z, &bufferOffset);
  225. }
  226. }
  227. }
  228. }
  229. }
  230. // Free file data buffer
  231. delete[] buffer;
  232. GLuint vao;
  233. GLuint vbo;
  234. GLuint ibo;
  235. // Generate and bind VAO
  236. glGenVertexArrays(1, &vao);
  237. glBindVertexArray(vao);
  238. // Generate and bind VBO, then upload vertex data
  239. glGenBuffers(1, &vbo);
  240. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  241. glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertexSize * modelData->vertexCount, modelData->vertexData, GL_STATIC_DRAW);
  242. // Setup vertex attribute arrays
  243. std::size_t attribOffset = 0;
  244. std::size_t attribSize = 0;
  245. // Vertex position attribute
  246. attribSize = 3;
  247. glEnableVertexAttribArray(EMERGENT_VERTEX_POSITION);
  248. glVertexAttribPointer(EMERGENT_VERTEX_POSITION, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  249. attribOffset += attribSize;
  250. // Vertex normal attribute
  251. attribSize = 3;
  252. glEnableVertexAttribArray(EMERGENT_VERTEX_NORMAL);
  253. glVertexAttribPointer(EMERGENT_VERTEX_NORMAL, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  254. attribOffset += attribSize;
  255. // Vertex UV attribute
  256. if ((modelData->vertexFormat & UV) != 0)
  257. {
  258. attribSize = 2;
  259. glEnableVertexAttribArray(EMERGENT_VERTEX_TEXCOORD);
  260. glVertexAttribPointer(EMERGENT_VERTEX_TEXCOORD, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  261. attribOffset += attribSize;
  262. }
  263. // Vertex tangent and bitangent attributes
  264. if ((modelData->vertexFormat & TANGENT) != 0)
  265. {
  266. // Tangent
  267. attribSize = 4;
  268. glEnableVertexAttribArray(EMERGENT_VERTEX_TANGENT);
  269. glVertexAttribPointer(EMERGENT_VERTEX_TANGENT, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  270. attribOffset += attribSize;
  271. // Bitangent
  272. attribSize = 4;
  273. glEnableVertexAttribArray(EMERGENT_VERTEX_BITANGENT);
  274. glVertexAttribPointer(EMERGENT_VERTEX_BITANGENT, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  275. attribOffset += attribSize;
  276. }
  277. // Vertex indices and weights attributes
  278. if ((modelData->vertexFormat & TANGENT) != 0)
  279. {
  280. // Indices
  281. attribSize = 4;
  282. glEnableVertexAttribArray(EMERGENT_VERTEX_BONE_INDICES);
  283. glVertexAttribPointer(EMERGENT_VERTEX_BONE_INDICES, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  284. attribOffset += attribSize;
  285. // Weights
  286. attribSize = 4;
  287. glEnableVertexAttribArray(EMERGENT_VERTEX_BONE_WEIGHTS);
  288. glVertexAttribPointer(EMERGENT_VERTEX_BONE_WEIGHTS, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float));
  289. attribOffset += attribSize;
  290. }
  291. // Generate and bind IBO, then upload index data
  292. glGenBuffers(1, &ibo);
  293. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  294. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(std::uint32_t) * indexCount, modelData->indexData, GL_STATIC_DRAW);
  295. // Delete vertex and index data
  296. delete[] modelData->vertexData;
  297. delete[] modelData->indexData;
  298. // Allocate model
  299. Model* model = new Model();
  300. model->setVAO(vao);
  301. model->setVBO(vbo);
  302. model->setIBO(ibo);
  303. model->setVertexFormat(modelData->vertexFormat);
  304. model->setBounds(modelData->bounds);
  305. // Create model groups
  306. for (std::size_t i = 0; i < modelData->groupCount; ++i)
  307. {
  308. ModelLoader::MaterialGroup* modelDataGroup = &modelData->groups[i];
  309. // Allocate model group
  310. Model::Group* modelGroup = new Model::Group();
  311. // Set model group name
  312. modelGroup->name = modelDataGroup->materialName;
  313. // Load material
  314. std::string materialFilename = std::string("data/materials/") + modelDataGroup->materialName + std::string(".mtl");
  315. if (materialLoader != nullptr)
  316. {
  317. modelGroup->material = materialLoader->load(materialFilename);
  318. if (!modelGroup->material)
  319. {
  320. std::cerr << std::string("ModelLoader::load(): Failed to load material file \"") << materialFilename << std::string("\" for model file \"") << filename << std::string("\"") << std::endl;
  321. }
  322. }
  323. else
  324. {
  325. modelGroup->material = nullptr;
  326. std::cerr << std::string("ModelLoader::load(): No valid material loader, material file \"") << materialFilename << std::string("\" not loaded") << std::endl;
  327. }
  328. // Setup model group geometry
  329. modelGroup->indexOffset = modelDataGroup->indexOffset;
  330. modelGroup->triangleCount = modelDataGroup->triangleCount;
  331. modelGroup->bounds = modelDataGroup->bounds;
  332. // Add model group to model
  333. model->addGroup(modelGroup);
  334. }
  335. // Create skeleton
  336. if (skeletonData != nullptr)
  337. {
  338. // Allocate skeleton
  339. Skeleton* skeleton = new Skeleton();
  340. // Construct bone hierarchy from bone data
  341. constructBoneHierarchy(skeleton->getRootBone(), skeletonData->bones, 0);
  342. // Calculate bind pose
  343. skeleton->calculateBindPose();
  344. // Create animations
  345. for (std::size_t i = 0; i < skeletonData->animationCount; ++i)
  346. {
  347. AnimationData* animationData = &skeletonData->animations[i];
  348. Animation* animation = new Animation();
  349. animation->setName(animationData->name);
  350. animation->setTimeFrame(animationData->startTime, animationData->endTime);
  351. for (std::size_t j = 0; j < animationData->channelCount; ++j)
  352. {
  353. ChannelData* channelData = &animationData->channels[j];
  354. AnimationChannel* channel = animation->createChannel(channelData->id);
  355. for (std::size_t k = 0; k < channelData->keyFrameCount; ++k)
  356. {
  357. KeyFrameData* keyFrameData = &channelData->keyFrames[k];
  358. KeyFrame* keyFrame = channel->insertKeyFrame(keyFrameData->time);
  359. keyFrame->setTransform(keyFrameData->transform);
  360. }
  361. }
  362. // Add animation to skeleton
  363. skeleton->addAnimation(animation);
  364. }
  365. // Add skeleton to model
  366. model->setSkeleton(skeleton);
  367. }
  368. // Delete model data groups
  369. delete[] modelData->groups;
  370. // Delete model data
  371. delete modelData;
  372. // Delete skeleton data
  373. if (skeletonData != nullptr)
  374. {
  375. for (std::size_t i = 0; i < skeletonData->boneCount; ++i)
  376. {
  377. delete[] skeletonData->bones[i].children;
  378. }
  379. delete[] skeletonData->bones;
  380. for (std::size_t i = 0; i < skeletonData->animationCount; ++i)
  381. {
  382. AnimationData* animation = &skeletonData->animations[i];
  383. for (std::size_t j = 0; j < animation->channelCount; ++j)
  384. {
  385. delete[] animation->channels[j].keyFrames;
  386. }
  387. delete[] animation->channels;
  388. }
  389. delete[] skeletonData->animations;
  390. delete skeletonData;
  391. }
  392. return model;
  393. }
  394. void ModelLoader::setMaterialLoader(MaterialLoader* materialLoader)
  395. {
  396. this->materialLoader = materialLoader;
  397. }
  398. void ModelLoader::constructBoneHierarchy(Bone* bone, const BoneData* data, std::uint16_t index)
  399. {
  400. bone->setName(data[index].name);
  401. Transform transform;
  402. transform.translation = data[index].translation;
  403. transform.rotation = data[index].rotation;
  404. transform.scale = Vector3(1.0f);
  405. bone->setRelativeTransform(transform);
  406. bone->setLength(data[index].length);
  407. for (std::uint16_t i = 0; i < data[index].childCount; ++i)
  408. {
  409. constructBoneHierarchy(bone->createChild(), data, data[index].children[i]);
  410. }
  411. }