FBXConverter.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXConverter.cpp
  34. * @brief Implementation of the FBX DOM -> aiScene converter
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  38. #include "FBXParser.h"
  39. #include "FBXConverter.h"
  40. #include "FBXDocument.h"
  41. #include "FBXUtil.h"
  42. #include "FBXProperties.h"
  43. #include "FBXImporter.h"
  44. namespace Assimp {
  45. namespace FBX {
  46. using namespace Util;
  47. // XXX vc9's debugger won't step into anonymous namespaces
  48. //namespace {
  49. /** Dummy class to encapsulate the conversion process */
  50. class Converter
  51. {
  52. public:
  53. Converter(aiScene* out, const Document& doc)
  54. : out(out)
  55. , doc(doc)
  56. {
  57. ConvertRootNode();
  58. if(doc.Settings().readAllMaterials) {
  59. // unfortunately this means we have to evaluate all objects
  60. BOOST_FOREACH(const ObjectMap::value_type& v,doc.Objects()) {
  61. const Object* ob = v.second->Get();
  62. if(!ob) {
  63. continue;
  64. }
  65. const Material* mat = dynamic_cast<const Material*>(ob);
  66. if(mat) {
  67. if (materials_converted.find(mat) == materials_converted.end()) {
  68. ConvertMaterial(*mat);
  69. }
  70. }
  71. }
  72. }
  73. TransferDataToScene();
  74. }
  75. ~Converter()
  76. {
  77. std::for_each(meshes.begin(),meshes.end(),Util::delete_fun<aiMesh>());
  78. std::for_each(materials.begin(),materials.end(),Util::delete_fun<aiMaterial>());
  79. }
  80. private:
  81. // ------------------------------------------------------------------------------------------------
  82. // find scene root and trigger recursive scene conversion
  83. void ConvertRootNode()
  84. {
  85. out->mRootNode = new aiNode();
  86. out->mRootNode->mName.Set("RootNode");
  87. // root has ID 0
  88. ConvertNodes(0L, *out->mRootNode);
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // collect and assign child nodes
  92. void ConvertNodes(uint64_t id, aiNode& parent)
  93. {
  94. const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(id);
  95. std::vector<aiNode*> nodes;
  96. nodes.reserve(conns.size());
  97. BOOST_FOREACH(const Connection* con, conns) {
  98. // ignore object-property links
  99. if(con->PropertyName().length()) {
  100. continue;
  101. }
  102. const Object* const object = con->SourceObject();
  103. if(!object) {
  104. FBXImporter::LogWarn("failed to convert source object for node link");
  105. continue;
  106. }
  107. const Model* const model = dynamic_cast<const Model*>(object);
  108. if(model) {
  109. aiNode* nd = new aiNode();
  110. nodes.push_back(nd);
  111. // strip Model:: prefix
  112. std::string name = model->Name();
  113. if(name.substr(0,7) == "Model::") {
  114. name = name.substr(7);
  115. }
  116. nd->mName.Set(name);
  117. nd->mParent = &parent;
  118. ConvertTransformation(*model,*nd);
  119. ConvertModel(*model, *nd);
  120. ConvertNodes(model->ID(), *nd);
  121. }
  122. }
  123. if(nodes.size()) {
  124. parent.mChildren = new aiNode*[nodes.size()]();
  125. parent.mNumChildren = static_cast<unsigned int>(nodes.size());
  126. std::swap_ranges(nodes.begin(),nodes.end(),parent.mChildren);
  127. }
  128. }
  129. // ------------------------------------------------------------------------------------------------
  130. void ConvertTransformation(const Model& model, aiNode& nd)
  131. {
  132. const PropertyTable& props = model.Props();
  133. bool ok;
  134. aiVector3D Translation = PropertyGet<aiVector3D>(props,"Lcl Translation",ok);
  135. if(!ok) {
  136. Translation = aiVector3D(0.0f,0.0f,0.0f);
  137. }
  138. aiVector3D Scaling = PropertyGet<aiVector3D>(props,"Lcl Scaling",ok);
  139. if(!ok) {
  140. Scaling = aiVector3D(1.0f,1.0f,1.0f);
  141. }
  142. // XXX euler angles, radians, xyz order?
  143. aiVector3D Rotation = PropertyGet<aiVector3D>(props,"Lcl Rotation",ok);
  144. if(!ok) {
  145. Rotation = aiVector3D(0.0f,0.0f,0.0f);
  146. }
  147. aiMatrix4x4 temp;
  148. nd.mTransformation = aiMatrix4x4::Scaling(Scaling,temp);
  149. if(fabs(Rotation.x) > 1e-6f) {
  150. nd.mTransformation *= aiMatrix4x4::RotationX(Rotation.x,temp);
  151. }
  152. if(fabs(Rotation.y) > 1e-6f) {
  153. nd.mTransformation *= aiMatrix4x4::RotationY(Rotation.y,temp);
  154. }
  155. if(fabs(Rotation.z) > 1e-6f) {
  156. nd.mTransformation *= aiMatrix4x4::RotationZ(Rotation.z,temp);
  157. }
  158. nd.mTransformation.a4 = Translation.x;
  159. nd.mTransformation.b4 = Translation.y;
  160. nd.mTransformation.c4 = Translation.z;
  161. }
  162. // ------------------------------------------------------------------------------------------------
  163. void ConvertModel(const Model& model, aiNode& nd)
  164. {
  165. const std::vector<const Geometry*>& geos = model.GetGeometry();
  166. std::vector<unsigned int> meshes;
  167. meshes.reserve(geos.size());
  168. BOOST_FOREACH(const Geometry* geo, geos) {
  169. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*>(geo);
  170. if(mesh) {
  171. const std::vector<unsigned int>& indices = ConvertMesh(*mesh, model);
  172. std::copy(indices.begin(),indices.end(),std::back_inserter(meshes) );
  173. }
  174. else {
  175. FBXImporter::LogWarn("ignoring unrecognized geometry: " + geo->Name());
  176. }
  177. }
  178. if(meshes.size()) {
  179. nd.mMeshes = new unsigned int[meshes.size()]();
  180. nd.mNumMeshes = static_cast<unsigned int>(meshes.size());
  181. std::swap_ranges(meshes.begin(),meshes.end(),nd.mMeshes);
  182. }
  183. }
  184. // ------------------------------------------------------------------------------------------------
  185. // MeshGeometry -> aiMesh, return mesh index + 1 or 0 if the conversion failed
  186. std::vector<unsigned int> ConvertMesh(const MeshGeometry& mesh, const Model& model)
  187. {
  188. std::vector<unsigned int> temp;
  189. MeshMap::const_iterator it = meshes_converted.find(&mesh);
  190. if (it != meshes_converted.end()) {
  191. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(temp));
  192. return temp;
  193. }
  194. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  195. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  196. if(vertices.empty() || faces.empty()) {
  197. FBXImporter::LogWarn("ignoring empty geometry: " + mesh.Name());
  198. return temp;
  199. }
  200. // one material per mesh maps easily to aiMesh. Multiple material
  201. // meshes need to be split.
  202. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  203. if (!mindices.empty()) {
  204. const unsigned int base = mindices[0];
  205. BOOST_FOREACH(unsigned int index, mindices) {
  206. if(index != base) {
  207. return ConvertMeshMultiMaterial(mesh, model);
  208. }
  209. }
  210. }
  211. // faster codepath, just copy the data
  212. temp.push_back(ConvertMeshSingleMaterial(mesh, model));
  213. return temp;
  214. }
  215. // ------------------------------------------------------------------------------------------------
  216. aiMesh* SetupEmptyMesh(const MeshGeometry& mesh, unsigned int material_index)
  217. {
  218. aiMesh* const out_mesh = new aiMesh();
  219. meshes.push_back(out_mesh);
  220. meshes_converted[&mesh].push_back(static_cast<unsigned int>(meshes.size()-1));
  221. // set name
  222. std::string name = mesh.Name();
  223. if (name.substr(0,10) == "Geometry::") {
  224. name = name.substr(10);
  225. }
  226. if(name.length()) {
  227. out_mesh->mName.Set(name);
  228. }
  229. return out_mesh;
  230. }
  231. // ------------------------------------------------------------------------------------------------
  232. unsigned int ConvertMeshSingleMaterial(const MeshGeometry& mesh, const Model& model)
  233. {
  234. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  235. aiMesh* const out_mesh = SetupEmptyMesh(mesh,mindices.size() ? mindices[0] : static_cast<unsigned int>(-1));
  236. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  237. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  238. // copy vertices
  239. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  240. out_mesh->mVertices = new aiVector3D[vertices.size()];
  241. std::copy(vertices.begin(),vertices.end(),out_mesh->mVertices);
  242. // generate dummy faces
  243. out_mesh->mNumFaces = static_cast<unsigned int>(faces.size());
  244. aiFace* fac = out_mesh->mFaces = new aiFace[faces.size()]();
  245. unsigned int cursor = 0;
  246. BOOST_FOREACH(unsigned int pcount, faces) {
  247. aiFace& f = *fac++;
  248. f.mNumIndices = pcount;
  249. f.mIndices = new unsigned int[pcount];
  250. switch(pcount)
  251. {
  252. case 1:
  253. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  254. break;
  255. case 2:
  256. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  257. break;
  258. case 3:
  259. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  260. break;
  261. default:
  262. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  263. break;
  264. }
  265. for (unsigned int i = 0; i < pcount; ++i) {
  266. f.mIndices[i] = cursor++;
  267. }
  268. }
  269. // copy normals
  270. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  271. if(normals.size()) {
  272. ai_assert(normals.size() == vertices.size());
  273. out_mesh->mNormals = new aiVector3D[vertices.size()];
  274. std::copy(normals.begin(),normals.end(),out_mesh->mNormals);
  275. }
  276. // copy tangents - assimp requires both tangents and bitangents (binormals)
  277. // to be present, or neither of them. Compute binormals from normals
  278. // and tangents if needed.
  279. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  280. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  281. if(tangents.size()) {
  282. std::vector<aiVector3D> tempBinormals;
  283. if (!binormals->size()) {
  284. if (normals.size()) {
  285. tempBinormals.resize(normals.size());
  286. for (unsigned int i = 0; i < tangents.size(); ++i) {
  287. tempBinormals[i] = normals[i] ^ tangents[i];
  288. }
  289. binormals = &tempBinormals;
  290. }
  291. else {
  292. binormals = NULL;
  293. }
  294. }
  295. if(binormals) {
  296. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  297. out_mesh->mTangents = new aiVector3D[vertices.size()];
  298. std::copy(tangents.begin(),tangents.end(),out_mesh->mTangents);
  299. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  300. std::copy(binormals->begin(),binormals->end(),out_mesh->mBitangents);
  301. }
  302. }
  303. // copy texture coords
  304. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  305. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  306. if(uvs.empty()) {
  307. break;
  308. }
  309. aiVector3D* out_uv = out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  310. BOOST_FOREACH(const aiVector2D& v, uvs) {
  311. *out_uv++ = aiVector3D(v.x,v.y,0.0f);
  312. }
  313. out_mesh->mNumUVComponents[i] = 2;
  314. }
  315. // copy vertex colors
  316. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
  317. const std::vector<aiColor4D>& colors = mesh.GetVertexColors(i);
  318. if(colors.empty()) {
  319. break;
  320. }
  321. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  322. std::copy(colors.begin(),colors.end(),out_mesh->mColors[i]);
  323. }
  324. if(mindices.empty()) {
  325. FBXImporter::LogError("no material assigned to mesh, setting default material");
  326. out_mesh->mMaterialIndex = GetDefaultMaterial();
  327. }
  328. else {
  329. ConvertMaterialForMesh(out_mesh,model,mesh,mindices[0]);
  330. }
  331. return static_cast<unsigned int>(meshes.size() - 1);
  332. }
  333. // ------------------------------------------------------------------------------------------------
  334. std::vector<unsigned int> ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model)
  335. {
  336. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  337. ai_assert(mindices.size());
  338. std::set<unsigned int> had;
  339. std::vector<unsigned int> indices;
  340. BOOST_FOREACH(unsigned int index, mindices) {
  341. if(had.find(index) == had.end()) {
  342. indices.push_back(ConvertMeshMultiMaterial(mesh, model, index));
  343. had.insert(index);
  344. }
  345. }
  346. return indices;
  347. }
  348. // ------------------------------------------------------------------------------------------------
  349. unsigned int ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model, unsigned int index)
  350. {
  351. aiMesh* const out_mesh = SetupEmptyMesh(mesh, index);
  352. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  353. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  354. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  355. unsigned int count_faces = 0;
  356. unsigned int count_vertices = 0;
  357. // count faces
  358. for(std::vector<unsigned int>::const_iterator it = mindices.begin(),
  359. end = mindices.end(), itf = faces.begin(); it != end; ++it, ++itf)
  360. {
  361. if ((*it) != index) {
  362. continue;
  363. }
  364. ++count_faces;
  365. count_vertices += *itf;
  366. }
  367. ai_assert(count_faces);
  368. // allocate output data arrays, but don't fill them yet
  369. out_mesh->mNumVertices = count_vertices;
  370. out_mesh->mVertices = new aiVector3D[count_vertices];
  371. out_mesh->mNumFaces = count_faces;
  372. aiFace* fac = out_mesh->mFaces = new aiFace[count_faces]();
  373. // allocate normals
  374. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  375. if(normals.size()) {
  376. ai_assert(normals.size() == vertices.size());
  377. out_mesh->mNormals = new aiVector3D[vertices.size()];
  378. }
  379. // allocate tangents, binormals.
  380. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  381. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  382. if(tangents.size()) {
  383. std::vector<aiVector3D> tempBinormals;
  384. if (!binormals->size()) {
  385. if (normals.size()) {
  386. // XXX this computes the binormals for the entire mesh, not only
  387. // the part for which we need them.
  388. tempBinormals.resize(normals.size());
  389. for (unsigned int i = 0; i < tangents.size(); ++i) {
  390. tempBinormals[i] = normals[i] ^ tangents[i];
  391. }
  392. binormals = &tempBinormals;
  393. }
  394. else {
  395. binormals = NULL;
  396. }
  397. }
  398. if(binormals) {
  399. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  400. out_mesh->mTangents = new aiVector3D[vertices.size()];
  401. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  402. }
  403. }
  404. // allocate texture coords
  405. unsigned int num_uvs = 0;
  406. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs) {
  407. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  408. if(uvs.empty()) {
  409. break;
  410. }
  411. out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  412. out_mesh->mNumUVComponents[i] = 2;
  413. }
  414. // allocate vertex colors
  415. unsigned int num_vcs = 0;
  416. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs) {
  417. const std::vector<aiColor4D>& colors = mesh.GetVertexColors(i);
  418. if(colors.empty()) {
  419. break;
  420. }
  421. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  422. }
  423. unsigned int cursor = 0, in_cursor = 0;
  424. for(std::vector<unsigned int>::const_iterator it = mindices.begin(),
  425. end = mindices.end(), itf = faces.begin(); it != end; ++it, ++itf)
  426. {
  427. const unsigned int pcount = *itf;
  428. if ((*it) != index) {
  429. in_cursor += pcount;
  430. continue;
  431. }
  432. aiFace& f = *fac++;
  433. f.mNumIndices = pcount;
  434. f.mIndices = new unsigned int[pcount];
  435. switch(pcount)
  436. {
  437. case 1:
  438. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  439. break;
  440. case 2:
  441. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  442. break;
  443. case 3:
  444. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  445. break;
  446. default:
  447. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  448. break;
  449. }
  450. for (unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor) {
  451. f.mIndices[i] = cursor;
  452. out_mesh->mVertices[cursor] = vertices[in_cursor];
  453. if(out_mesh->mNormals) {
  454. out_mesh->mNormals[cursor] = normals[in_cursor];
  455. }
  456. if(out_mesh->mTangents) {
  457. out_mesh->mTangents[cursor] = tangents[in_cursor];
  458. out_mesh->mBitangents[cursor] = (*binormals)[in_cursor];
  459. }
  460. for (unsigned int i = 0; i < num_uvs; ++i) {
  461. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  462. out_mesh->mTextureCoords[i][cursor] = aiVector3D(uvs[in_cursor].x,uvs[in_cursor].y, 0.0f);
  463. }
  464. for (unsigned int i = 0; i < num_vcs; ++i) {
  465. const std::vector<aiColor4D>& cols = mesh.GetVertexColors(i);
  466. out_mesh->mColors[i][cursor] = cols[in_cursor];
  467. }
  468. }
  469. }
  470. ConvertMaterialForMesh(out_mesh,model,mesh,index);
  471. return static_cast<unsigned int>(meshes.size() - 1);
  472. }
  473. // ------------------------------------------------------------------------------------------------
  474. void ConvertMaterialForMesh(aiMesh* out, const Model& model, const MeshGeometry& geo, unsigned int materialIndex)
  475. {
  476. // locate source materials for this mesh
  477. const std::vector<const Material*>& mats = model.GetMaterials();
  478. if (materialIndex >= mats.size()) {
  479. FBXImporter::LogError("material index out of bounds, setting default material");
  480. out->mMaterialIndex = GetDefaultMaterial();
  481. return;
  482. }
  483. const Material* const mat = mats[materialIndex];
  484. MaterialMap::const_iterator it = materials_converted.find(mat);
  485. if (it != materials_converted.end()) {
  486. out->mMaterialIndex = (*it).second;
  487. return;
  488. }
  489. out->mMaterialIndex = ConvertMaterial(*mat);
  490. materials_converted[mat] = out->mMaterialIndex;
  491. }
  492. // ------------------------------------------------------------------------------------------------
  493. unsigned int GetDefaultMaterial()
  494. {
  495. if (defaultMaterialIndex) {
  496. return defaultMaterialIndex - 1;
  497. }
  498. aiMaterial* out_mat = new aiMaterial();
  499. materials.push_back(out_mat);
  500. const aiColor3D diffuse = aiColor3D(0.8f,0.8f,0.8f);
  501. out_mat->AddProperty(&diffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  502. aiString s;
  503. s.Set(AI_DEFAULT_MATERIAL_NAME);
  504. out_mat->AddProperty(&s,AI_MATKEY_NAME);
  505. defaultMaterialIndex = static_cast<unsigned int>(materials.size());
  506. return defaultMaterialIndex - 1;
  507. }
  508. // ------------------------------------------------------------------------------------------------
  509. // Material -> aiMaterial
  510. unsigned int ConvertMaterial(const Material& material)
  511. {
  512. const PropertyTable& props = material.Props();
  513. // generate empty output material
  514. aiMaterial* out_mat = new aiMaterial();
  515. materials_converted[&material] = static_cast<unsigned int>(materials.size());
  516. materials.push_back(out_mat);
  517. aiString str;
  518. // stip Material:: prefix
  519. std::string name = material.Name();
  520. if(name.substr(0,10) == "Material::") {
  521. name = name.substr(10);
  522. }
  523. // set material name if not empty - this could happen
  524. // and there should be no key for it in this case.
  525. if(name.length()) {
  526. str.Set(name);
  527. out_mat->AddProperty(&str,AI_MATKEY_NAME);
  528. }
  529. // shading stuff and colors
  530. SetShadingPropertiesCommon(out_mat,props);
  531. // texture assignments
  532. SetTextureProperties(out_mat,material.Textures());
  533. return static_cast<unsigned int>(materials.size() - 1);
  534. }
  535. // ------------------------------------------------------------------------------------------------
  536. void TrySetTextureProperties(aiMaterial* out_mat, const TextureMap& textures, const std::string& propName, aiTextureType target)
  537. {
  538. TextureMap::const_iterator it = textures.find(propName);
  539. if(it == textures.end()) {
  540. return;
  541. }
  542. const Texture* const tex = (*it).second;
  543. aiString path;
  544. path.Set(tex->RelativeFilename());
  545. out_mat->AddProperty(&path,_AI_MATKEY_TEXTURE_BASE,target,0);
  546. aiUVTransform uvTrafo;
  547. // XXX handle all kinds of UV transformations
  548. uvTrafo.mScaling = tex->UVScaling();
  549. uvTrafo.mTranslation = tex->UVTranslation();
  550. out_mat->AddProperty(&uvTrafo,1,_AI_MATKEY_UVTRANSFORM_BASE,target,0);
  551. const PropertyTable& props = tex->Props();
  552. int uvIndex = 0;
  553. bool ok;
  554. const std::string& uvSet = PropertyGet<std::string>(props,"UVSet",ok);
  555. if(ok) {
  556. // "default" is the name which usually appears in the FbxFileTexture template
  557. if(uvSet != "default" && uvSet.length()) {
  558. // this is a bit awkward - we need to find a mesh that uses this
  559. // material and scan its UV channels for the given UV name because
  560. // assimp references UV channels by index, not by name.
  561. // XXX: the case that UV channels may appear in different orders
  562. // in meshes is unhandled. A possible solution would be to sort
  563. // the UV channels alphabetically, but this would have the side
  564. // effect that the primary (first) UV channel would sometimes
  565. // be moved, causing trouble when users read only the first
  566. // UV channel and ignore UV channel assignments altogether.
  567. const unsigned int matIndex = std::distance(materials.begin(),
  568. std::find(materials.begin(),materials.end(),out_mat)
  569. );
  570. uvIndex = -1;
  571. BOOST_FOREACH(const MeshMap::value_type& v,meshes_converted) {
  572. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*> (v.first);
  573. if(!mesh) {
  574. continue;
  575. }
  576. const std::vector<unsigned int>& mats = mesh->GetMaterialIndices();
  577. if(std::find(mats.begin(),mats.end(),matIndex) == mats.end()) {
  578. continue;
  579. }
  580. int index = -1;
  581. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  582. if(mesh->GetTextureCoords(i).empty()) {
  583. break;
  584. }
  585. const std::string& name = mesh->GetTextureCoordChannelName(i);
  586. if(name == uvSet) {
  587. index = static_cast<int>(i);
  588. break;
  589. }
  590. }
  591. if(index == -1) {
  592. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  593. continue;
  594. }
  595. if(uvIndex == -1) {
  596. uvIndex = index;
  597. }
  598. else {
  599. FBXImporter::LogWarn("the UV channel named " + uvSet +
  600. " appears at different positions in meshes, results will be wrong");
  601. }
  602. }
  603. if(uvIndex == -1) {
  604. FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel");
  605. uvIndex = 0;
  606. }
  607. }
  608. }
  609. out_mat->AddProperty(&uvIndex,1,_AI_MATKEY_UVWSRC_BASE,target,0);
  610. }
  611. // ------------------------------------------------------------------------------------------------
  612. void SetTextureProperties(aiMaterial* out_mat, const TextureMap& textures)
  613. {
  614. TrySetTextureProperties(out_mat, textures, "DiffuseColor", aiTextureType_DIFFUSE);
  615. TrySetTextureProperties(out_mat, textures, "AmbientColor", aiTextureType_AMBIENT);
  616. TrySetTextureProperties(out_mat, textures, "EmissiveColor", aiTextureType_EMISSIVE);
  617. TrySetTextureProperties(out_mat, textures, "SpecularColor", aiTextureType_SPECULAR);
  618. TrySetTextureProperties(out_mat, textures, "TransparentColor", aiTextureType_OPACITY);
  619. TrySetTextureProperties(out_mat, textures, "ReflectionColor", aiTextureType_REFLECTION);
  620. TrySetTextureProperties(out_mat, textures, "DisplacementColor", aiTextureType_DISPLACEMENT);
  621. TrySetTextureProperties(out_mat, textures, "NormalMap", aiTextureType_NORMALS);
  622. TrySetTextureProperties(out_mat, textures, "Bump", aiTextureType_HEIGHT);
  623. }
  624. // ------------------------------------------------------------------------------------------------
  625. aiColor3D GetColorPropertyFromMaterial(const PropertyTable& props,const std::string& baseName, bool& result)
  626. {
  627. result = true;
  628. bool ok;
  629. const aiVector3D& Diffuse = PropertyGet<aiVector3D>(props,baseName,ok);
  630. if(ok) {
  631. return aiColor3D(Diffuse.x,Diffuse.y,Diffuse.z);
  632. }
  633. else {
  634. aiVector3D DiffuseColor = PropertyGet<aiVector3D>(props,baseName + "Color",ok);
  635. if(ok) {
  636. float DiffuseFactor = PropertyGet<float>(props,baseName + "Factor",ok);
  637. if(ok) {
  638. DiffuseColor *= DiffuseFactor;
  639. }
  640. return aiColor3D(DiffuseColor.x,DiffuseColor.y,DiffuseColor.z);
  641. }
  642. }
  643. result = false;
  644. return aiColor3D(0.0f,0.0f,0.0f);
  645. }
  646. // ------------------------------------------------------------------------------------------------
  647. void SetShadingPropertiesCommon(aiMaterial* out_mat, const PropertyTable& props)
  648. {
  649. // set shading properties. There are various, redundant ways in which FBX materials
  650. // specify their shading settings (depending on shading models, prop
  651. // template etc.). No idea which one is right in a particular context.
  652. // Just try to make sense of it - there's no spec to verify this against,
  653. // so why should we.
  654. bool ok;
  655. const aiColor3D& Diffuse = GetColorPropertyFromMaterial(props,"Diffuse",ok);
  656. if(ok) {
  657. out_mat->AddProperty(&Diffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  658. }
  659. const aiColor3D& Emissive = GetColorPropertyFromMaterial(props,"Emissive",ok);
  660. if(ok) {
  661. out_mat->AddProperty(&Emissive,1,AI_MATKEY_COLOR_EMISSIVE);
  662. }
  663. const aiColor3D& Ambient = GetColorPropertyFromMaterial(props,"Ambient",ok);
  664. if(ok) {
  665. out_mat->AddProperty(&Ambient,1,AI_MATKEY_COLOR_AMBIENT);
  666. }
  667. const aiColor3D& Specular = GetColorPropertyFromMaterial(props,"Specular",ok);
  668. if(ok) {
  669. out_mat->AddProperty(&Specular,1,AI_MATKEY_COLOR_SPECULAR);
  670. }
  671. const float Opacity = PropertyGet<float>(props,"Opacity",ok);
  672. if(ok) {
  673. out_mat->AddProperty(&Opacity,1,AI_MATKEY_OPACITY);
  674. }
  675. const float Reflectivity = PropertyGet<float>(props,"Reflectivity",ok);
  676. if(ok) {
  677. out_mat->AddProperty(&Reflectivity,1,AI_MATKEY_REFLECTIVITY);
  678. }
  679. const float Shininess = PropertyGet<float>(props,"Shininess",ok);
  680. if(ok) {
  681. out_mat->AddProperty(&Shininess,1,AI_MATKEY_SHININESS_STRENGTH);
  682. }
  683. const float ShininessExponent = PropertyGet<float>(props,"ShininessExponent",ok);
  684. if(ok) {
  685. out_mat->AddProperty(&ShininessExponent,1,AI_MATKEY_SHININESS);
  686. }
  687. }
  688. // ------------------------------------------------------------------------------------------------
  689. // copy generated meshes, animations, lights, cameras and textures to the output scene
  690. void TransferDataToScene()
  691. {
  692. ai_assert(!out->mMeshes && !out->mNumMeshes);
  693. // note: the trailing () ensures initialization with NULL - not
  694. // many C++ users seem to know this, so pointing it out to avoid
  695. // confusion why this code works.
  696. out->mMeshes = new aiMesh*[meshes.size()]();
  697. out->mNumMeshes = static_cast<unsigned int>(meshes.size());
  698. std::swap_ranges(meshes.begin(),meshes.end(),out->mMeshes);
  699. if(materials.size()) {
  700. out->mMaterials = new aiMaterial*[materials.size()]();
  701. out->mNumMaterials = static_cast<unsigned int>(materials.size());
  702. std::swap_ranges(materials.begin(),materials.end(),out->mMaterials);
  703. }
  704. }
  705. private:
  706. // 0: not assigned yet, others: index is value - 1
  707. unsigned int defaultMaterialIndex;
  708. std::vector<aiMesh*> meshes;
  709. std::vector<aiMaterial*> materials;
  710. typedef std::map<const Material*, unsigned int> MaterialMap;
  711. MaterialMap materials_converted;
  712. typedef std::map<const Geometry*, std::vector<unsigned int> > MeshMap;
  713. MeshMap meshes_converted;
  714. aiScene* const out;
  715. const FBX::Document& doc;
  716. };
  717. //} // !anon
  718. // ------------------------------------------------------------------------------------------------
  719. void ConvertToAssimpScene(aiScene* out, const Document& doc)
  720. {
  721. Converter converter(out,doc);
  722. }
  723. } // !FBX
  724. } // !Assimp
  725. #endif