BsFBXImporter.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsFBXImporter.h"
  4. #include "BsResource.h"
  5. #include "BsCoreApplication.h"
  6. #include "BsDebug.h"
  7. #include "BsDataStream.h"
  8. #include "BsMeshData.h"
  9. #include "BsMesh.h"
  10. #include "BsVector2.h"
  11. #include "BsVector3.h"
  12. #include "BsVector4.h"
  13. #include "BsQuaternion.h"
  14. #include "BsVertexDataDesc.h"
  15. #include "BsFBXUtility.h"
  16. #include "BsMeshUtility.h"
  17. #include "BsRendererMeshData.h"
  18. #include "BsMeshImportOptions.h"
  19. namespace BansheeEngine
  20. {
  21. Matrix4 FBXToNativeType(const FbxAMatrix& value)
  22. {
  23. Matrix4 native;
  24. for (UINT32 row = 0; row < 4; row++)
  25. for (UINT32 col = 0; col < 4; col++)
  26. native[row][col] = (float)value[col][row];
  27. return native;
  28. }
  29. Vector3 FBXToNativeType(const FbxVector4& value)
  30. {
  31. Vector3 native;
  32. native.x = (float)value[0];
  33. native.y = (float)value[1];
  34. native.z = (float)value[2];
  35. return native;
  36. }
  37. Vector3 FBXToNativeType(const FbxDouble3& value)
  38. {
  39. Vector3 native;
  40. native.x = (float)value[0];
  41. native.y = (float)value[1];
  42. native.z = (float)value[2];
  43. return native;
  44. }
  45. Vector2 FBXToNativeType(const FbxVector2& value)
  46. {
  47. Vector2 native;
  48. native.x = (float)value[0];
  49. native.y = (float)value[1];
  50. return native;
  51. }
  52. RGBA FBXToNativeType(const FbxColor& value)
  53. {
  54. Color native;
  55. native.r = (float)value[0];
  56. native.g = (float)value[1];
  57. native.b = (float)value[2];
  58. native.a = (float)value[3];
  59. return native.getAsRGBA();
  60. }
  61. FbxSurfaceMaterial* FBXToNativeType(FbxSurfaceMaterial* const& value)
  62. {
  63. return value;
  64. }
  65. int FBXToNativeType(const int & value)
  66. {
  67. return value;
  68. }
  69. FBXImporter::FBXImporter()
  70. :SpecificImporter(), mFBXManager(nullptr)
  71. {
  72. mExtensions.push_back(L"fbx");
  73. }
  74. FBXImporter::~FBXImporter()
  75. {
  76. }
  77. bool FBXImporter::isExtensionSupported(const WString& ext) const
  78. {
  79. WString lowerCaseExt = ext;
  80. StringUtil::toLowerCase(lowerCaseExt);
  81. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  82. }
  83. bool FBXImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  84. {
  85. return true; // FBX files can be plain-text so I don't even check for magic number
  86. }
  87. ImportOptionsPtr FBXImporter::createImportOptions() const
  88. {
  89. return bs_shared_ptr_new<MeshImportOptions>();
  90. }
  91. ResourcePtr FBXImporter::import(const Path& filePath, ConstImportOptionsPtr importOptions)
  92. {
  93. FbxScene* fbxScene = nullptr;
  94. if (!startUpSdk(fbxScene))
  95. return nullptr;
  96. if (!loadFBXFile(fbxScene, filePath))
  97. return nullptr;
  98. const MeshImportOptions* meshImportOptions = static_cast<const MeshImportOptions*>(importOptions.get());
  99. FBXImportOptions fbxImportOptions;
  100. fbxImportOptions.importNormals = meshImportOptions->getImportNormals();
  101. fbxImportOptions.importTangents = meshImportOptions->getImportTangents();
  102. fbxImportOptions.importAnimation = meshImportOptions->getImportAnimation();
  103. fbxImportOptions.importBlendShapes = meshImportOptions->getImportBlendShapes();
  104. fbxImportOptions.importSkin = meshImportOptions->getImportSkin();
  105. fbxImportOptions.importScale = meshImportOptions->getImportScale();
  106. FBXImportScene importedScene;
  107. parseScene(fbxScene, fbxImportOptions, importedScene);
  108. if (fbxImportOptions.importBlendShapes)
  109. importBlendShapes(importedScene, fbxImportOptions);
  110. if (fbxImportOptions.importSkin)
  111. importSkin(importedScene);
  112. if (fbxImportOptions.importAnimation)
  113. importAnimations(fbxScene, fbxImportOptions, importedScene);
  114. splitMeshVertices(importedScene);
  115. generateMissingTangentSpace(importedScene, fbxImportOptions);
  116. Vector<SubMesh> subMeshes;
  117. RendererMeshDataPtr rendererMeshData = generateMeshData(importedScene, fbxImportOptions, subMeshes);
  118. // TODO - Later: Optimize mesh: Remove bad and degenerate polygons, weld nearby vertices, optimize for vertex cache
  119. shutDownSdk();
  120. INT32 usage = MU_STATIC;
  121. if (meshImportOptions->getCPUReadable())
  122. usage |= MU_CPUCACHED;
  123. MeshPtr mesh = Mesh::_createPtr(rendererMeshData->getData(), subMeshes, usage);
  124. WString fileName = filePath.getWFilename(false);
  125. mesh->setName(fileName);
  126. return mesh;
  127. }
  128. bool FBXImporter::startUpSdk(FbxScene*& scene)
  129. {
  130. mFBXManager = FbxManager::Create();
  131. if (mFBXManager == nullptr)
  132. {
  133. LOGERR("FBX import failed: FBX SDK failed to initialize. FbxManager::Create() failed.");
  134. return false;
  135. }
  136. FbxIOSettings* ios = FbxIOSettings::Create(mFBXManager, IOSROOT);
  137. mFBXManager->SetIOSettings(ios);
  138. scene = FbxScene::Create(mFBXManager, "Import Scene");
  139. if (scene == nullptr)
  140. {
  141. LOGWRN("FBX import failed: Failed to create FBX scene.");
  142. return false;
  143. }
  144. return true;
  145. }
  146. void FBXImporter::shutDownSdk()
  147. {
  148. mFBXManager->Destroy();
  149. mFBXManager = nullptr;
  150. }
  151. bool FBXImporter::loadFBXFile(FbxScene* scene, const Path& filePath)
  152. {
  153. int lFileMajor, lFileMinor, lFileRevision;
  154. int lSDKMajor, lSDKMinor, lSDKRevision;
  155. FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision);
  156. FbxImporter* importer = FbxImporter::Create(mFBXManager, "");
  157. bool importStatus = importer->Initialize(filePath.toString().c_str(), -1, mFBXManager->GetIOSettings());
  158. importer->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);
  159. if(!importStatus)
  160. {
  161. LOGERR("FBX import failed: Call to FbxImporter::Initialize() failed.\n" +
  162. String("Error returned: %s\n\n") + String(importer->GetStatus().GetErrorString()));
  163. return false;
  164. }
  165. mFBXManager->GetIOSettings()->SetBoolProp(IMP_FBX_TEXTURE, false);
  166. mFBXManager->GetIOSettings()->SetBoolProp(IMP_FBX_GOBO, false);
  167. importStatus = importer->Import(scene);
  168. if(!importStatus)
  169. {
  170. importer->Destroy();
  171. LOGERR("FBX import failed: Call to FbxImporter::Import() failed.\n" +
  172. String("Error returned: %s\n\n") + String(importer->GetStatus().GetErrorString()));
  173. return false;
  174. }
  175. FbxAxisSystem fileCoordSystem = scene->GetGlobalSettings().GetAxisSystem();
  176. FbxAxisSystem bsCoordSystem(FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eRightHanded);
  177. if (fileCoordSystem != bsCoordSystem)
  178. bsCoordSystem.ConvertScene(scene);
  179. importer->Destroy();
  180. return true;
  181. }
  182. void FBXImporter::parseScene(FbxScene* scene, const FBXImportOptions& options, FBXImportScene& outputScene)
  183. {
  184. outputScene.rootNode = createImportNode(outputScene, scene->GetRootNode(), nullptr);
  185. Stack<FbxNode*> todo;
  186. todo.push(scene->GetRootNode());
  187. while(!todo.empty())
  188. {
  189. FbxNode* curNode = todo.top();
  190. FBXImportNode* curImportNode = outputScene.nodeMap[curNode];
  191. todo.pop();
  192. const char* name = curNode->GetName();
  193. FbxNodeAttribute* attrib = curNode->GetNodeAttribute();
  194. if(attrib != nullptr)
  195. {
  196. FbxNodeAttribute::EType attribType = attrib->GetAttributeType();
  197. switch(attribType)
  198. {
  199. case FbxNodeAttribute::eNurbs:
  200. case FbxNodeAttribute::eNurbsSurface:
  201. case FbxNodeAttribute::ePatch:
  202. {
  203. FbxGeometryConverter geomConverter(mFBXManager);
  204. attrib = geomConverter.Triangulate(attrib, true);
  205. if (attrib->GetAttributeType() == FbxNodeAttribute::eMesh)
  206. {
  207. FbxMesh* mesh = static_cast<FbxMesh*>(attrib);
  208. mesh->RemoveBadPolygons();
  209. parseMesh(mesh, curImportNode, options, outputScene);
  210. }
  211. }
  212. break;
  213. case FbxNodeAttribute::eMesh:
  214. {
  215. FbxMesh* mesh = static_cast<FbxMesh*>(attrib);
  216. mesh->RemoveBadPolygons();
  217. if(!mesh->IsTriangleMesh())
  218. {
  219. FbxGeometryConverter geomConverter(mFBXManager);
  220. geomConverter.Triangulate(mesh, true);
  221. attrib = curNode->GetNodeAttribute();
  222. mesh = static_cast<FbxMesh*>(attrib);
  223. }
  224. parseMesh(mesh, curImportNode, options, outputScene);
  225. }
  226. break;
  227. }
  228. }
  229. for (int i = 0; i < curNode->GetChildCount(); i++)
  230. {
  231. FbxNode* childNode = curNode->GetChild(i);
  232. createImportNode(outputScene, childNode, curImportNode);
  233. todo.push(childNode);
  234. }
  235. }
  236. }
  237. FBXImportNode* FBXImporter::createImportNode(FBXImportScene& scene, FbxNode* fbxNode, FBXImportNode* parent)
  238. {
  239. FBXImportNode* node = bs_new<FBXImportNode>();
  240. Vector3 translation = FBXToNativeType(fbxNode->LclTranslation.Get());
  241. Vector3 rotationEuler = FBXToNativeType(fbxNode->LclRotation.Get());
  242. Vector3 scale = FBXToNativeType(fbxNode->LclScaling.Get());
  243. Quaternion rotation((Radian)rotationEuler.x, (Radian)rotationEuler.y, (Radian)rotationEuler.z);
  244. node->localTransform.setTRS(translation, rotation, scale);
  245. node->fbxNode = fbxNode;
  246. if (parent != nullptr)
  247. {
  248. node->worldTransform = node->localTransform * parent->worldTransform;
  249. parent->children.push_back(node);
  250. }
  251. else
  252. node->worldTransform = node->localTransform;
  253. scene.nodeMap.insert(std::make_pair(fbxNode, node));
  254. return node;
  255. }
  256. void FBXImporter::splitMeshVertices(FBXImportScene& scene)
  257. {
  258. Vector<FBXImportMesh*> splitMeshes;
  259. for (auto& mesh : scene.meshes)
  260. {
  261. FBXImportMesh* splitMesh = bs_new<FBXImportMesh>();
  262. splitMesh->fbxMesh = mesh->fbxMesh;
  263. splitMesh->referencedBy = mesh->referencedBy;
  264. splitMesh->bones = mesh->bones;
  265. FBXUtility::splitVertices(*mesh, *splitMesh);
  266. FBXUtility::flipWindingOrder(*splitMesh);
  267. splitMeshes.push_back(splitMesh);
  268. bs_delete(mesh);
  269. }
  270. scene.meshes = splitMeshes;
  271. }
  272. RendererMeshDataPtr FBXImporter::generateMeshData(const FBXImportScene& scene, const FBXImportOptions& options, Vector<SubMesh>& outputSubMeshes)
  273. {
  274. Matrix4 importScale = Matrix4::scaling(options.importScale);
  275. Vector<MeshDataPtr> allMeshData;
  276. Vector<Vector<SubMesh>> allSubMeshes;
  277. for (auto& mesh : scene.meshes)
  278. {
  279. Vector<Vector<UINT32>> indicesPerMaterial;
  280. for (UINT32 i = 0; i < (UINT32)mesh->indices.size(); i++)
  281. {
  282. while ((UINT32)mesh->materials[i] >= (UINT32)indicesPerMaterial.size())
  283. indicesPerMaterial.push_back(Vector<UINT32>());
  284. indicesPerMaterial[mesh->materials[i]].push_back(mesh->indices[i]);
  285. }
  286. UINT32* orderedIndices = (UINT32*)bs_alloc((UINT32)mesh->indices.size() * sizeof(UINT32));
  287. Vector<SubMesh> subMeshes;
  288. UINT32 currentIndex = 0;
  289. for (auto& subMeshIndices : indicesPerMaterial)
  290. {
  291. UINT32 indexCount = (UINT32)subMeshIndices.size();
  292. UINT32* dest = orderedIndices + currentIndex;
  293. memcpy(dest, subMeshIndices.data(), indexCount * sizeof(UINT32));
  294. subMeshes.push_back(SubMesh(currentIndex, indexCount, DOT_TRIANGLE_LIST));
  295. currentIndex += indexCount;
  296. }
  297. UINT32 vertexLayout = (UINT32)VertexLayout::Position;
  298. size_t numVertices = mesh->positions.size();
  299. bool hasColors = mesh->colors.size() == numVertices;
  300. bool hasNormals = mesh->normals.size() == numVertices;
  301. if (hasColors)
  302. vertexLayout |= (UINT32)VertexLayout::Color;
  303. bool hasTangents = false;
  304. if (hasNormals)
  305. {
  306. vertexLayout |= (UINT32)VertexLayout::Normal;
  307. if (mesh->tangents.size() == numVertices &&
  308. mesh->bitangents.size() == numVertices)
  309. {
  310. vertexLayout |= (UINT32)VertexLayout::Tangent;
  311. hasTangents = true;
  312. }
  313. }
  314. int UVIdx = 0;
  315. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  316. {
  317. if (mesh->UV[i].size() == numVertices)
  318. {
  319. if (i == 0)
  320. vertexLayout |= (UINT32)VertexLayout::UV0;
  321. else if (i == 1)
  322. vertexLayout |= (UINT32)VertexLayout::UV1;
  323. }
  324. }
  325. UINT32 numIndices = (UINT32)mesh->indices.size();
  326. for (auto& node : mesh->referencedBy)
  327. {
  328. Matrix4 worldTransform = node->worldTransform * importScale;
  329. Matrix4 worldTransformIT = worldTransform.transpose();
  330. worldTransformIT = worldTransformIT.inverse();
  331. RendererMeshDataPtr meshData = RendererMeshData::create((UINT32)numVertices, numIndices, (VertexLayout)vertexLayout);
  332. // Copy indices
  333. meshData->setIndices((UINT32*)mesh->indices.data(), numIndices * sizeof(UINT32));
  334. // Copy & transform positions
  335. UINT32 positionsSize = sizeof(Vector3) * (UINT32)numVertices;
  336. Vector3* transformedPositions = (Vector3*)bs_stack_alloc(positionsSize);
  337. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  338. transformedPositions[i] = worldTransform.multiplyAffine((Vector3)mesh->positions[i]);
  339. meshData->setPositions(transformedPositions, positionsSize);
  340. bs_stack_free(transformedPositions);
  341. // Copy & transform normals
  342. if (hasNormals)
  343. {
  344. UINT32 normalsSize = sizeof(Vector3) * (UINT32)numVertices;
  345. Vector3* transformedNormals = (Vector3*)bs_stack_alloc(normalsSize);
  346. // Copy, convert & transform tangents & bitangents
  347. if (hasTangents)
  348. {
  349. UINT32 tangentsSize = sizeof(Vector4) * (UINT32)numVertices;
  350. Vector4* transformedTangents = (Vector4*)bs_stack_alloc(tangentsSize);
  351. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  352. {
  353. Vector3 normal = (Vector3)mesh->normals[i];
  354. normal = worldTransformIT.multiplyDirection(normal);
  355. transformedNormals[i] = Vector3::normalize(normal);
  356. Vector3 tangent = (Vector3)mesh->tangents[i];
  357. tangent = Vector3::normalize(worldTransformIT.multiplyDirection(tangent));
  358. Vector3 bitangent = (Vector3)mesh->bitangents[i];
  359. bitangent = worldTransformIT.multiplyDirection(bitangent);
  360. Vector3 engineBitangent = Vector3::cross(normal, tangent);
  361. float sign = Vector3::dot(engineBitangent, bitangent);
  362. transformedTangents[i] = Vector4(tangent.x, tangent.y, tangent.z, sign > 0 ? 1.0f : -1.0f);
  363. }
  364. meshData->setTangents(transformedTangents, tangentsSize);
  365. bs_stack_free(transformedTangents);
  366. }
  367. else // Just normals
  368. {
  369. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  370. transformedNormals[i] = Vector3::normalize(worldTransformIT.multiplyDirection((Vector3)mesh->normals[i]));
  371. }
  372. meshData->setNormals(transformedNormals, normalsSize);
  373. bs_stack_free(transformedNormals);
  374. }
  375. // Copy colors
  376. if (hasColors)
  377. {
  378. meshData->setColors(mesh->colors.data(), sizeof(UINT32) * (UINT32)numVertices);
  379. }
  380. // Copy UV
  381. int writeUVIDx = 0;
  382. for (auto& uvLayer : mesh->UV)
  383. {
  384. if (uvLayer.size() == numVertices)
  385. {
  386. UINT32 size = sizeof(Vector2) * (UINT32)numVertices;
  387. Vector2* transformedUV = (Vector2*)bs_stack_alloc(size);
  388. UINT32 i = 0;
  389. for (auto& uv : uvLayer)
  390. {
  391. transformedUV[i] = uv;
  392. transformedUV[i].y = 1.0f - uv.y;
  393. i++;
  394. }
  395. if (writeUVIDx == 0)
  396. meshData->setUV0(transformedUV, size);
  397. else if (writeUVIDx == 1)
  398. meshData->setUV1(transformedUV, size);
  399. bs_stack_free(transformedUV);
  400. writeUVIDx++;
  401. }
  402. }
  403. // TODO - Transform blend shapes?
  404. allMeshData.push_back(meshData->getData());
  405. allSubMeshes.push_back(subMeshes);
  406. }
  407. }
  408. if (allMeshData.size() > 1)
  409. {
  410. return RendererMeshData::create(MeshData::combine(allMeshData, allSubMeshes, outputSubMeshes));
  411. }
  412. else if (allMeshData.size() == 1)
  413. {
  414. outputSubMeshes = allSubMeshes[0];
  415. return RendererMeshData::create(allMeshData[0]);
  416. }
  417. return nullptr;
  418. }
  419. template<class TFBX, class TNative>
  420. class FBXDirectIndexer
  421. {
  422. public:
  423. FBXDirectIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  424. :mElementArray(layer.GetDirectArray()),
  425. mElementCount(mElementArray.GetCount())
  426. {}
  427. bool get(int index, TNative& output) const
  428. {
  429. if (index < 0 || index >= mElementCount)
  430. return false;
  431. output = FBXToNativeType(mElementArray.GetAt(index));
  432. return true;
  433. }
  434. bool isEmpty() const
  435. {
  436. return mElementCount == 0;
  437. }
  438. private:
  439. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  440. int mElementCount;
  441. };
  442. template<class TFBX, class TNative>
  443. class FBXIndexIndexer
  444. {
  445. public:
  446. FBXIndexIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  447. :mElementArray(layer.GetDirectArray()),
  448. mIndexArray(layer.GetIndexArray()),
  449. mElementCount(mElementArray.GetCount()),
  450. mIndexCount(mIndexArray.GetCount())
  451. {}
  452. bool get(int index, TNative& output) const
  453. {
  454. if (index < 0 || index >= mIndexCount)
  455. return false;
  456. int actualIndex = mIndexArray.GetAt(index);
  457. if (actualIndex < 0 || actualIndex >= mElementCount)
  458. return false;
  459. output = FBXToNativeType(mElementArray.GetAt(actualIndex));
  460. return true;
  461. }
  462. bool isEmpty() const
  463. {
  464. return mElementCount == 0 || mIndexCount == 0;
  465. }
  466. private:
  467. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  468. const FbxLayerElementArrayTemplate<int>& mIndexArray;
  469. int mElementCount;
  470. int mIndexCount;
  471. };
  472. template<class TFBX, class TNative, class TIndexer>
  473. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  474. {
  475. TIndexer indexer(layer);
  476. if (indexer.isEmpty())
  477. return;
  478. output.resize(indices.size());
  479. FbxLayerElement::EMappingMode mappingMode = layer.GetMappingMode();
  480. UINT32 indexCount = (UINT32)indices.size();
  481. switch (mappingMode)
  482. {
  483. case FbxLayerElement::eByControlPoint:
  484. for (UINT32 i = 0; i < indexCount; i++)
  485. {
  486. int index = indices[i];
  487. indexer.get(index, output[i]);
  488. }
  489. break;
  490. case FbxLayerElement::eByPolygonVertex:
  491. for (UINT32 i = 0; i < indexCount; i++)
  492. indexer.get(i, output[i]);
  493. break;
  494. case FbxLayerElement::eByPolygon:
  495. // We expect mesh to be triangulated here
  496. {
  497. UINT32 polygonCount = indexCount / 3;
  498. UINT32 index = 0;
  499. for (UINT32 i = 0; i < polygonCount; i++)
  500. {
  501. TNative value;
  502. indexer.get(i, value);
  503. output[index++] = value;
  504. output[index++] = value;
  505. output[index++] = value;
  506. }
  507. }
  508. break;
  509. case FbxLayerElement::eAllSame:
  510. {
  511. TNative value;
  512. indexer.get(0, value);
  513. for (UINT32 i = 0; i < indexCount; i++)
  514. output[i] = value;
  515. }
  516. break;
  517. default:
  518. LOGWRN("FBX Import: Unsupported layer mapping mode.");
  519. break;
  520. }
  521. }
  522. template<class TFBX, class TNative>
  523. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  524. {
  525. FbxLayerElement::EReferenceMode refMode = layer.GetReferenceMode();
  526. if (refMode == FbxLayerElement::eDirect)
  527. readLayerData<TFBX, TNative, FBXDirectIndexer<TFBX, TNative> >(layer, output, indices);
  528. else if (refMode == FbxLayerElement::eIndexToDirect)
  529. readLayerData<TFBX, TNative, FBXIndexIndexer<TFBX, TNative> >(layer, output, indices);
  530. else
  531. LOGWRN("FBX Import: Unsupported layer reference mode.");
  532. }
  533. void FBXImporter::parseMesh(FbxMesh* mesh, FBXImportNode* parentNode, const FBXImportOptions& options, FBXImportScene& outputScene)
  534. {
  535. // Check if valid
  536. if (!mesh->IsTriangleMesh())
  537. return;
  538. UINT32 vertexCount = mesh->GetControlPointsCount();
  539. UINT32 triangleCount = mesh->GetPolygonCount();
  540. if (vertexCount == 0 || triangleCount == 0)
  541. return;
  542. // Register in global mesh array
  543. FBXImportMesh* importMesh = nullptr;
  544. auto iterFindMesh = outputScene.meshMap.find(mesh);
  545. if (iterFindMesh != outputScene.meshMap.end())
  546. {
  547. UINT32 meshIdx = iterFindMesh->second;
  548. outputScene.meshes[meshIdx]->referencedBy.push_back(parentNode);
  549. return;
  550. }
  551. else
  552. {
  553. importMesh = bs_new<FBXImportMesh>();
  554. outputScene.meshes.push_back(importMesh);
  555. importMesh->referencedBy.push_back(parentNode);
  556. importMesh->fbxMesh = mesh;
  557. outputScene.meshMap[mesh] = (UINT32)outputScene.meshes.size() - 1;
  558. }
  559. // Import vertices
  560. importMesh->positions.resize(vertexCount);
  561. FbxVector4* controlPoints = mesh->GetControlPoints();
  562. for (UINT32 i = 0; i < vertexCount; i++)
  563. importMesh->positions[i] = FBXToNativeType(controlPoints[i]);
  564. // Import triangles
  565. UINT32 indexCount = triangleCount * 3;
  566. importMesh->indices.resize(indexCount);
  567. int* fbxIndices = mesh->GetPolygonVertices();
  568. importMesh->indices.assign(fbxIndices, fbxIndices + indexCount);
  569. // Import UVs
  570. Vector<FbxLayerElementUV*> fbxUVLayers;
  571. //// Search the diffuse layers first
  572. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  573. {
  574. FbxLayer* layer = mesh->GetLayer(i, FbxLayerElement::eUV);
  575. if (layer == nullptr)
  576. continue;
  577. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  578. {
  579. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  580. if (uvLayer == nullptr)
  581. continue;
  582. fbxUVLayers.push_back(uvLayer);
  583. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  584. break;
  585. }
  586. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  587. break;
  588. }
  589. //// If there's room, search all others too
  590. if (fbxUVLayers.size() < FBX_IMPORT_MAX_UV_LAYERS)
  591. {
  592. UINT32 numLayers = mesh->GetLayerCount();
  593. for (UINT32 i = 0; i < numLayers; i++)
  594. {
  595. FbxLayer* layer = mesh->GetLayer(i);
  596. if (layer == nullptr)
  597. continue;
  598. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  599. {
  600. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  601. if (uvLayer == nullptr)
  602. continue;
  603. auto iterFind = std::find(fbxUVLayers.begin(), fbxUVLayers.end(), uvLayer);
  604. if (iterFind != fbxUVLayers.end())
  605. continue;
  606. fbxUVLayers.push_back(uvLayer);
  607. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  608. break;
  609. }
  610. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  611. break;
  612. }
  613. }
  614. for (size_t i = 0; i < fbxUVLayers.size(); i++)
  615. readLayerData(*fbxUVLayers[i], importMesh->UV[i], importMesh->indices);
  616. FbxLayer* mainLayer = mesh->GetLayer(0);
  617. if (mainLayer != nullptr)
  618. {
  619. // Import colors
  620. if (mainLayer->GetVertexColors() != nullptr)
  621. readLayerData(*mainLayer->GetVertexColors(), importMesh->colors, importMesh->indices);
  622. // Import normals
  623. if (options.importNormals)
  624. {
  625. bool hasNormals = mainLayer->GetNormals() != nullptr;
  626. if (!hasNormals)
  627. {
  628. if (mainLayer->GetSmoothing() != nullptr)
  629. {
  630. FbxLayerElementSmoothing* smoothing = mainLayer->GetSmoothing();
  631. if (smoothing->GetMappingMode() == FbxLayerElement::eByEdge)
  632. {
  633. FbxGeometryConverter converter(mFBXManager);
  634. converter.ComputePolygonSmoothingFromEdgeSmoothing(mesh, 0);
  635. }
  636. readLayerData(*smoothing, importMesh->smoothingGroups, importMesh->indices);
  637. if (!importMesh->smoothingGroups.empty())
  638. {
  639. FBXUtility::normalsFromSmoothing(importMesh->positions, importMesh->indices,
  640. importMesh->smoothingGroups, importMesh->normals);
  641. }
  642. }
  643. }
  644. else
  645. readLayerData(*mainLayer->GetNormals(), importMesh->normals, importMesh->indices);
  646. }
  647. // Import tangents
  648. if (options.importTangents)
  649. {
  650. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  651. if (!hasTangents)
  652. {
  653. if (fbxUVLayers.size() > 0)
  654. hasTangents = mesh->GenerateTangentsData(0, false);
  655. }
  656. if (hasTangents)
  657. {
  658. readLayerData(*mainLayer->GetTangents(), importMesh->tangents, importMesh->indices);
  659. readLayerData(*mainLayer->GetBinormals(), importMesh->bitangents, importMesh->indices);
  660. }
  661. }
  662. // Import material indexes
  663. if (mainLayer->GetMaterials() != nullptr)
  664. {
  665. Vector<FbxSurfaceMaterial*> fbxMaterials;
  666. readLayerData(*mainLayer->GetMaterials(), fbxMaterials, importMesh->indices);
  667. UnorderedMap<FbxSurfaceMaterial*, int> materialLookup;
  668. int nextMaterialIdx = 0;
  669. for (UINT32 i = 0; i < (UINT32)fbxMaterials.size(); i++)
  670. {
  671. auto iterFind = materialLookup.find(fbxMaterials[i]);
  672. int materialIdx = 0;
  673. if (iterFind != materialLookup.end())
  674. materialIdx = iterFind->second;
  675. else
  676. {
  677. materialIdx = nextMaterialIdx++;
  678. materialLookup[fbxMaterials[i]] = materialIdx;
  679. }
  680. importMesh->materials.push_back(materialIdx);
  681. }
  682. }
  683. }
  684. }
  685. void FBXImporter::importBlendShapes(FBXImportScene& scene, const FBXImportOptions& options)
  686. {
  687. for (auto& mesh : scene.meshes)
  688. {
  689. FbxMesh* fbxMesh = mesh->fbxMesh;
  690. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  691. for (UINT32 i = 0; i < deformerCount; i++)
  692. {
  693. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  694. UINT32 blendShapeChannelCount = (UINT32)deformer->GetBlendShapeChannelCount();
  695. for (UINT32 j = 0; j < blendShapeChannelCount; ++j)
  696. {
  697. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  698. double* weights = channel->GetTargetShapeFullWeights();
  699. UINT32 frameCount = channel->GetTargetShapeCount();
  700. if (frameCount == 0)
  701. continue;
  702. mesh->blendShapes.push_back(FBXBlendShape());
  703. FBXBlendShape& blendShape = mesh->blendShapes.back();
  704. blendShape.name = channel->GetName();
  705. blendShape.frames.resize(frameCount);
  706. for (UINT32 k = 0; k < frameCount; k++)
  707. {
  708. FbxShape* fbxShape = channel->GetTargetShape(k);
  709. FBXBlendShapeFrame& frame = blendShape.frames[k];
  710. frame.weight = (float)weights[k];
  711. importBlendShapeFrame(fbxShape, *mesh, options, frame);
  712. }
  713. }
  714. }
  715. }
  716. }
  717. void FBXImporter::importBlendShapeFrame(FbxShape* shape, const FBXImportMesh& mesh, const FBXImportOptions& options, FBXBlendShapeFrame& outFrame)
  718. {
  719. UINT32 vertexCount = (UINT32)shape->GetControlPointsCount();
  720. outFrame.positions.resize(vertexCount);
  721. FbxVector4* controlPoints = shape->GetControlPoints();
  722. for (UINT32 i = 0; i < vertexCount; i++)
  723. outFrame.positions[i] = FBXToNativeType(controlPoints[i]);
  724. FbxLayer* mainLayer = shape->GetLayer(0);
  725. if (options.importNormals)
  726. {
  727. bool hasNormals = mainLayer->GetNormals() != nullptr;
  728. if (!hasNormals)
  729. {
  730. if (!mesh.smoothingGroups.empty())
  731. {
  732. FBXUtility::normalsFromSmoothing(outFrame.positions, mesh.indices,
  733. mesh.smoothingGroups, outFrame.normals);
  734. }
  735. }
  736. else
  737. readLayerData(*mainLayer->GetNormals(), outFrame.normals, mesh.indices);
  738. }
  739. if (options.importTangents)
  740. {
  741. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  742. if (hasTangents)
  743. {
  744. readLayerData(*mainLayer->GetTangents(), outFrame.tangents, mesh.indices);
  745. readLayerData(*mainLayer->GetBinormals(), outFrame.bitangents, mesh.indices);
  746. }
  747. }
  748. }
  749. void FBXImporter::importSkin(FBXImportScene& scene)
  750. {
  751. for (auto& mesh : scene.meshes)
  752. {
  753. FbxMesh* fbxMesh = mesh->fbxMesh;
  754. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eSkin);
  755. if (deformerCount > 0)
  756. {
  757. // We ignore other deformers if there's more than one
  758. FbxSkin* deformer = static_cast<FbxSkin*>(fbxMesh->GetDeformer(0, FbxDeformer::eSkin));
  759. UINT32 boneCount = (UINT32)deformer->GetClusterCount();
  760. if (boneCount == 0)
  761. continue;
  762. // If only one bone and it links to itself, ignore the bone
  763. if (boneCount == 1)
  764. {
  765. FbxCluster* cluster = deformer->GetCluster(0);
  766. if (mesh->referencedBy.size() == 1 && mesh->referencedBy[0]->fbxNode == cluster->GetLink())
  767. continue;
  768. }
  769. importSkin(scene, deformer, *mesh);
  770. }
  771. }
  772. }
  773. void FBXImporter::importSkin(FBXImportScene& scene, FbxSkin* skin, FBXImportMesh& mesh)
  774. {
  775. Vector<FBXBoneInfluence>& influences = mesh.boneInfluences;
  776. influences.resize(mesh.positions.size());
  777. UnorderedSet<FbxNode*> existingBones;
  778. UINT32 boneCount = (UINT32)skin->GetClusterCount();
  779. for (UINT32 i = 0; i < boneCount; i++)
  780. {
  781. FbxCluster* cluster = skin->GetCluster(i);
  782. FbxNode* link = cluster->GetLink();
  783. // The bone node doesn't exist, skip it
  784. auto iterFind = scene.nodeMap.find(link);
  785. if (iterFind == scene.nodeMap.end())
  786. continue;
  787. mesh.bones.push_back(FBXBone());
  788. FBXBone& bone = mesh.bones.back();
  789. bone.node = iterFind->second;
  790. FbxAMatrix clusterTransform;
  791. cluster->GetTransformMatrix(clusterTransform);
  792. FbxAMatrix linkTransform;
  793. cluster->GetTransformLinkMatrix(linkTransform);
  794. FbxAMatrix bindPose = linkTransform.Inverse() * clusterTransform;
  795. bone.bindPose = FBXToNativeType(bindPose);
  796. bool isDuplicate = existingBones.insert(link).second;
  797. bool isAdditive = cluster->GetLinkMode() == FbxCluster::eAdditive;
  798. // We avoid importing weights twice for duplicate bones and we don't
  799. // support additive link mode.
  800. bool importWeights = !isDuplicate && !isAdditive;
  801. if (!importWeights)
  802. continue;
  803. double* weights = cluster->GetControlPointWeights();
  804. INT32* indices = cluster->GetControlPointIndices();
  805. UINT32 numIndices = (UINT32)cluster->GetControlPointIndicesCount();
  806. INT32 numVertices = (INT32)influences.size();
  807. // Add new weights while keeping them in order and removing the smallest ones
  808. // if number of influences exceeds the set maximum value
  809. for (UINT32 j = 0; j < numIndices; j++)
  810. {
  811. INT32 vertexIndex = indices[j];
  812. float weight = (float)weights[j];
  813. for (UINT32 k = 0; k < FBX_IMPORT_MAX_BONE_INFLUENCES; k++)
  814. {
  815. if (vertexIndex < 0 || vertexIndex >= numVertices)
  816. continue;
  817. if (weight >= influences[vertexIndex].weights[k])
  818. {
  819. for (UINT32 l = FBX_IMPORT_MAX_BONE_INFLUENCES - 2; l >= k; l--)
  820. {
  821. influences[vertexIndex].weights[l + 1] = influences[vertexIndex].weights[l];
  822. influences[vertexIndex].indices[l + 1] = influences[vertexIndex].indices[l];
  823. }
  824. influences[vertexIndex].weights[k] = weight;
  825. influences[vertexIndex].indices[k] = i;
  826. break;
  827. }
  828. }
  829. }
  830. }
  831. if (mesh.bones.empty())
  832. mesh.boneInfluences.clear();
  833. // Normalize weights
  834. UINT32 numInfluences = (UINT32)mesh.boneInfluences.size();
  835. for (UINT32 i = 0; i < numInfluences; i++)
  836. {
  837. float sum = 0.0f;
  838. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  839. sum += influences[i].weights[j];
  840. float invSum = 1.0f / sum;
  841. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  842. influences[i].weights[j] *= invSum;
  843. }
  844. }
  845. void FBXImporter::generateMissingTangentSpace(FBXImportScene& scene, const FBXImportOptions& options)
  846. {
  847. for (auto& mesh : scene.meshes)
  848. {
  849. UINT32 numVertices = (UINT32)mesh->positions.size();
  850. UINT32 numIndices = (UINT32)mesh->indices.size();
  851. if ((options.importNormals || options.importTangents) && mesh->normals.empty())
  852. {
  853. mesh->normals.resize(numVertices);
  854. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, mesh->normals.data());
  855. }
  856. if (options.importTangents && !mesh->UV[0].empty() && (mesh->tangents.empty() || mesh->bitangents.empty()))
  857. {
  858. mesh->tangents.resize(numVertices);
  859. mesh->bitangents.resize(numVertices);
  860. MeshUtility::calculateTangents(mesh->positions.data(), mesh->normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  861. numVertices, numIndices, mesh->tangents.data(), mesh->bitangents.data());
  862. }
  863. for (auto& shape : mesh->blendShapes)
  864. {
  865. for (auto& frame : shape.frames)
  866. {
  867. if ((options.importNormals || options.importTangents) && frame.normals.empty())
  868. {
  869. frame.normals.resize(numVertices);
  870. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, frame.normals.data());
  871. }
  872. if (options.importTangents && !mesh->UV[0].empty() && (frame.tangents.empty() || frame.bitangents.empty()))
  873. {
  874. mesh->tangents.resize(numVertices);
  875. mesh->bitangents.resize(numVertices);
  876. MeshUtility::calculateTangents(mesh->positions.data(), frame.normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  877. numVertices, numIndices, frame.tangents.data(), frame.bitangents.data());
  878. }
  879. }
  880. }
  881. }
  882. }
  883. void FBXImporter::importAnimations(FbxScene* scene, FBXImportOptions& importOptions, FBXImportScene& importScene)
  884. {
  885. FbxNode* root = scene->GetRootNode();
  886. UINT32 numAnimStacks = (UINT32)scene->GetSrcObjectCount<FbxAnimStack>();
  887. for (UINT32 i = 0; i < numAnimStacks; i++)
  888. {
  889. FbxAnimStack* animStack = scene->GetSrcObject<FbxAnimStack>(i);
  890. importScene.clips.push_back(FBXAnimationClip());
  891. FBXAnimationClip& clip = importScene.clips.back();
  892. clip.name = animStack->GetName();
  893. FbxTimeSpan timeSpan = animStack->GetLocalTimeSpan();
  894. clip.start = (float)timeSpan.GetStart().GetSecondDouble();
  895. clip.end = (float)timeSpan.GetStop().GetSecondDouble();
  896. UINT32 layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  897. if (layerCount > 1)
  898. {
  899. FbxAnimEvaluator* evaluator = scene->GetAnimationEvaluator();
  900. FbxTime startTime;
  901. startTime.SetSecondDouble(clip.start);
  902. FbxTime endTime;
  903. endTime.SetSecondDouble(clip.end);
  904. FbxTime sampleRate;
  905. if (importOptions.animResample)
  906. sampleRate.SetSecondDouble(importOptions.animSampleRate);
  907. else
  908. {
  909. FbxTime::EMode timeMode = scene->GetGlobalSettings().GetTimeMode();
  910. sampleRate.SetSecondDouble(1.0f / FbxTime::GetFrameRate(timeMode));
  911. }
  912. if (!animStack->BakeLayers(evaluator, startTime, endTime, sampleRate))
  913. continue;
  914. layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  915. }
  916. if (layerCount == 1)
  917. {
  918. FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(0);
  919. importAnimations(animLayer, root, importOptions, clip, importScene);
  920. }
  921. }
  922. }
  923. void FBXImporter::importAnimations(FbxAnimLayer* layer, FbxNode* node, FBXImportOptions& importOptions,
  924. FBXAnimationClip& clip, FBXImportScene& importScene)
  925. {
  926. FbxAnimCurve* translation[3];
  927. translation[0] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  928. translation[1] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  929. translation[2] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  930. FbxAnimCurve* rotation[3];
  931. rotation[0] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  932. rotation[1] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  933. rotation[2] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  934. FbxAnimCurve* scale[3];
  935. scale[0] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  936. scale[1] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  937. scale[2] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  938. auto hasCurveValues = [](FbxAnimCurve* curves[3])
  939. {
  940. for (UINT32 i = 0; i < 3; i++)
  941. {
  942. if (curves[i] != nullptr && curves[i]->KeyGetCount() > 0)
  943. return true;
  944. }
  945. return false;
  946. };
  947. bool hasBoneAnimation = hasCurveValues(translation) || hasCurveValues(rotation) || hasCurveValues(scale);
  948. if (hasBoneAnimation)
  949. {
  950. clip.boneAnimations.push_back(FBXBoneAnimation());
  951. FBXBoneAnimation& boneAnim = clip.boneAnimations.back();
  952. boneAnim.node = importScene.nodeMap[node];
  953. importCurve(translation[0], importOptions, boneAnim.translation[0], clip.start, clip.end);
  954. importCurve(translation[1], importOptions, boneAnim.translation[1], clip.start, clip.end);
  955. importCurve(translation[2], importOptions, boneAnim.translation[2], clip.start, clip.end);
  956. importCurve(scale[0], importOptions, boneAnim.scale[0], clip.start, clip.end);
  957. importCurve(scale[1], importOptions, boneAnim.scale[1], clip.start, clip.end);
  958. importCurve(scale[2], importOptions, boneAnim.scale[2], clip.start, clip.end);
  959. FBXAnimationCurve tempCurveRotation[3];
  960. importCurve(rotation[0], importOptions, tempCurveRotation[0], clip.start, clip.end);
  961. importCurve(rotation[1], importOptions, tempCurveRotation[1], clip.start, clip.end);
  962. importCurve(rotation[2], importOptions, tempCurveRotation[2], clip.start, clip.end);
  963. eulerToQuaternionCurves(tempCurveRotation, boneAnim.rotation);
  964. }
  965. if (importOptions.importBlendShapes)
  966. {
  967. FbxMesh* fbxMesh = node->GetMesh();
  968. if (fbxMesh != nullptr)
  969. {
  970. INT32 deformerCount = fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  971. for (INT32 i = 0; i < deformerCount; i++)
  972. {
  973. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  974. INT32 channelCount = deformer->GetBlendShapeChannelCount();
  975. for (INT32 j = 0; j < channelCount; j++)
  976. {
  977. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  978. FbxAnimCurve* curve = fbxMesh->GetShapeChannel(i, j, layer);
  979. if (curve != nullptr && curve->KeyGetCount() > 0)
  980. {
  981. clip.blendShapeAnimations.push_back(FBXBlendShapeAnimation());
  982. FBXBlendShapeAnimation& blendShapeAnim = clip.blendShapeAnimations.back();
  983. blendShapeAnim.blendShape = channel->GetName();
  984. importCurve(curve, importOptions, blendShapeAnim.curve, clip.start, clip.end);
  985. }
  986. }
  987. }
  988. }
  989. }
  990. UINT32 childCount = (UINT32)node->GetChildCount();
  991. for (UINT32 i = 0; i < childCount; i++)
  992. {
  993. FbxNode* child = node->GetChild(i);
  994. importAnimations(layer, child, importOptions, clip, importScene);
  995. }
  996. }
  997. void FBXImporter::eulerToQuaternionCurves(FBXAnimationCurve(&eulerCurves)[3], FBXAnimationCurve(&quatCurves)[4])
  998. {
  999. const float FIT_TIME = 0.33f;
  1000. INT32 numKeys = (INT32)eulerCurves[0].keyframes.size();
  1001. if (numKeys != (INT32)eulerCurves[1].keyframes.size() || numKeys != (INT32)eulerCurves[2].keyframes.size())
  1002. return;
  1003. auto eulerToQuaternion = [&](INT32 keyIdx, float time, const Quaternion& lastQuat)
  1004. {
  1005. Degree x = (Degree)eulerCurves[0].evaluate(time);
  1006. Degree y = (Degree)eulerCurves[1].evaluate(time);
  1007. Degree z = (Degree)eulerCurves[2].evaluate(time);
  1008. Quaternion quat(x, y, z);
  1009. // Flip quaternion in case rotation is over 180 degrees
  1010. if (keyIdx > 0)
  1011. {
  1012. float dot = quat.dot(lastQuat);
  1013. if (dot < 0.0f)
  1014. quat = Quaternion(-quat.x, -quat.y, -quat.z, -quat.w);
  1015. }
  1016. return quat;
  1017. };
  1018. struct FitKeyframe
  1019. {
  1020. float time;
  1021. Quaternion value;
  1022. };
  1023. Vector<FitKeyframe> fitQuaternions(numKeys * 2);
  1024. Quaternion lastQuat;
  1025. for (INT32 i = 0; i < numKeys; i++)
  1026. {
  1027. float time = eulerCurves[0].keyframes[i].time;
  1028. Quaternion quat = eulerToQuaternion(i, time, lastQuat);
  1029. // Calculate extra values between keys so we can better approximate tangents
  1030. if ((i + 1) < numKeys)
  1031. {
  1032. float nextTime = eulerCurves[0].keyframes[i + 1].time;
  1033. float dt = nextTime - time;
  1034. FitKeyframe& fitStart = fitQuaternions[i * 2 + 0];
  1035. FitKeyframe& fitEnd = fitQuaternions[i * 2 + 1];
  1036. fitStart.time = time + dt * FIT_TIME;
  1037. fitEnd.time = time + dt * (1.0f - FIT_TIME);
  1038. fitStart.value = eulerToQuaternion(i, fitStart.time, quat);
  1039. fitEnd.value = eulerToQuaternion(i, fitEnd.time, fitStart.value);
  1040. lastQuat = fitStart.value;
  1041. }
  1042. // TODO - If animation is looping I should also compare last and first for continuity
  1043. for (INT32 j = 0; j < 4; j++)
  1044. {
  1045. quatCurves[j].keyframes.push_back(FBXKeyFrame());
  1046. FBXKeyFrame& keyFrame = quatCurves[j].keyframes.back();
  1047. keyFrame.time = time;
  1048. keyFrame.value = quat[j];
  1049. keyFrame.inTangent = 0;
  1050. keyFrame.outTangent = 0;
  1051. }
  1052. }
  1053. // Recalculate tangents for quaternion curves
  1054. // TODO - There must be an analytical way to convert euler angle tangents
  1055. // to quaternion tangents, but I don't want to bother figuring it out
  1056. // until I have a test-bed for animation.
  1057. if (numKeys > 1)
  1058. {
  1059. // TODO - I could check per-key curve interpolation originally assigned in FBX
  1060. // and use that to generate linear/constant slopes. Currently I assume
  1061. // its all cubic.
  1062. // First key
  1063. {
  1064. const FitKeyframe& fitKeyFrame = fitQuaternions[0];
  1065. for (INT32 j = 0; j < 4; j++)
  1066. {
  1067. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[0];
  1068. float dt = fitKeyFrame.time - keyFrame.time;
  1069. keyFrame.inTangent = (fitKeyFrame.value[j] - keyFrame.value) / dt;
  1070. keyFrame.outTangent = keyFrame.inTangent;
  1071. }
  1072. }
  1073. // In-between keys
  1074. {
  1075. for (INT32 i = 1; i < (numKeys - 1); i++)
  1076. {
  1077. const FitKeyframe& fitPointStart = fitQuaternions[i * 2 - 1];
  1078. const FitKeyframe& fitPointEnd = fitQuaternions[i * 2 + 0];
  1079. for (INT32 j = 0; j < 4; j++)
  1080. {
  1081. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[i];
  1082. float dt0 = fitPointEnd.time - keyFrame.time;
  1083. float dt1 = keyFrame.time - fitPointStart.time;
  1084. float t0 = fitPointEnd.value[j] - keyFrame.value;
  1085. float t1 = keyFrame.value - fitPointStart.value[j];
  1086. keyFrame.inTangent = t0 / (0.5f * dt0) + t1 / (0.5f * dt1);
  1087. keyFrame.outTangent = keyFrame.inTangent;
  1088. }
  1089. }
  1090. }
  1091. // Last key
  1092. {
  1093. const FitKeyframe& fitKeyFrame = fitQuaternions[(numKeys - 2) * 2];
  1094. for (INT32 j = 0; j < 4; j++)
  1095. {
  1096. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[numKeys - 2];
  1097. float dt = keyFrame.time - fitKeyFrame.time;
  1098. keyFrame.inTangent = (keyFrame.value - fitKeyFrame.value[j]) / dt;
  1099. keyFrame.outTangent = keyFrame.inTangent;
  1100. }
  1101. }
  1102. }
  1103. }
  1104. void FBXImporter::importCurve(FbxAnimCurve* fbxCurve, FBXImportOptions& importOptions, FBXAnimationCurve& curve, float start, float end)
  1105. {
  1106. if (fbxCurve == nullptr)
  1107. return;
  1108. INT32 keyCount = fbxCurve->KeyGetCount();
  1109. if (importOptions.animResample)
  1110. {
  1111. float curveStart = std::numeric_limits<float>::infinity();
  1112. float curveEnd = -std::numeric_limits<float>::infinity();
  1113. for (INT32 i = 0; i < keyCount; i++)
  1114. {
  1115. FbxTime fbxTime = fbxCurve->KeyGetTime(i);
  1116. float time = (float)fbxTime.GetSecondDouble();
  1117. curveStart = std::min(time, curveStart);
  1118. curveEnd = std::max(time, curveEnd);
  1119. }
  1120. curveStart = Math::clamp(curveStart, start, end);
  1121. curveEnd = Math::clamp(curveEnd, start, end);
  1122. float curveLength = curveEnd - curveStart;
  1123. INT32 numSamples = Math::ceilToInt(curveLength / importOptions.animSampleRate);
  1124. // We don't use the exact provided sample rate but instead modify it slightly so it
  1125. // completely covers the curve range including start/end points while maintaining
  1126. // constant time step between keyframes.
  1127. float dt = curveLength / (float)numSamples;
  1128. INT32 lastKeyframe = 0;
  1129. INT32 lastLeftTangent = 0;
  1130. INT32 lastRightTangent = 0;
  1131. for (INT32 i = 0; i < numSamples; i++)
  1132. {
  1133. float sampleTime = std::min(curveStart + i * dt, curveEnd);
  1134. FbxTime fbxSampleTime;
  1135. fbxSampleTime.SetSecondDouble(sampleTime);
  1136. curve.keyframes.push_back(FBXKeyFrame());
  1137. FBXKeyFrame& keyFrame = curve.keyframes.back();
  1138. keyFrame.time = sampleTime;
  1139. keyFrame.value = fbxCurve->Evaluate(fbxSampleTime, &lastKeyframe);
  1140. keyFrame.inTangent = fbxCurve->EvaluateLeftDerivative(fbxSampleTime, &lastLeftTangent);
  1141. keyFrame.outTangent = fbxCurve->EvaluateRightDerivative(fbxSampleTime, &lastRightTangent);
  1142. }
  1143. }
  1144. else
  1145. {
  1146. for (int i = 0; i < keyCount; i++)
  1147. {
  1148. FbxTime fbxTime = fbxCurve->KeyGetTime(i);
  1149. float time = (float)fbxTime.GetSecondDouble();
  1150. if (time < start || time > end)
  1151. continue;
  1152. curve.keyframes.push_back(FBXKeyFrame());
  1153. FBXKeyFrame& keyFrame = curve.keyframes.back();
  1154. keyFrame.time = time;
  1155. keyFrame.value = fbxCurve->KeyGetValue(i);
  1156. keyFrame.inTangent = fbxCurve->KeyGetLeftDerivative(i);
  1157. keyFrame.outTangent = fbxCurve->KeyGetRightDerivative(i);
  1158. }
  1159. }
  1160. }
  1161. }