MMDImporter.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #ifndef ASSIMP_BUILD_NO_MMD_IMPORTER
  35. #include "AssetLib/MMD/MMDImporter.h"
  36. #include "AssetLib/MMD/MMDPmdParser.h"
  37. #include "AssetLib/MMD/MMDPmxParser.h"
  38. #include "AssetLib/MMD/MMDVmdParser.h"
  39. #include "PostProcessing/ConvertToLHProcess.h"
  40. #include <assimp/DefaultIOSystem.h>
  41. #include <assimp/ai_assert.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/Importer.hpp>
  44. #include <fstream>
  45. #include <iomanip>
  46. #include <memory>
  47. static const aiImporterDesc desc = { "MMD Importer",
  48. "",
  49. "",
  50. "surfaces supported?",
  51. aiImporterFlags_SupportTextFlavour,
  52. 0,
  53. 0,
  54. 0,
  55. 0,
  56. "pmx" };
  57. namespace Assimp {
  58. using namespace std;
  59. // ------------------------------------------------------------------------------------------------
  60. // Default constructor
  61. MMDImporter::MMDImporter() :
  62. m_Buffer(),
  63. m_strAbsPath("") {
  64. DefaultIOSystem io;
  65. m_strAbsPath = io.getOsSeparator();
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Destructor.
  69. MMDImporter::~MMDImporter() {
  70. // empty
  71. }
  72. // ------------------------------------------------------------------------------------------------
  73. // Returns true, if file is an pmx file.
  74. bool MMDImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler,
  75. bool checkSig) const {
  76. if (!checkSig) {
  77. return SimpleExtensionCheck(pFile, "pmx");
  78. } else {
  79. // Check file Header
  80. static const char *pTokens[] = { "PMX " };
  81. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, pTokens, 1);
  82. }
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. const aiImporterDesc *MMDImporter::GetInfo() const {
  86. return &desc;
  87. }
  88. // ------------------------------------------------------------------------------------------------
  89. // MMD import implementation
  90. void MMDImporter::InternReadFile(const std::string &file, aiScene *pScene,
  91. IOSystem * /*pIOHandler*/) {
  92. // Read file by istream
  93. std::filebuf fb;
  94. if (!fb.open(file, std::ios::in | std::ios::binary)) {
  95. throw DeadlyImportError("Failed to open file " + file + ".");
  96. }
  97. std::istream fileStream(&fb);
  98. // Get the file-size and validate it, throwing an exception when fails
  99. fileStream.seekg(0, fileStream.end);
  100. size_t fileSize = static_cast<size_t>(fileStream.tellg());
  101. fileStream.seekg(0, fileStream.beg);
  102. if (fileSize < sizeof(pmx::PmxModel)) {
  103. throw DeadlyImportError(file + " is too small.");
  104. }
  105. pmx::PmxModel model;
  106. model.Read(&fileStream);
  107. CreateDataFromImport(&model, pScene);
  108. }
  109. // ------------------------------------------------------------------------------------------------
  110. void MMDImporter::CreateDataFromImport(const pmx::PmxModel *pModel,
  111. aiScene *pScene) {
  112. if (pModel == nullptr) {
  113. return;
  114. }
  115. aiNode *pNode = new aiNode;
  116. if (!pModel->model_name.empty()) {
  117. pNode->mName.Set(pModel->model_name);
  118. }
  119. pScene->mRootNode = pNode;
  120. pNode = new aiNode;
  121. pScene->mRootNode->addChildren(1, &pNode);
  122. pNode->mName.Set(string(pModel->model_name) + string("_mesh"));
  123. // split mesh by materials
  124. pNode->mNumMeshes = pModel->material_count;
  125. pNode->mMeshes = new unsigned int[pNode->mNumMeshes];
  126. for (unsigned int index = 0; index < pNode->mNumMeshes; index++) {
  127. pNode->mMeshes[index] = index;
  128. }
  129. pScene->mNumMeshes = pModel->material_count;
  130. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  131. for (unsigned int i = 0, indexStart = 0; i < pScene->mNumMeshes; i++) {
  132. const int indexCount = pModel->materials[i].index_count;
  133. pScene->mMeshes[i] = CreateMesh(pModel, indexStart, indexCount);
  134. pScene->mMeshes[i]->mName = pModel->materials[i].material_name;
  135. pScene->mMeshes[i]->mMaterialIndex = i;
  136. indexStart += indexCount;
  137. }
  138. // create node hierarchy for bone position
  139. std::unique_ptr<aiNode *[]> ppNode(new aiNode *[pModel->bone_count]);
  140. for (auto i = 0; i < pModel->bone_count; i++) {
  141. ppNode[i] = new aiNode(pModel->bones[i].bone_name);
  142. }
  143. for (auto i = 0; i < pModel->bone_count; i++) {
  144. const pmx::PmxBone &bone = pModel->bones[i];
  145. if (bone.parent_index < 0) {
  146. pScene->mRootNode->addChildren(1, ppNode.get() + i);
  147. } else {
  148. ppNode[bone.parent_index]->addChildren(1, ppNode.get() + i);
  149. aiVector3D v3 = aiVector3D(
  150. bone.position[0] - pModel->bones[bone.parent_index].position[0],
  151. bone.position[1] - pModel->bones[bone.parent_index].position[1],
  152. bone.position[2] - pModel->bones[bone.parent_index].position[2]);
  153. aiMatrix4x4::Translation(v3, ppNode[i]->mTransformation);
  154. }
  155. }
  156. // create materials
  157. pScene->mNumMaterials = pModel->material_count;
  158. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  159. for (unsigned int i = 0; i < pScene->mNumMaterials; i++) {
  160. pScene->mMaterials[i] = CreateMaterial(&pModel->materials[i], pModel);
  161. }
  162. // Convert everything to OpenGL space
  163. MakeLeftHandedProcess convertProcess;
  164. convertProcess.Execute(pScene);
  165. FlipUVsProcess uvFlipper;
  166. uvFlipper.Execute(pScene);
  167. FlipWindingOrderProcess windingFlipper;
  168. windingFlipper.Execute(pScene);
  169. }
  170. // ------------------------------------------------------------------------------------------------
  171. aiMesh *MMDImporter::CreateMesh(const pmx::PmxModel *pModel,
  172. const int indexStart, const int indexCount) {
  173. aiMesh *pMesh = new aiMesh;
  174. pMesh->mNumVertices = indexCount;
  175. pMesh->mNumFaces = indexCount / 3;
  176. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  177. const int numIndices = 3; // triangular face
  178. for (unsigned int index = 0; index < pMesh->mNumFaces; index++) {
  179. pMesh->mFaces[index].mNumIndices = numIndices;
  180. unsigned int *indices = new unsigned int[numIndices];
  181. indices[0] = numIndices * index;
  182. indices[1] = numIndices * index + 1;
  183. indices[2] = numIndices * index + 2;
  184. pMesh->mFaces[index].mIndices = indices;
  185. }
  186. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  187. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  188. pMesh->mTextureCoords[0] = new aiVector3D[pMesh->mNumVertices];
  189. pMesh->mNumUVComponents[0] = 2;
  190. // additional UVs
  191. for (int i = 1; i <= pModel->setting.uv; i++) {
  192. pMesh->mTextureCoords[i] = new aiVector3D[pMesh->mNumVertices];
  193. pMesh->mNumUVComponents[i] = 4;
  194. }
  195. map<int, vector<aiVertexWeight>> bone_vertex_map;
  196. // fill in contents and create bones
  197. for (int index = 0; index < indexCount; index++) {
  198. const pmx::PmxVertex *v =
  199. &pModel->vertices[pModel->indices[indexStart + index]];
  200. const float *position = v->position;
  201. pMesh->mVertices[index].Set(position[0], position[1], position[2]);
  202. const float *normal = v->normal;
  203. pMesh->mNormals[index].Set(normal[0], normal[1], normal[2]);
  204. pMesh->mTextureCoords[0][index].x = v->uv[0];
  205. pMesh->mTextureCoords[0][index].y = v->uv[1];
  206. for (int i = 1; i <= pModel->setting.uv; i++) {
  207. // TODO: wrong here? use quaternion transform?
  208. pMesh->mTextureCoords[i][index].x = v->uva[i][0];
  209. pMesh->mTextureCoords[i][index].y = v->uva[i][1];
  210. }
  211. // handle bone map
  212. const auto vsBDEF1_ptr =
  213. dynamic_cast<pmx::PmxVertexSkinningBDEF1 *>(v->skinning.get());
  214. const auto vsBDEF2_ptr =
  215. dynamic_cast<pmx::PmxVertexSkinningBDEF2 *>(v->skinning.get());
  216. const auto vsBDEF4_ptr =
  217. dynamic_cast<pmx::PmxVertexSkinningBDEF4 *>(v->skinning.get());
  218. const auto vsSDEF_ptr =
  219. dynamic_cast<pmx::PmxVertexSkinningSDEF *>(v->skinning.get());
  220. switch (v->skinning_type) {
  221. case pmx::PmxVertexSkinningType::BDEF1:
  222. bone_vertex_map[vsBDEF1_ptr->bone_index].push_back(
  223. aiVertexWeight(index, 1.0));
  224. break;
  225. case pmx::PmxVertexSkinningType::BDEF2:
  226. bone_vertex_map[vsBDEF2_ptr->bone_index1].push_back(
  227. aiVertexWeight(index, vsBDEF2_ptr->bone_weight));
  228. bone_vertex_map[vsBDEF2_ptr->bone_index2].push_back(
  229. aiVertexWeight(index, 1.0f - vsBDEF2_ptr->bone_weight));
  230. break;
  231. case pmx::PmxVertexSkinningType::BDEF4:
  232. bone_vertex_map[vsBDEF4_ptr->bone_index1].push_back(
  233. aiVertexWeight(index, vsBDEF4_ptr->bone_weight1));
  234. bone_vertex_map[vsBDEF4_ptr->bone_index2].push_back(
  235. aiVertexWeight(index, vsBDEF4_ptr->bone_weight2));
  236. bone_vertex_map[vsBDEF4_ptr->bone_index3].push_back(
  237. aiVertexWeight(index, vsBDEF4_ptr->bone_weight3));
  238. bone_vertex_map[vsBDEF4_ptr->bone_index4].push_back(
  239. aiVertexWeight(index, vsBDEF4_ptr->bone_weight4));
  240. break;
  241. case pmx::PmxVertexSkinningType::SDEF: // TODO: how to use sdef_c, sdef_r0,
  242. // sdef_r1?
  243. bone_vertex_map[vsSDEF_ptr->bone_index1].push_back(
  244. aiVertexWeight(index, vsSDEF_ptr->bone_weight));
  245. bone_vertex_map[vsSDEF_ptr->bone_index2].push_back(
  246. aiVertexWeight(index, 1.0f - vsSDEF_ptr->bone_weight));
  247. break;
  248. case pmx::PmxVertexSkinningType::QDEF:
  249. const auto vsQDEF_ptr =
  250. dynamic_cast<pmx::PmxVertexSkinningQDEF *>(v->skinning.get());
  251. bone_vertex_map[vsQDEF_ptr->bone_index1].push_back(
  252. aiVertexWeight(index, vsQDEF_ptr->bone_weight1));
  253. bone_vertex_map[vsQDEF_ptr->bone_index2].push_back(
  254. aiVertexWeight(index, vsQDEF_ptr->bone_weight2));
  255. bone_vertex_map[vsQDEF_ptr->bone_index3].push_back(
  256. aiVertexWeight(index, vsQDEF_ptr->bone_weight3));
  257. bone_vertex_map[vsQDEF_ptr->bone_index4].push_back(
  258. aiVertexWeight(index, vsQDEF_ptr->bone_weight4));
  259. break;
  260. }
  261. }
  262. // make all bones for each mesh
  263. // assign bone weights to skinned bones (otherwise just initialize)
  264. auto bone_ptr_ptr = new aiBone *[pModel->bone_count];
  265. pMesh->mNumBones = pModel->bone_count;
  266. pMesh->mBones = bone_ptr_ptr;
  267. for (auto ii = 0; ii < pModel->bone_count; ++ii) {
  268. auto pBone = new aiBone;
  269. const auto &pmxBone = pModel->bones[ii];
  270. pBone->mName = pmxBone.bone_name;
  271. aiVector3D pos(pmxBone.position[0], pmxBone.position[1], pmxBone.position[2]);
  272. aiMatrix4x4::Translation(-pos, pBone->mOffsetMatrix);
  273. auto it = bone_vertex_map.find(ii);
  274. if (it != bone_vertex_map.end()) {
  275. pBone->mNumWeights = static_cast<unsigned int>(it->second.size());
  276. pBone->mWeights = new aiVertexWeight[pBone->mNumWeights];
  277. for (unsigned int j = 0; j < pBone->mNumWeights; j++) {
  278. pBone->mWeights[j] = it->second[j];
  279. }
  280. }
  281. bone_ptr_ptr[ii] = pBone;
  282. }
  283. return pMesh;
  284. }
  285. // ------------------------------------------------------------------------------------------------
  286. aiMaterial *MMDImporter::CreateMaterial(const pmx::PmxMaterial *pMat,
  287. const pmx::PmxModel *pModel) {
  288. aiMaterial *mat = new aiMaterial();
  289. aiString name(pMat->material_english_name);
  290. mat->AddProperty(&name, AI_MATKEY_NAME);
  291. aiColor3D diffuse(pMat->diffuse[0], pMat->diffuse[1], pMat->diffuse[2]);
  292. mat->AddProperty(&diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  293. aiColor3D specular(pMat->specular[0], pMat->specular[1], pMat->specular[2]);
  294. mat->AddProperty(&specular, 1, AI_MATKEY_COLOR_SPECULAR);
  295. aiColor3D ambient(pMat->ambient[0], pMat->ambient[1], pMat->ambient[2]);
  296. mat->AddProperty(&ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  297. float opacity = pMat->diffuse[3];
  298. mat->AddProperty(&opacity, 1, AI_MATKEY_OPACITY);
  299. float shininess = pMat->specularlity;
  300. mat->AddProperty(&shininess, 1, AI_MATKEY_SHININESS_STRENGTH);
  301. if (pMat->diffuse_texture_index >= 0) {
  302. aiString texture_path(pModel->textures[pMat->diffuse_texture_index]);
  303. mat->AddProperty(&texture_path, AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0));
  304. }
  305. int mapping_uvwsrc = 0;
  306. mat->AddProperty(&mapping_uvwsrc, 1,
  307. AI_MATKEY_UVWSRC(aiTextureType_DIFFUSE, 0));
  308. return mat;
  309. }
  310. // ------------------------------------------------------------------------------------------------
  311. } // Namespace Assimp
  312. #endif // !! ASSIMP_BUILD_NO_MMD_IMPORTER