XFileImporter.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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. /** @file XFileImporter.cpp
  35. * @brief Implementation of the XFile importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_X_IMPORTER
  38. #include "AssetLib/X/XFileImporter.h"
  39. #include "AssetLib/X/XFileParser.h"
  40. #include "PostProcessing/ConvertToLHProcess.h"
  41. #include <assimp/TinyFormatter.h>
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/scene.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <assimp/importerdesc.h>
  46. #include <cctype>
  47. #include <memory>
  48. using namespace Assimp;
  49. using namespace Assimp::Formatter;
  50. static const aiImporterDesc desc = {
  51. "Direct3D XFile Importer",
  52. "",
  53. "",
  54. "",
  55. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
  56. 1,
  57. 3,
  58. 1,
  59. 5,
  60. "x"
  61. };
  62. // ------------------------------------------------------------------------------------------------
  63. // Constructor to be privately used by Importer
  64. XFileImporter::XFileImporter() : mBuffer() {
  65. // empty
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Returns whether the class can handle the format of the given file.
  69. bool XFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool /*checkSig*/) const {
  70. static const uint32_t token[] = { AI_MAKE_MAGIC("xof ") };
  71. return CheckMagicToken(pIOHandler,pFile,token,AI_COUNT_OF(token));
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Get file extension list
  75. const aiImporterDesc* XFileImporter::GetInfo () const {
  76. return &desc;
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Imports the given file into the given scene structure.
  80. void XFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  81. // read file into memory
  82. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  83. if ( file.get() == nullptr ) {
  84. throw DeadlyImportError( "Failed to open file ", pFile, "." );
  85. }
  86. static const size_t MinSize = 16;
  87. size_t fileSize = file->FileSize();
  88. if ( fileSize < MinSize ) {
  89. throw DeadlyImportError( "XFile is too small." );
  90. }
  91. // in the hope that binary files will never start with a BOM ...
  92. mBuffer.resize( fileSize + 1);
  93. file->Read( &mBuffer.front(), 1, fileSize);
  94. ConvertToUTF8(mBuffer);
  95. // parse the file into a temporary representation
  96. XFileParser parser( mBuffer);
  97. // and create the proper return structures out of it
  98. CreateDataRepresentationFromImport( pScene, parser.GetImportedData());
  99. // if nothing came from it, report it as error
  100. if ( !pScene->mRootNode ) {
  101. throw DeadlyImportError( "XFile is ill-formatted - no content imported." );
  102. }
  103. }
  104. // ------------------------------------------------------------------------------------------------
  105. // Constructs the return data structure out of the imported data.
  106. void XFileImporter::CreateDataRepresentationFromImport( aiScene* pScene, XFile::Scene* pData)
  107. {
  108. // Read the global materials first so that meshes referring to them can find them later
  109. ConvertMaterials( pScene, pData->mGlobalMaterials);
  110. // copy nodes, extracting meshes and materials on the way
  111. pScene->mRootNode = CreateNodes( pScene, nullptr, pData->mRootNode);
  112. // extract animations
  113. CreateAnimations( pScene, pData);
  114. // read the global meshes that were stored outside of any node
  115. if( !pData->mGlobalMeshes.empty() ) {
  116. // create a root node to hold them if there isn't any, yet
  117. if( pScene->mRootNode == nullptr ) {
  118. pScene->mRootNode = new aiNode;
  119. pScene->mRootNode->mName.Set( "$dummy_node");
  120. }
  121. // convert all global meshes and store them in the root node.
  122. // If there was one before, the global meshes now suddenly have its transformation matrix...
  123. // Don't know what to do there, I don't want to insert another node under the present root node
  124. // just to avoid this.
  125. CreateMeshes( pScene, pScene->mRootNode, pData->mGlobalMeshes);
  126. }
  127. if (!pScene->mRootNode) {
  128. throw DeadlyImportError( "No root node" );
  129. }
  130. // Convert everything to OpenGL space... it's the same operation as the conversion back, so we can reuse the step directly
  131. MakeLeftHandedProcess convertProcess;
  132. convertProcess.Execute( pScene);
  133. FlipWindingOrderProcess flipper;
  134. flipper.Execute(pScene);
  135. // finally: create a dummy material if not material was imported
  136. if( pScene->mNumMaterials == 0) {
  137. pScene->mNumMaterials = 1;
  138. // create the Material
  139. aiMaterial* mat = new aiMaterial;
  140. int shadeMode = (int) aiShadingMode_Gouraud;
  141. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  142. // material colours
  143. int specExp = 1;
  144. aiColor3D clr = aiColor3D( 0, 0, 0);
  145. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_EMISSIVE);
  146. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_SPECULAR);
  147. clr = aiColor3D( 0.5f, 0.5f, 0.5f);
  148. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  149. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  150. pScene->mMaterials = new aiMaterial*[1];
  151. pScene->mMaterials[0] = mat;
  152. }
  153. }
  154. // ------------------------------------------------------------------------------------------------
  155. // Recursively creates scene nodes from the imported hierarchy.
  156. aiNode* XFileImporter::CreateNodes( aiScene* pScene, aiNode* pParent, const XFile::Node* pNode) {
  157. if ( !pNode ) {
  158. return nullptr;
  159. }
  160. // create node
  161. aiNode* node = new aiNode;
  162. node->mName.length = (ai_uint32)pNode->mName.length();
  163. node->mParent = pParent;
  164. memcpy( node->mName.data, pNode->mName.c_str(), pNode->mName.length());
  165. node->mName.data[node->mName.length] = 0;
  166. node->mTransformation = pNode->mTrafoMatrix;
  167. // convert meshes from the source node
  168. CreateMeshes( pScene, node, pNode->mMeshes);
  169. // handle children
  170. if( !pNode->mChildren.empty() ) {
  171. node->mNumChildren = (unsigned int)pNode->mChildren.size();
  172. node->mChildren = new aiNode* [node->mNumChildren];
  173. for ( unsigned int a = 0; a < pNode->mChildren.size(); ++a ) {
  174. node->mChildren[ a ] = CreateNodes( pScene, node, pNode->mChildren[ a ] );
  175. }
  176. }
  177. return node;
  178. }
  179. // ------------------------------------------------------------------------------------------------
  180. // Creates the meshes for the given node.
  181. void XFileImporter::CreateMeshes( aiScene* pScene, aiNode* pNode, const std::vector<XFile::Mesh*>& pMeshes) {
  182. if (pMeshes.empty()) {
  183. return;
  184. }
  185. // create a mesh for each mesh-material combination in the source node
  186. std::vector<aiMesh*> meshes;
  187. for( unsigned int a = 0; a < pMeshes.size(); ++a ) {
  188. XFile::Mesh* sourceMesh = pMeshes[a];
  189. if ( nullptr == sourceMesh ) {
  190. continue;
  191. }
  192. // first convert its materials so that we can find them with their index afterwards
  193. ConvertMaterials( pScene, sourceMesh->mMaterials);
  194. unsigned int numMaterials = std::max( (unsigned int)sourceMesh->mMaterials.size(), 1u);
  195. for( unsigned int b = 0; b < numMaterials; ++b ) {
  196. // collect the faces belonging to this material
  197. std::vector<unsigned int> faces;
  198. unsigned int numVertices = 0;
  199. if( !sourceMesh->mFaceMaterials.empty() ) {
  200. // if there is a per-face material defined, select the faces with the corresponding material
  201. for( unsigned int c = 0; c < sourceMesh->mFaceMaterials.size(); ++c ) {
  202. if( sourceMesh->mFaceMaterials[c] == b) {
  203. faces.push_back( c);
  204. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  205. }
  206. }
  207. } else {
  208. // if there is no per-face material, place everything into one mesh
  209. for( unsigned int c = 0; c < sourceMesh->mPosFaces.size(); ++c ) {
  210. faces.push_back( c);
  211. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  212. }
  213. }
  214. // no faces/vertices using this material? strange...
  215. if ( numVertices == 0 ) {
  216. continue;
  217. }
  218. // create a submesh using this material
  219. aiMesh* mesh = new aiMesh;
  220. meshes.push_back( mesh);
  221. // find the material in the scene's material list. Either own material
  222. // or referenced material, it should already have a valid index
  223. if( !sourceMesh->mFaceMaterials.empty() ) {
  224. mesh->mMaterialIndex = static_cast<unsigned int>(sourceMesh->mMaterials[b].sceneIndex);
  225. } else {
  226. mesh->mMaterialIndex = 0;
  227. }
  228. // Create properly sized data arrays in the mesh. We store unique vertices per face,
  229. // as specified
  230. mesh->mNumVertices = numVertices;
  231. mesh->mVertices = new aiVector3D[numVertices];
  232. mesh->mNumFaces = (unsigned int)faces.size();
  233. mesh->mFaces = new aiFace[mesh->mNumFaces];
  234. // name
  235. mesh->mName.Set(sourceMesh->mName);
  236. // normals?
  237. if ( sourceMesh->mNormals.size() > 0 ) {
  238. mesh->mNormals = new aiVector3D[ numVertices ];
  239. }
  240. // texture coords
  241. for( unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c ) {
  242. if ( !sourceMesh->mTexCoords[ c ].empty() ) {
  243. mesh->mTextureCoords[ c ] = new aiVector3D[ numVertices ];
  244. }
  245. }
  246. // vertex colors
  247. for( unsigned int c = 0; c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c ) {
  248. if ( !sourceMesh->mColors[ c ].empty() ) {
  249. mesh->mColors[ c ] = new aiColor4D[ numVertices ];
  250. }
  251. }
  252. // now collect the vertex data of all data streams present in the imported mesh
  253. unsigned int newIndex( 0 );
  254. std::vector<unsigned int> orgPoints; // from which original point each new vertex stems
  255. orgPoints.resize( numVertices, 0);
  256. for( unsigned int c = 0; c < faces.size(); ++c ) {
  257. unsigned int f = faces[c]; // index of the source face
  258. const XFile::Face& pf = sourceMesh->mPosFaces[f]; // position source face
  259. // create face. either triangle or triangle fan depending on the index count
  260. aiFace& df = mesh->mFaces[c]; // destination face
  261. df.mNumIndices = (unsigned int)pf.mIndices.size();
  262. df.mIndices = new unsigned int[ df.mNumIndices];
  263. // collect vertex data for indices of this face
  264. for( unsigned int d = 0; d < df.mNumIndices; ++d ) {
  265. df.mIndices[ d ] = newIndex;
  266. const unsigned int newIdx( pf.mIndices[ d ] );
  267. if ( newIdx > sourceMesh->mPositions.size() ) {
  268. continue;
  269. }
  270. orgPoints[newIndex] = pf.mIndices[d];
  271. // Position
  272. mesh->mVertices[newIndex] = sourceMesh->mPositions[pf.mIndices[d]];
  273. // Normal, if present
  274. if ( mesh->HasNormals() ) {
  275. if ( sourceMesh->mNormFaces[ f ].mIndices.size() > d ) {
  276. const size_t idx( sourceMesh->mNormFaces[ f ].mIndices[ d ] );
  277. mesh->mNormals[ newIndex ] = sourceMesh->mNormals[ idx ];
  278. }
  279. }
  280. // texture coord sets
  281. for( unsigned int e = 0; e < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++e ) {
  282. if( mesh->HasTextureCoords( e)) {
  283. aiVector2D tex = sourceMesh->mTexCoords[e][pf.mIndices[d]];
  284. mesh->mTextureCoords[e][newIndex] = aiVector3D( tex.x, 1.0f - tex.y, 0.0f);
  285. }
  286. }
  287. // vertex color sets
  288. for ( unsigned int e = 0; e < AI_MAX_NUMBER_OF_COLOR_SETS; ++e ) {
  289. if ( mesh->HasVertexColors( e ) ) {
  290. mesh->mColors[ e ][ newIndex ] = sourceMesh->mColors[ e ][ pf.mIndices[ d ] ];
  291. }
  292. }
  293. newIndex++;
  294. }
  295. }
  296. // there should be as much new vertices as we calculated before
  297. ai_assert( newIndex == numVertices);
  298. // convert all bones of the source mesh which influence vertices in this newly created mesh
  299. const std::vector<XFile::Bone>& bones = sourceMesh->mBones;
  300. std::vector<aiBone*> newBones;
  301. for( unsigned int c = 0; c < bones.size(); ++c ) {
  302. const XFile::Bone& obone = bones[c];
  303. // set up a vertex-linear array of the weights for quick searching if a bone influences a vertex
  304. std::vector<ai_real> oldWeights( sourceMesh->mPositions.size(), 0.0);
  305. for ( unsigned int d = 0; d < obone.mWeights.size(); ++d ) {
  306. oldWeights[ obone.mWeights[ d ].mVertex ] = obone.mWeights[ d ].mWeight;
  307. }
  308. // collect all vertex weights that influence a vertex in the new mesh
  309. std::vector<aiVertexWeight> newWeights;
  310. newWeights.reserve( numVertices);
  311. for( unsigned int d = 0; d < orgPoints.size(); ++d ) {
  312. // does the new vertex stem from an old vertex which was influenced by this bone?
  313. ai_real w = oldWeights[orgPoints[d]];
  314. if ( w > 0.0 ) {
  315. newWeights.emplace_back( d, w );
  316. }
  317. }
  318. // if the bone has no weights in the newly created mesh, ignore it
  319. if ( newWeights.empty() ) {
  320. continue;
  321. }
  322. // create
  323. aiBone* nbone = new aiBone;
  324. newBones.push_back( nbone);
  325. // copy name and matrix
  326. nbone->mName.Set( obone.mName);
  327. nbone->mOffsetMatrix = obone.mOffsetMatrix;
  328. nbone->mNumWeights = (unsigned int)newWeights.size();
  329. nbone->mWeights = new aiVertexWeight[nbone->mNumWeights];
  330. for ( unsigned int d = 0; d < newWeights.size(); ++d ) {
  331. nbone->mWeights[ d ] = newWeights[ d ];
  332. }
  333. }
  334. // store the bones in the mesh
  335. mesh->mNumBones = (unsigned int)newBones.size();
  336. if( !newBones.empty()) {
  337. mesh->mBones = new aiBone*[mesh->mNumBones];
  338. std::copy( newBones.begin(), newBones.end(), mesh->mBones);
  339. }
  340. }
  341. }
  342. // reallocate scene mesh array to be large enough
  343. aiMesh** prevArray = pScene->mMeshes;
  344. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes + meshes.size()];
  345. if( prevArray) {
  346. memcpy( pScene->mMeshes, prevArray, pScene->mNumMeshes * sizeof( aiMesh*));
  347. delete [] prevArray;
  348. }
  349. // allocate mesh index array in the node
  350. pNode->mNumMeshes = (unsigned int)meshes.size();
  351. pNode->mMeshes = new unsigned int[pNode->mNumMeshes];
  352. // store all meshes in the mesh library of the scene and store their indices in the node
  353. for( unsigned int a = 0; a < meshes.size(); a++) {
  354. pScene->mMeshes[pScene->mNumMeshes] = meshes[a];
  355. pNode->mMeshes[a] = pScene->mNumMeshes;
  356. pScene->mNumMeshes++;
  357. }
  358. }
  359. // ------------------------------------------------------------------------------------------------
  360. // Converts the animations from the given imported data and creates them in the scene.
  361. void XFileImporter::CreateAnimations( aiScene* pScene, const XFile::Scene* pData) {
  362. std::vector<aiAnimation*> newAnims;
  363. for( unsigned int a = 0; a < pData->mAnims.size(); ++a ) {
  364. const XFile::Animation* anim = pData->mAnims[a];
  365. // some exporters mock me with empty animation tags.
  366. if ( anim->mAnims.empty() ) {
  367. continue;
  368. }
  369. // create a new animation to hold the data
  370. aiAnimation* nanim = new aiAnimation;
  371. newAnims.push_back( nanim);
  372. nanim->mName.Set( anim->mName);
  373. // duration will be determined by the maximum length
  374. nanim->mDuration = 0;
  375. nanim->mTicksPerSecond = pData->mAnimTicksPerSecond;
  376. nanim->mNumChannels = (unsigned int)anim->mAnims.size();
  377. nanim->mChannels = new aiNodeAnim*[nanim->mNumChannels];
  378. for( unsigned int b = 0; b < anim->mAnims.size(); ++b ) {
  379. const XFile::AnimBone* bone = anim->mAnims[b];
  380. aiNodeAnim* nbone = new aiNodeAnim;
  381. nbone->mNodeName.Set( bone->mBoneName);
  382. nanim->mChannels[b] = nbone;
  383. // key-frames are given as combined transformation matrix keys
  384. if( !bone->mTrafoKeys.empty() )
  385. {
  386. nbone->mNumPositionKeys = (unsigned int)bone->mTrafoKeys.size();
  387. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  388. nbone->mNumRotationKeys = (unsigned int)bone->mTrafoKeys.size();
  389. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  390. nbone->mNumScalingKeys = (unsigned int)bone->mTrafoKeys.size();
  391. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  392. for( unsigned int c = 0; c < bone->mTrafoKeys.size(); ++c) {
  393. // deconstruct each matrix into separate position, rotation and scaling
  394. double time = bone->mTrafoKeys[c].mTime;
  395. aiMatrix4x4 trafo = bone->mTrafoKeys[c].mMatrix;
  396. // extract position
  397. aiVector3D pos( trafo.a4, trafo.b4, trafo.c4);
  398. nbone->mPositionKeys[c].mTime = time;
  399. nbone->mPositionKeys[c].mValue = pos;
  400. // extract scaling
  401. aiVector3D scale;
  402. scale.x = aiVector3D( trafo.a1, trafo.b1, trafo.c1).Length();
  403. scale.y = aiVector3D( trafo.a2, trafo.b2, trafo.c2).Length();
  404. scale.z = aiVector3D( trafo.a3, trafo.b3, trafo.c3).Length();
  405. nbone->mScalingKeys[c].mTime = time;
  406. nbone->mScalingKeys[c].mValue = scale;
  407. // reconstruct rotation matrix without scaling
  408. aiMatrix3x3 rotmat(
  409. trafo.a1 / scale.x, trafo.a2 / scale.y, trafo.a3 / scale.z,
  410. trafo.b1 / scale.x, trafo.b2 / scale.y, trafo.b3 / scale.z,
  411. trafo.c1 / scale.x, trafo.c2 / scale.y, trafo.c3 / scale.z);
  412. // and convert it into a quaternion
  413. nbone->mRotationKeys[c].mTime = time;
  414. nbone->mRotationKeys[c].mValue = aiQuaternion( rotmat);
  415. }
  416. // longest lasting key sequence determines duration
  417. nanim->mDuration = std::max( nanim->mDuration, bone->mTrafoKeys.back().mTime);
  418. } else {
  419. // separate key sequences for position, rotation, scaling
  420. nbone->mNumPositionKeys = (unsigned int)bone->mPosKeys.size();
  421. if (nbone->mNumPositionKeys != 0) {
  422. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  423. for( unsigned int c = 0; c < nbone->mNumPositionKeys; ++c ) {
  424. aiVector3D pos = bone->mPosKeys[c].mValue;
  425. nbone->mPositionKeys[c].mTime = bone->mPosKeys[c].mTime;
  426. nbone->mPositionKeys[c].mValue = pos;
  427. }
  428. }
  429. // rotation
  430. nbone->mNumRotationKeys = (unsigned int)bone->mRotKeys.size();
  431. if (nbone->mNumRotationKeys != 0) {
  432. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  433. for( unsigned int c = 0; c < nbone->mNumRotationKeys; ++c ) {
  434. aiMatrix3x3 rotmat = bone->mRotKeys[c].mValue.GetMatrix();
  435. nbone->mRotationKeys[c].mTime = bone->mRotKeys[c].mTime;
  436. nbone->mRotationKeys[c].mValue = aiQuaternion( rotmat);
  437. nbone->mRotationKeys[c].mValue.w *= -1.0f; // needs quat inversion
  438. }
  439. }
  440. // scaling
  441. nbone->mNumScalingKeys = (unsigned int)bone->mScaleKeys.size();
  442. if (nbone->mNumScalingKeys != 0) {
  443. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  444. for( unsigned int c = 0; c < nbone->mNumScalingKeys; c++)
  445. nbone->mScalingKeys[c] = bone->mScaleKeys[c];
  446. }
  447. // longest lasting key sequence determines duration
  448. if( bone->mPosKeys.size() > 0)
  449. nanim->mDuration = std::max( nanim->mDuration, bone->mPosKeys.back().mTime);
  450. if( bone->mRotKeys.size() > 0)
  451. nanim->mDuration = std::max( nanim->mDuration, bone->mRotKeys.back().mTime);
  452. if( bone->mScaleKeys.size() > 0)
  453. nanim->mDuration = std::max( nanim->mDuration, bone->mScaleKeys.back().mTime);
  454. }
  455. }
  456. }
  457. // store all converted animations in the scene
  458. if( newAnims.size() > 0)
  459. {
  460. pScene->mNumAnimations = (unsigned int)newAnims.size();
  461. pScene->mAnimations = new aiAnimation* [pScene->mNumAnimations];
  462. for( unsigned int a = 0; a < newAnims.size(); a++)
  463. pScene->mAnimations[a] = newAnims[a];
  464. }
  465. }
  466. // ------------------------------------------------------------------------------------------------
  467. // Converts all materials in the given array and stores them in the scene's material list.
  468. void XFileImporter::ConvertMaterials( aiScene* pScene, std::vector<XFile::Material>& pMaterials)
  469. {
  470. // count the non-referrer materials in the array
  471. unsigned int numNewMaterials( 0 );
  472. for ( unsigned int a = 0; a < pMaterials.size(); ++a ) {
  473. if ( !pMaterials[ a ].mIsReference ) {
  474. ++numNewMaterials;
  475. }
  476. }
  477. // resize the scene's material list to offer enough space for the new materials
  478. if( numNewMaterials > 0 ) {
  479. aiMaterial** prevMats = pScene->mMaterials;
  480. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials + numNewMaterials];
  481. if( nullptr != prevMats) {
  482. ::memcpy( pScene->mMaterials, prevMats, pScene->mNumMaterials * sizeof( aiMaterial*));
  483. delete [] prevMats;
  484. }
  485. }
  486. // convert all the materials given in the array
  487. for( unsigned int a = 0; a < pMaterials.size(); ++a ) {
  488. XFile::Material& oldMat = pMaterials[a];
  489. if( oldMat.mIsReference) {
  490. // find the material it refers to by name, and store its index
  491. for( size_t b = 0; b < pScene->mNumMaterials; ++b ) {
  492. aiString name;
  493. pScene->mMaterials[b]->Get( AI_MATKEY_NAME, name);
  494. if( strcmp( name.C_Str(), oldMat.mName.data()) == 0 ) {
  495. oldMat.sceneIndex = a;
  496. break;
  497. }
  498. }
  499. if( oldMat.sceneIndex == SIZE_MAX ) {
  500. ASSIMP_LOG_WARN( "Could not resolve global material reference \"", oldMat.mName, "\"" );
  501. oldMat.sceneIndex = 0;
  502. }
  503. continue;
  504. }
  505. aiMaterial* mat = new aiMaterial;
  506. aiString name;
  507. name.Set( oldMat.mName);
  508. mat->AddProperty( &name, AI_MATKEY_NAME);
  509. // Shading model: hard-coded to PHONG, there is no such information in an XFile
  510. // FIX (aramis): If the specular exponent is 0, use gouraud shading. This is a bugfix
  511. // for some models in the SDK (e.g. good old tiny.x)
  512. int shadeMode = (int)oldMat.mSpecularExponent == 0.0f
  513. ? aiShadingMode_Gouraud : aiShadingMode_Phong;
  514. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  515. // material colours
  516. // Unclear: there's no ambient colour, but emissive. What to put for ambient?
  517. // Probably nothing at all, let the user select a suitable default.
  518. mat->AddProperty( &oldMat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  519. mat->AddProperty( &oldMat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  520. mat->AddProperty( &oldMat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  521. mat->AddProperty( &oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  522. // texture, if there is one
  523. if (1 == oldMat.mTextures.size() ) {
  524. const XFile::TexEntry& otex = oldMat.mTextures.back();
  525. if (otex.mName.length()) {
  526. // if there is only one texture assume it contains the diffuse color
  527. aiString tex( otex.mName);
  528. if ( otex.mIsNormalMap ) {
  529. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS( 0 ) );
  530. } else {
  531. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE( 0 ) );
  532. }
  533. }
  534. } else {
  535. // Otherwise ... try to search for typical strings in the
  536. // texture's file name like 'bump' or 'diffuse'
  537. unsigned int iHM = 0,iNM = 0,iDM = 0,iSM = 0,iAM = 0,iEM = 0;
  538. for( unsigned int b = 0; b < oldMat.mTextures.size(); ++b ) {
  539. const XFile::TexEntry& otex = oldMat.mTextures[b];
  540. std::string sz = otex.mName;
  541. if ( !sz.length() ) {
  542. continue;
  543. }
  544. // find the file name
  545. std::string::size_type s = sz.find_last_of("\\/");
  546. if ( std::string::npos == s ) {
  547. s = 0;
  548. }
  549. // cut off the file extension
  550. std::string::size_type sExt = sz.find_last_of('.');
  551. if (std::string::npos != sExt){
  552. sz[sExt] = '\0';
  553. }
  554. // convert to lower case for easier comparison
  555. for ( unsigned int c = 0; c < sz.length(); ++c ) {
  556. sz[ c ] = (char) tolower( (unsigned char) sz[ c ] );
  557. }
  558. // Place texture filename property under the corresponding name
  559. aiString tex( oldMat.mTextures[b].mName);
  560. // bump map
  561. if (std::string::npos != sz.find("bump", s) || std::string::npos != sz.find("height", s)) {
  562. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_HEIGHT(iHM++));
  563. } else if (otex.mIsNormalMap || std::string::npos != sz.find( "normal", s) || std::string::npos != sz.find("nm", s)) {
  564. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS(iNM++));
  565. } else if (std::string::npos != sz.find( "spec", s) || std::string::npos != sz.find( "glanz", s)) {
  566. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_SPECULAR(iSM++));
  567. } else if (std::string::npos != sz.find( "ambi", s) || std::string::npos != sz.find( "env", s)) {
  568. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_AMBIENT(iAM++));
  569. } else if (std::string::npos != sz.find( "emissive", s) || std::string::npos != sz.find( "self", s)) {
  570. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_EMISSIVE(iEM++));
  571. } else {
  572. // Assume it is a diffuse texture
  573. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE(iDM++));
  574. }
  575. }
  576. }
  577. pScene->mMaterials[pScene->mNumMaterials] = mat;
  578. oldMat.sceneIndex = pScene->mNumMaterials;
  579. pScene->mNumMaterials++;
  580. }
  581. }
  582. #endif // !! ASSIMP_BUILD_NO_X_IMPORTER