XFileImporter.cpp 30 KB

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