FBXSceneEncoder.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  1. #ifdef USE_FBX
  2. #include <algorithm>
  3. #include <string>
  4. #include "FBXSceneEncoder.h"
  5. #include "EncoderArguments.h"
  6. using namespace gameplay;
  7. /**
  8. * Returns the aspect ratio from the given camera.
  9. *
  10. * @param fbxCamera The FBX camera to get the aspect ratio from.
  11. *
  12. * @return The aspect ratio from the camera.
  13. */
  14. static float getAspectRatio(FbxCamera* fbxCamera);
  15. /**
  16. * Returns the field of view Y from the given camera.
  17. *
  18. * @param fbxCamera The camera to get the fiew of view from.
  19. *
  20. * @return The field of view Y.
  21. */
  22. static float getFieldOfView(FbxCamera* fbxCamera);
  23. /**
  24. * Loads the texture coordinates from given mesh's polygon part into the vertex.
  25. *
  26. * @param fbxMesh The mesh to get the polygon from.
  27. * @param uvs The UV list to load tex coords from.
  28. * @param uvSetIndex The UV set index of the uvs.
  29. * @param polyIndex The index of the polygon in the mesh.
  30. * @param posInPoly The position of the vertex in the polygon.
  31. * @param meshVertexIndex The index of the vertex in the mesh.
  32. * @param vertex The vertex to copy the texture coordinates to.
  33. */
  34. static void loadTextureCoords(FbxMesh* fbxMesh, const FbxGeometryElementUV* uvs, int uvSetIndex, int polyIndex, int posInPoly, int meshVertexIndex, Vertex* vertex);
  35. /**
  36. * Loads the normal from the mesh and adds it to the given vertex.
  37. *
  38. * @param fbxMesh The mesh to get the polygon from.
  39. * @param vertexIndex The vertex index in the mesh.
  40. * @param controlPointIndex The control point index.
  41. * @param vertex The vertex to copy to.
  42. */
  43. static void loadNormal(FbxMesh* fbxMesh, int vertexIndex, int controlPointIndex, Vertex* vertex);
  44. /**
  45. * Loads the tangent from the mesh and adds it to the given vertex.
  46. *
  47. * @param fbxMesh The mesh to load from.
  48. * @param vertexIndex The index of the vertex within fbxMesh.
  49. * @param vertex The vertex to copy to.
  50. */
  51. static void loadTangent(FbxMesh* fbxMesh, int vertexIndex, Vertex* vertex);
  52. /**
  53. * Loads the binormal from the mesh and adds it to the given vertex.
  54. *
  55. * @param fbxMesh The mesh to load from.
  56. * @param vertexIndex The index of the vertex within fbxMesh.
  57. * @param vertex The vertex to copy to.
  58. */
  59. static void loadBinormal(FbxMesh* fbxMesh, int vertexIndex, Vertex* vertex);
  60. /**
  61. * Loads the vertex diffuse color from the mesh and adds it to the given vertex.
  62. *
  63. * @param fbxMesh The mesh to load from.
  64. * @param vertexIndex The index of the vertex within fbxMesh.
  65. * @param vertex The vertex to copy to.
  66. */
  67. static void loadVertexColor(FbxMesh* fbxMesh, int vertexIndex, Vertex* vertex);
  68. /**
  69. * Loads the blend weight and blend indices data into the vertex.
  70. *
  71. * @param vertexWeights List of vertex weights. The x member contains the blendIndices. The y member contains the blendWeights.
  72. * @param vertex The vertex to copy the blend data to.
  73. */
  74. static void loadBlendData(const std::vector<Vector2>& vertexWeights, Vertex* vertex);
  75. /**
  76. * Loads the blend weights and blend indices from the given mesh.
  77. *
  78. * Each element of weights is a list of Vector2s where "x" is the blend index and "y" is the blend weight.
  79. *
  80. * @param fbxMesh The mesh to load from.
  81. * @param weights List of blend weights and blend indices for each vertex.
  82. *
  83. * @return True if this mesh has a mesh skin, false otherwise.
  84. */
  85. static bool loadBlendWeights(FbxMesh* fbxMesh, std::vector<std::vector<Vector2> >& weights);
  86. /**
  87. * Copies from an FBX matrix to a float[16] array.
  88. */
  89. static void copyMatrix(const FbxMatrix& fbxMatrix, float* matrix);
  90. /**
  91. * Copies from an FBX matrix to a gameplay matrix.
  92. */
  93. static void copyMatrix(const FbxMatrix& fbxMatrix, Matrix& matrix);
  94. /**
  95. * Finds the min and max start time and stop time of the given animation curve.
  96. *
  97. * startTime is updated if the animation curve contains a start time that is less than startTime.
  98. * stopTime is updated if the animation curve contains a stop time that is greater than stopTime.
  99. * frameRate is updated if the animation curve contains a frame rate that is greater than frameRate.
  100. *
  101. * @param animCurve The animation curve to read from.
  102. * @param startTime The min start time. (in/out)
  103. * @param stopTime The max stop time. (in/out)
  104. * @param frameRate The frame rate. (in/out)
  105. */
  106. static void findMinMaxTime(FbxAnimCurve* animCurve, float* startTime, float* stopTime, float* frameRate);
  107. /**
  108. * Appends key frame data to the given node for the specified animation target attribute.
  109. *
  110. * @param fbxNode The node to get the matrix transform from.
  111. * @param channel The aniamtion channel to write values into.
  112. * @param time The time of the keyframe.
  113. * @param scale The evaluated scale for the keyframe.
  114. * @param rotation The evalulated rotation for the keyframe.
  115. * @param translation The evalulated translation for the keyframe.
  116. */
  117. static void appendKeyFrame(FbxNode* fbxNode, AnimationChannel* channel, float time, const Vector3& scale, const Quaternion& rotation, const Vector3& translation);
  118. /**
  119. * Decomposes the given node's matrix transform at the given time and copies to scale, rotation and translation.
  120. *
  121. * @param fbxNode The node to get the matrix transform from.
  122. * @param time The time to get the matrix transform from.
  123. * @param scale The scale to copy to.
  124. * @param rotation The rotation to copy to.
  125. * @param translation The translation to copy to.
  126. */
  127. static void decompose(FbxNode* fbxNode, float time, Vector3* scale, Quaternion* rotation, Vector3* translation);
  128. /**
  129. * Creates an animation channel that targets the given node and target attribute using the given key times and key values.
  130. *
  131. * @param fbxNode The node to target.
  132. * @param targetAttrib The attribute type to target.
  133. * @param keyTimes The key times for the animation channel.
  134. * @param keyValues The key values for the animation channel.
  135. *
  136. * @return The newly created animation channel.
  137. */
  138. static AnimationChannel* createAnimationChannel(FbxNode* fbxNode, unsigned int targetAttrib, const std::vector<float>& keyTimes, const std::vector<float>& keyValues);
  139. void addScaleChannel(Animation* animation, FbxNode* fbxNode, float startTime, float stopTime);
  140. void addTranslateChannel(Animation* animation, FbxNode* fbxNode, float startTime, float stopTime);
  141. /**
  142. * Determines if it is possible to automatically group animations for mesh skins.
  143. *
  144. * @param fbxScene The FBX scene to search.
  145. *
  146. * @return True if there is at least one mesh skin that has animations that can be grouped.
  147. */
  148. bool isGroupAnimationPossible(FbxScene* fbxScene);
  149. bool isGroupAnimationPossible(FbxNode* fbxNode);
  150. bool isGroupAnimationPossible(FbxMesh* fbxMesh);
  151. FbxAnimCurve* getCurve(FbxPropertyT<FbxDouble3>& prop, FbxAnimLayer* animLayer, const char* pChannel)
  152. {
  153. #if FBXSDK_VERSION_MAJOR == 2013 && FBXSDK_VERSION_MINOR == 1
  154. return prop.GetCurve<FbxAnimCurve>(animLayer, pChannel);
  155. #else
  156. return prop.GetCurve(animLayer, pChannel);
  157. #endif
  158. }
  159. ////////////////////////////////////
  160. // Member Functions
  161. ////////////////////////////////////
  162. FBXSceneEncoder::FBXSceneEncoder()
  163. : _groupAnimation(NULL), _autoGroupAnimations(false)
  164. {
  165. }
  166. FBXSceneEncoder::~FBXSceneEncoder()
  167. {
  168. }
  169. void FBXSceneEncoder::write(const std::string& filepath, const EncoderArguments& arguments)
  170. {
  171. FbxManager* sdkManager = FbxManager::Create();
  172. FbxIOSettings *ios = FbxIOSettings::Create(sdkManager, IOSROOT);
  173. sdkManager->SetIOSettings(ios);
  174. FbxImporter* importer = FbxImporter::Create(sdkManager,"");
  175. if (!importer->Initialize(filepath.c_str(), -1, sdkManager->GetIOSettings()))
  176. {
  177. LOG(1, "Call to FbxImporter::Initialize() failed.\n");
  178. LOG(1, "Error returned: %s\n\n", importer->GetLastErrorString());
  179. exit(-1);
  180. }
  181. FbxScene* fbxScene = FbxScene::Create(sdkManager,"__FBX_SCENE__");
  182. print("Loading FBX file.");
  183. importer->Import(fbxScene);
  184. importer->Destroy();
  185. // Determine if animations should be grouped.
  186. if (arguments.getGroupAnimationAnimationId().empty() && isGroupAnimationPossible(fbxScene))
  187. {
  188. if (promptUserGroupAnimations())
  189. {
  190. _autoGroupAnimations = true;
  191. }
  192. }
  193. print("Loading Scene.");
  194. loadScene(fbxScene);
  195. print("Loading animations.");
  196. loadAnimations(fbxScene, arguments);
  197. sdkManager->Destroy();
  198. print("Optimizing GamePlay Binary.");
  199. _gamePlayFile.adjust();
  200. if (_autoGroupAnimations)
  201. {
  202. _gamePlayFile.groupMeshSkinAnimations();
  203. }
  204. std::string outputFilePath = arguments.getOutputFilePath();
  205. if (arguments.textOutputEnabled())
  206. {
  207. int pos = outputFilePath.find_last_of('.');
  208. if (pos > 2)
  209. {
  210. std::string path = outputFilePath.substr(0, pos);
  211. path.append(".xml");
  212. LOG(1, "Saving debug file: %s\n", path.c_str());
  213. if (!_gamePlayFile.saveText(path))
  214. {
  215. LOG(1, "Error writing text file: %s\n", path.c_str());
  216. }
  217. }
  218. }
  219. else
  220. {
  221. LOG(1, "Saving binary file: %s\n", outputFilePath.c_str());
  222. if (!_gamePlayFile.saveBinary(outputFilePath))
  223. {
  224. LOG(1, "Error writing binary file: %s\n", outputFilePath.c_str());
  225. }
  226. }
  227. }
  228. void FBXSceneEncoder::loadScene(FbxScene* fbxScene)
  229. {
  230. Scene* scene = new Scene();
  231. scene->setId(fbxScene->GetName());
  232. if (scene->getId().length() == 0)
  233. {
  234. scene->setId("__SCENE__");
  235. }
  236. // Load all of the nodes and their contents.
  237. FbxNode* rootNode = fbxScene->GetRootNode();
  238. if (rootNode)
  239. {
  240. print("Triangulate.");
  241. triangulateRecursive(rootNode);
  242. print("Load nodes.");
  243. // Don't include the FBX root node in the GPB.
  244. const int childCount = rootNode->GetChildCount();
  245. for (int i = 0; i < childCount; ++i)
  246. {
  247. Node* node = loadNode(rootNode->GetChild(i));
  248. if (node)
  249. {
  250. scene->add(node);
  251. }
  252. }
  253. }
  254. // Load the MeshSkin information from the scene's poses.
  255. loadBindShapes(fbxScene);
  256. // Find the ambient light of the scene
  257. FbxColor ambientColor = fbxScene->GetGlobalSettings().GetAmbientColor();
  258. scene->setAmbientColor((float)ambientColor.mRed, (float)ambientColor.mGreen, (float)ambientColor.mBlue);
  259. // Assign the first camera node (if there is one) in the scene as the active camera
  260. // This ensures that if there's a camera in the scene that it is assigned as the
  261. // active camera.
  262. // TODO: add logic to find the "active" camera node in the fbxScene
  263. scene->setActiveCameraNode(scene->getFirstCameraNode());
  264. _gamePlayFile.addScene(scene);
  265. }
  266. void FBXSceneEncoder::loadAnimationChannels(FbxAnimLayer* animLayer, FbxNode* fbxNode, Animation* animation)
  267. {
  268. const std::string* targetId = NULL;
  269. const char* name = fbxNode->GetName();
  270. Node* node = _gamePlayFile.getNode(name);
  271. if (node)
  272. {
  273. targetId = &node->getId();
  274. }
  275. // Determine which properties are animated on this node
  276. // Find the transform at each key frame
  277. // TODO: Ignore properties that are not animated (scale, rotation, translation)
  278. // This should result in only one animation channel per animated node.
  279. float startTime = FLT_MAX, stopTime = -1.0f, frameRate = -FLT_MAX;
  280. bool tx = false, ty = false, tz = false, rx = false, ry = false, rz = false, sx = false, sy = false, sz = false;
  281. FbxAnimCurve* animCurve = NULL;
  282. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  283. if (animCurve)
  284. {
  285. tx = true;
  286. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  287. }
  288. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  289. if (animCurve)
  290. {
  291. ty = true;
  292. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  293. }
  294. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  295. if (animCurve)
  296. {
  297. tz = true;
  298. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  299. }
  300. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  301. if (animCurve)
  302. {
  303. rx = true;
  304. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  305. }
  306. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  307. if (animCurve)
  308. {
  309. ry = true;
  310. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  311. }
  312. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  313. if (animCurve)
  314. {
  315. rz = true;
  316. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  317. }
  318. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  319. if (animCurve)
  320. {
  321. sx = true;
  322. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  323. }
  324. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  325. if (animCurve)
  326. {
  327. sy = true;
  328. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  329. }
  330. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  331. if (animCurve)
  332. {
  333. sz = true;
  334. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  335. }
  336. if (!(sx || sy || sz || rx || ry || rz || tx || ty || tz))
  337. return; // no animation channels
  338. assert(startTime != FLT_MAX);
  339. assert(stopTime >= 0.0f);
  340. // Determine which animation channels to create
  341. std::vector<unsigned int> channelAttribs;
  342. if (sx && sy && sz)
  343. {
  344. if (rx || ry || rz)
  345. {
  346. if (tx && ty && tz)
  347. {
  348. channelAttribs.push_back(Transform::ANIMATE_SCALE_ROTATE_TRANSLATE);
  349. }
  350. else
  351. {
  352. channelAttribs.push_back(Transform::ANIMATE_SCALE_ROTATE);
  353. if (tx)
  354. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  355. if (ty)
  356. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  357. if (tz)
  358. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  359. }
  360. }
  361. else
  362. {
  363. if (tx && ty && tz)
  364. {
  365. channelAttribs.push_back(Transform::ANIMATE_SCALE_TRANSLATE);
  366. }
  367. else
  368. {
  369. channelAttribs.push_back(Transform::ANIMATE_SCALE);
  370. if (tx)
  371. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  372. if (ty)
  373. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  374. if (tz)
  375. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  376. }
  377. }
  378. }
  379. else
  380. {
  381. if (rx || ry || rz)
  382. {
  383. if (tx && ty && tz)
  384. {
  385. channelAttribs.push_back(Transform::ANIMATE_ROTATE_TRANSLATE);
  386. }
  387. else
  388. {
  389. channelAttribs.push_back(Transform::ANIMATE_ROTATE);
  390. if (tx)
  391. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  392. if (ty)
  393. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  394. if (tz)
  395. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  396. }
  397. }
  398. else
  399. {
  400. if (tx && ty && tz)
  401. {
  402. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE);
  403. }
  404. else
  405. {
  406. if (tx)
  407. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  408. if (ty)
  409. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  410. if (tz)
  411. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  412. }
  413. }
  414. if (sx)
  415. channelAttribs.push_back(Transform::ANIMATE_SCALE_X);
  416. if (sy)
  417. channelAttribs.push_back(Transform::ANIMATE_SCALE_Y);
  418. if (sz)
  419. channelAttribs.push_back(Transform::ANIMATE_SCALE_Z);
  420. }
  421. unsigned int channelCount = channelAttribs.size();
  422. assert(channelCount > 0);
  423. // Allocate channel list
  424. for (unsigned int i = 0; i < channelCount; ++i)
  425. {
  426. AnimationChannel* channel = new AnimationChannel();
  427. channel->setTargetId(name);
  428. channel->setInterpolation(AnimationChannel::LINEAR);
  429. channel->setTargetAttribute(channelAttribs[i]);
  430. animation->add(channel);
  431. }
  432. // Evaulate animation curve in increments of frameRate and populate channel data.
  433. FbxAMatrix fbxMatrix;
  434. Matrix matrix;
  435. float increment = 1000.0f / frameRate;
  436. for (float time = startTime; time <= stopTime; time += increment)
  437. {
  438. // Clamp time to stopTime
  439. time = std::min(time, stopTime);
  440. // Evalulate the animation at this time
  441. FbxTime kTime;
  442. kTime.SetMilliSeconds((FbxLongLong)time);
  443. fbxMatrix = fbxNode->EvaluateLocalTransform(kTime);
  444. copyMatrix(fbxMatrix, matrix);
  445. // Decompose the evalulated transformation matrix into separate
  446. // scale, rotation and translation.
  447. Vector3 scale;
  448. Quaternion rotation;
  449. Vector3 translation;
  450. matrix.decompose(&scale, &rotation, &translation);
  451. rotation.normalize();
  452. // Append keyframe data to all channels
  453. for (unsigned int i = 0; i < channelCount; ++i)
  454. {
  455. appendKeyFrame(fbxNode, animation->getAnimationChannel(i), time, scale, rotation, translation);
  456. }
  457. }
  458. if (_groupAnimation != animation)
  459. {
  460. // TODO explain
  461. _gamePlayFile.addAnimation(animation);
  462. }
  463. }
  464. void FBXSceneEncoder::loadAnimationLayer(FbxAnimLayer* fbxAnimLayer, FbxNode* fbxNode, const EncoderArguments& arguments)
  465. {
  466. bool animationGroupId = false;
  467. const char* name = fbxNode->GetName();
  468. // Check if this node's animations are supposed to be grouped
  469. if (name)
  470. {
  471. std::string str = name;
  472. if (arguments.containsGroupNodeId(str))
  473. {
  474. animationGroupId = true;
  475. _groupAnimation = new Animation();
  476. _groupAnimation->setId(arguments.getAnimationId(str));
  477. }
  478. }
  479. Animation* animation = _groupAnimation;
  480. if (!_groupAnimation)
  481. {
  482. animation = new Animation();
  483. animation->setId(name);
  484. }
  485. loadAnimationChannels(fbxAnimLayer, fbxNode, animation);
  486. const int childCount = fbxNode->GetChildCount();
  487. for (int modelCount = 0; modelCount < childCount; ++modelCount)
  488. {
  489. loadAnimationLayer(fbxAnimLayer, fbxNode->GetChild(modelCount), arguments);
  490. }
  491. if (animationGroupId)
  492. {
  493. _gamePlayFile.addAnimation(_groupAnimation);
  494. _groupAnimation = NULL;
  495. }
  496. }
  497. void FBXSceneEncoder::loadAnimations(FbxScene* fbxScene, const EncoderArguments& arguments)
  498. {
  499. FbxAnimEvaluator* evaluator = fbxScene->GetEvaluator();
  500. if (!evaluator)
  501. return;
  502. FbxAnimStack* animStack = evaluator->GetContext();
  503. if (!animStack)
  504. return;
  505. for (int i = 0; i < fbxScene->GetSrcObjectCount(FBX_TYPE(FbxAnimStack)); ++i)
  506. {
  507. FbxAnimStack* animStack = FbxCast<FbxAnimStack>(fbxScene->GetSrcObject(FBX_TYPE(FbxAnimStack), i));
  508. int nbAnimLayers = animStack->GetMemberCount(FBX_TYPE(FbxAnimLayer));
  509. for (int l = 0; l < nbAnimLayers; ++l)
  510. {
  511. FbxAnimLayer* animLayer = animStack->GetMember(FBX_TYPE(FbxAnimLayer), l);
  512. loadAnimationLayer(animLayer, fbxScene->GetRootNode(), arguments);
  513. }
  514. }
  515. }
  516. Node* FBXSceneEncoder::loadNode(FbxNode* fbxNode)
  517. {
  518. Node* node = NULL;
  519. // Check if this node has already been loaded
  520. const char* id = fbxNode->GetName();
  521. if (id && strlen(id) > 0)
  522. {
  523. node = _gamePlayFile.getNode(fbxNode->GetName());
  524. if (node)
  525. {
  526. return node;
  527. }
  528. }
  529. node = new Node();
  530. if (id)
  531. {
  532. node->setId(id);
  533. }
  534. _gamePlayFile.addNode(node);
  535. transformNode(fbxNode, node);
  536. loadCamera(fbxNode, node);
  537. loadLight(fbxNode, node);
  538. loadModel(fbxNode, node);
  539. if (fbxNode->GetSkeleton())
  540. {
  541. // Indicate that this is a joint node for the purpose of debugging.
  542. // The XML debug output will print that this node is a joint.
  543. node->setIsJoint(true);
  544. }
  545. // Load child nodes
  546. const int childCount = fbxNode->GetChildCount();
  547. for (int i = 0; i < childCount; ++i)
  548. {
  549. Node* child = loadNode(fbxNode->GetChild(i));
  550. if (child)
  551. {
  552. node->addChild(child);
  553. }
  554. }
  555. return node;
  556. }
  557. Mesh* FBXSceneEncoder::getMesh(FbxUInt64 meshId)
  558. {
  559. // Check if this mesh was already loaded.
  560. std::map<FbxUInt64, Mesh*>::iterator it = _meshes.find(meshId);
  561. if (it != _meshes.end())
  562. {
  563. return it->second;
  564. }
  565. return NULL;
  566. }
  567. void FBXSceneEncoder::saveMesh(FbxUInt64 meshId, Mesh* mesh)
  568. {
  569. assert(mesh);
  570. if (!getMesh(meshId))
  571. {
  572. _meshes[meshId] = mesh;
  573. }
  574. }
  575. void FBXSceneEncoder::print(const char* str)
  576. {
  577. LOG(1, "%s\n", str);
  578. }
  579. void FBXSceneEncoder::transformNode(FbxNode* fbxNode, Node* node)
  580. {
  581. FbxAMatrix matrix;
  582. if (fbxNode->GetCamera() || fbxNode->GetLight())
  583. {
  584. // TODO: Why is this necessary for Camera and Light?
  585. matrix.SetTRS(fbxNode->LclTranslation.Get(), fbxNode->LclRotation.Get(), fbxNode->LclScaling.Get());
  586. }
  587. else
  588. {
  589. matrix = fbxNode->EvaluateLocalTransform();
  590. }
  591. float m[16];
  592. copyMatrix(matrix, m);
  593. node->setTransformMatrix(m);
  594. }
  595. void FBXSceneEncoder::loadBindShapes(FbxScene* fbxScene)
  596. {
  597. float m[16];
  598. const int poseCount = fbxScene->GetPoseCount();
  599. for (int i = 0; i < poseCount; ++i)
  600. {
  601. FbxPose* pose = fbxScene->GetPose(i);
  602. assert(pose);
  603. if (pose->IsBindPose() && pose->GetCount() > 0)
  604. {
  605. FbxNode* fbxNode = pose->GetNode(0);
  606. if (fbxNode->GetMesh() != NULL)
  607. {
  608. Node* node = _gamePlayFile.getNode(fbxNode->GetName());
  609. assert(node && node->getModel());
  610. Model* model = node->getModel();
  611. if (model && model->getSkin())
  612. {
  613. MeshSkin* skin = model->getSkin();
  614. copyMatrix(pose->GetMatrix(0), m);
  615. skin->setBindShape(m);
  616. }
  617. }
  618. }
  619. }
  620. }
  621. void FBXSceneEncoder::loadCamera(FbxNode* fbxNode, Node* node)
  622. {
  623. FbxCamera* fbxCamera = fbxNode->GetCamera();
  624. if (!fbxCamera)
  625. {
  626. return;
  627. }
  628. Camera* camera = new Camera();
  629. const char* name = fbxNode->GetName();
  630. if (name)
  631. {
  632. std::string id(name);
  633. id.append("_Camera");
  634. camera->setId(id);
  635. }
  636. camera->setAspectRatio(getAspectRatio(fbxCamera));
  637. camera->setNearPlane((float)fbxCamera->NearPlane.Get());
  638. camera->setFarPlane((float)fbxCamera->FarPlane.Get());
  639. if (fbxCamera->ProjectionType.Get() == FbxCamera::eOrthogonal)
  640. {
  641. camera->setOrthographic();
  642. camera->setViewportWidth((float)fbxCamera->GetApertureWidth());
  643. camera->setViewportWidth((float)fbxCamera->GetApertureHeight());
  644. // xmag in FBX can be calculated from: OrthoZoom * 30.0 / 2.0
  645. camera->setViewportWidth((float)fbxCamera->OrthoZoom.Get() * 15.0f);
  646. }
  647. else if (fbxCamera->ProjectionType.Get() == FbxCamera::ePerspective)
  648. {
  649. camera->setPerspective();
  650. camera->setFieldOfView(getFieldOfView(fbxCamera));
  651. }
  652. else
  653. {
  654. LOG(2, "Warning: Unknown camera type in node.\n");
  655. return;
  656. }
  657. _gamePlayFile.addCamera(camera);
  658. node->setCamera(camera);
  659. }
  660. void FBXSceneEncoder::loadLight(FbxNode* fbxNode, Node* node)
  661. {
  662. FbxLight* fbxLight = fbxNode->GetLight();
  663. if (!fbxLight)
  664. {
  665. return;
  666. }
  667. Light* light = new Light();
  668. const char* name = fbxNode->GetName();
  669. if (name)
  670. {
  671. std::string id(name);
  672. id.append("_Light");
  673. light->setId(id);
  674. }
  675. FbxDouble3 color = fbxLight->Color.Get();
  676. light->setColor((float)color[0], (float)color[1], (float)color[2]);
  677. switch (fbxLight->LightType.Get())
  678. {
  679. case FbxLight::ePoint:
  680. {
  681. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  682. switch (decayType)
  683. {
  684. case FbxLight::eNone:
  685. // No decay. Can assume we have an ambient light, because ambient lights in the scene are
  686. // converted to point lights with no decay when exporting to FBX.
  687. light->setAmbientLight();
  688. break;
  689. case FbxLight::eLinear:
  690. light->setPointLight();
  691. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  692. break;
  693. case FbxLight::eQuadratic:
  694. light->setPointLight();
  695. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  696. break;
  697. case FbxLight::eCubic:
  698. default:
  699. // Not supported..
  700. break;
  701. }
  702. break;
  703. }
  704. case FbxLight::eDirectional:
  705. {
  706. light->setDirectionalLight();
  707. break;
  708. }
  709. case FbxLight::eSpot:
  710. {
  711. light->setSpotLight();
  712. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  713. switch (decayType)
  714. {
  715. case FbxLight::eNone:
  716. // No decay.
  717. break;
  718. case FbxLight::eLinear:
  719. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  720. break;
  721. case FbxLight::eQuadratic:
  722. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  723. break;
  724. case FbxLight::eCubic:
  725. // Not supported..
  726. break;
  727. }
  728. light->setFalloffAngle(MATH_DEG_TO_RAD((float)fbxLight->OuterAngle.Get())); // fall off angle
  729. break;
  730. }
  731. default:
  732. {
  733. LOG(2, "Warning: Unknown light type in node.\n");
  734. return;
  735. }
  736. }
  737. _gamePlayFile.addLight(light);
  738. node->setLight(light);
  739. }
  740. void FBXSceneEncoder::loadModel(FbxNode* fbxNode, Node* node)
  741. {
  742. FbxMesh* fbxMesh = fbxNode->GetMesh();
  743. if (!fbxMesh)
  744. {
  745. return;
  746. }
  747. if (fbxMesh->IsTriangleMesh())
  748. {
  749. Mesh* mesh = loadMesh(fbxMesh);
  750. Model* model = new Model();
  751. model->setMesh(mesh);
  752. node->setModel(model);
  753. loadSkin(fbxMesh, model);
  754. if (model->getSkin())
  755. {
  756. // TODO: explain
  757. node->resetTransformMatrix();
  758. }
  759. }
  760. }
  761. void FBXSceneEncoder::loadSkin(FbxMesh* fbxMesh, Model* model)
  762. {
  763. const int deformerCount = fbxMesh->GetDeformerCount();
  764. for (int i = 0; i < deformerCount; ++i)
  765. {
  766. FbxDeformer* deformer = fbxMesh->GetDeformer(i);
  767. if (deformer->GetDeformerType() == FbxDeformer::eSkin)
  768. {
  769. FbxSkin* fbxSkin = static_cast<FbxSkin*>(deformer);
  770. MeshSkin* skin = new MeshSkin();
  771. std::vector<std::string> jointNames;
  772. std::vector<Node*> joints;
  773. std::vector<Matrix> bindPoses;
  774. const int clusterCount = fbxSkin->GetClusterCount();
  775. for (int j = 0; j < clusterCount; ++j)
  776. {
  777. FbxCluster* cluster = fbxSkin->GetCluster(j);
  778. assert(cluster);
  779. FbxNode* linkedNode = cluster->GetLink();
  780. assert(linkedNode);
  781. if (linkedNode->GetSkeleton())
  782. {
  783. const char* jointName = linkedNode->GetName();
  784. assert(jointName);
  785. jointNames.push_back(jointName);
  786. Node* joint = loadNode(linkedNode);
  787. assert(joint);
  788. joints.push_back(joint);
  789. FbxAMatrix matrix;
  790. cluster->GetTransformLinkMatrix(matrix);
  791. Matrix m;
  792. copyMatrix(matrix.Inverse(), m);
  793. bindPoses.push_back(m);
  794. }
  795. }
  796. skin->setJointNames(jointNames);
  797. skin->setJoints(joints);
  798. skin->setBindPoses(bindPoses);
  799. model->setSkin(skin);
  800. break;
  801. }
  802. }
  803. }
  804. Mesh* FBXSceneEncoder::loadMesh(FbxMesh* fbxMesh)
  805. {
  806. // Check if this mesh has already been loaded.
  807. Mesh* mesh = getMesh(fbxMesh->GetUniqueID());
  808. if (mesh)
  809. {
  810. return mesh;
  811. }
  812. mesh = new Mesh();
  813. // GamePlay requires that a mesh have a unique ID but FbxMesh doesn't have a string ID.
  814. const char* name = fbxMesh->GetNode()->GetName();
  815. if (name)
  816. {
  817. std::string id(name);
  818. id.append("_Mesh");
  819. mesh->setId(id);
  820. }
  821. // The number of mesh parts is equal to the number of materials that affect this mesh.
  822. // There is always at least one mesh part.
  823. std::vector<MeshPart*> meshParts;
  824. const int materialCount = fbxMesh->GetNode()->GetMaterialCount();
  825. int meshPartSize = (materialCount > 0) ? materialCount : 1;
  826. for (int i = 0; i < meshPartSize; ++i)
  827. {
  828. meshParts.push_back(new MeshPart());
  829. }
  830. // Find the blend weights and blend indices if this mesh is skinned.
  831. std::vector<std::vector<Vector2> > weights;
  832. bool hasSkin = loadBlendWeights(fbxMesh, weights);
  833. // Get list of uv sets for mesh
  834. FbxStringList uvSetNameList;
  835. fbxMesh->GetUVSetNames(uvSetNameList);
  836. const int uvSetCount = uvSetNameList.GetCount();
  837. int vertexIndex = 0;
  838. FbxVector4* controlPoints = fbxMesh->GetControlPoints();
  839. const int polygonCount = fbxMesh->GetPolygonCount();
  840. for (int polyIndex = 0; polyIndex < polygonCount; ++polyIndex)
  841. {
  842. const int polygonSize = fbxMesh->GetPolygonSize(polyIndex);
  843. for (int posInPoly = 0; posInPoly < polygonSize; ++posInPoly)
  844. {
  845. int controlPointIndex = fbxMesh->GetPolygonVertex(polyIndex, posInPoly);
  846. Vertex vertex;
  847. FbxVector4& position = controlPoints[controlPointIndex];
  848. vertex.position.x = (float)position[0];
  849. vertex.position.y = (float)position[1];
  850. vertex.position.z = (float)position[2];
  851. // Load tex coords for all uv sets
  852. for (int uvSetIndex = 0; uvSetIndex < uvSetCount; ++uvSetIndex)
  853. {
  854. const FbxGeometryElementUV* uvElement = fbxMesh->GetElementUV(uvSetNameList.GetStringAt(uvSetIndex));
  855. if (uvElement)
  856. loadTextureCoords(fbxMesh, uvElement, uvSetIndex, polyIndex, posInPoly, vertexIndex, &vertex);
  857. }
  858. // Load other data
  859. loadNormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  860. loadTangent(fbxMesh, vertexIndex, &vertex);
  861. loadBinormal(fbxMesh, vertexIndex, &vertex);
  862. loadVertexColor(fbxMesh, vertexIndex, &vertex);
  863. if (hasSkin)
  864. {
  865. loadBlendData(weights[controlPointIndex], &vertex);
  866. }
  867. // Determine which mesh part this vertex index should be added to based on the material that affects it.
  868. int meshPartIndex = 0;
  869. const int elementMatrialCount = fbxMesh->GetElementMaterialCount();
  870. for (int k = 0; k < elementMatrialCount; ++k)
  871. {
  872. FbxGeometryElementMaterial* elementMaterial = fbxMesh->GetElementMaterial(k);
  873. meshPartIndex = elementMaterial->GetIndexArray().GetAt(polyIndex);
  874. }
  875. // Add the vertex to the mesh if it hasn't already been added and find the vertex index.
  876. unsigned int index;
  877. if (mesh->contains(vertex))
  878. {
  879. index = mesh->getVertexIndex(vertex);
  880. }
  881. else
  882. {
  883. index = mesh->addVertex(vertex);
  884. }
  885. meshParts[meshPartIndex]->addIndex(index);
  886. vertexIndex++;
  887. }
  888. }
  889. const size_t meshpartsSize = meshParts.size();
  890. for (size_t i = 0; i < meshpartsSize; ++i)
  891. {
  892. mesh->addMeshPart(meshParts[i]);
  893. }
  894. // The order that the vertex elements are add to the list matters.
  895. // It should be the same order as how the Vertex data is written.
  896. // Position
  897. mesh->addVetexAttribute(POSITION, Vertex::POSITION_COUNT);
  898. const Vertex& vertex = mesh->vertices[0];
  899. // Normals
  900. if (vertex.hasNormal)
  901. {
  902. mesh->addVetexAttribute(NORMAL, Vertex::NORMAL_COUNT);
  903. }
  904. // Tangents
  905. if (vertex.hasTangent)
  906. {
  907. mesh->addVetexAttribute(TANGENT, Vertex::TANGENT_COUNT);
  908. }
  909. // Binormals
  910. if (vertex.hasBinormal)
  911. {
  912. mesh->addVetexAttribute(BINORMAL, Vertex::BINORMAL_COUNT);
  913. }
  914. // Texture Coordinates
  915. for (unsigned int i = 0; i < MAX_UV_SETS; ++i)
  916. {
  917. if (vertex.hasTexCoord[i])
  918. {
  919. mesh->addVetexAttribute(TEXCOORD0 + i, Vertex::TEXCOORD_COUNT);
  920. }
  921. }
  922. // Diffuse Color
  923. if (vertex.hasDiffuse)
  924. {
  925. mesh->addVetexAttribute(COLOR, Vertex::DIFFUSE_COUNT);
  926. }
  927. // Skinning BlendWeights BlendIndices
  928. if (vertex.hasWeights)
  929. {
  930. mesh->addVetexAttribute(BLENDWEIGHTS, Vertex::BLEND_WEIGHTS_COUNT);
  931. mesh->addVetexAttribute(BLENDINDICES, Vertex::BLEND_INDICES_COUNT);
  932. }
  933. _gamePlayFile.addMesh(mesh);
  934. saveMesh(fbxMesh->GetUniqueID(), mesh);
  935. return mesh;
  936. }
  937. void FBXSceneEncoder::triangulateRecursive(FbxNode* fbxNode)
  938. {
  939. // Triangulate all NURBS, patch and mesh under this node recursively.
  940. FbxNodeAttribute* nodeAttribute = fbxNode->GetNodeAttribute();
  941. if (nodeAttribute)
  942. {
  943. if (nodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh ||
  944. nodeAttribute->GetAttributeType() == FbxNodeAttribute::eNurbs ||
  945. nodeAttribute->GetAttributeType() == FbxNodeAttribute::eNurbsSurface ||
  946. nodeAttribute->GetAttributeType() == FbxNodeAttribute::ePatch)
  947. {
  948. FbxGeometryConverter converter(fbxNode->GetFbxManager());
  949. converter.TriangulateInPlace(fbxNode);
  950. }
  951. }
  952. const int childCount = fbxNode->GetChildCount();
  953. for (int childIndex = 0; childIndex < childCount; ++childIndex)
  954. {
  955. triangulateRecursive(fbxNode->GetChild(childIndex));
  956. }
  957. }
  958. ////////////////////////////////////
  959. // Functions
  960. ////////////////////////////////////
  961. float getAspectRatio(FbxCamera* fbxCamera)
  962. {
  963. return (float)fbxCamera->FilmAspectRatio.Get();
  964. /*
  965. FbxCamera::ECameraAspectRatioMode camAspectRatioMode = fbxCamera->GetAspectRatioMode();
  966. double aspectX = fbxCamera->AspectWidth.Get();
  967. double aspectY = fbxCamera->AspectHeight.Get();
  968. double aspectRatio = 1.333333;
  969. switch ( camAspectRatioMode)
  970. {
  971. case FbxCamera::eWINDOW_SIZE:
  972. aspectRatio = aspectX / aspectY;
  973. break;
  974. case FbxCamera::eFIXED_RATIO:
  975. aspectRatio = aspectX;
  976. break;
  977. case FbxCamera::eFIXED_RESOLUTION:
  978. aspectRatio = aspectX / aspectY * fbxCamera->GetPixelRatio();
  979. break;
  980. case FbxCamera::eFIXED_WIDTH:
  981. aspectRatio = fbxCamera->GetPixelRatio() / aspectY;
  982. break;
  983. case FbxCamera::eFIXED_HEIGHT:
  984. aspectRatio = fbxCamera->GetPixelRatio() * aspectX;
  985. break;
  986. default:
  987. break;
  988. }
  989. return (float)aspectRatio;
  990. */
  991. }
  992. inline double vfov(double hfov, double aspect)
  993. {
  994. static const double MATH_PI_180 = 0.01745329251994329576923690768489;
  995. static const double MATH_180_PI = 57.295779513082320876798154814105;
  996. return (2.0 * atan((aspect) * tan( (hfov * MATH_PI_180) * 0.5)) * MATH_180_PI);
  997. }
  998. float getFieldOfView(FbxCamera* fbxCamera)
  999. {
  1000. double fieldOfViewX = 0.0;
  1001. double fieldOfViewY = 0.0;
  1002. double filmHeight = fbxCamera->GetApertureHeight();
  1003. double filmWidth = fbxCamera->GetApertureWidth() * fbxCamera->GetSqueezeRatio();
  1004. double apertureRatio = filmHeight / filmWidth;
  1005. if ( fbxCamera->GetApertureMode() == FbxCamera::eVertical)
  1006. {
  1007. fieldOfViewY = fbxCamera->FieldOfView.Get();
  1008. }
  1009. else if (fbxCamera->GetApertureMode() == FbxCamera::eHorizontal)
  1010. {
  1011. fieldOfViewX = fbxCamera->FieldOfView.Get();
  1012. fieldOfViewY = vfov( fieldOfViewX, apertureRatio);
  1013. }
  1014. else if (fbxCamera->GetApertureMode() == FbxCamera::eFocalLength)
  1015. {
  1016. fieldOfViewX = fbxCamera->ComputeFieldOfView(fbxCamera->FocalLength.Get());
  1017. fieldOfViewY = vfov( fieldOfViewX, apertureRatio);
  1018. }
  1019. else if (fbxCamera->GetApertureMode() == FbxCamera::eHorizAndVert)
  1020. {
  1021. fieldOfViewY = fbxCamera->FieldOfViewY.Get();
  1022. }
  1023. else
  1024. {
  1025. fieldOfViewY = 45.0;
  1026. }
  1027. return (float)fieldOfViewY;
  1028. }
  1029. void loadTextureCoords(FbxMesh* fbxMesh, const FbxGeometryElementUV* uvs, int uvSetIndex, int polyIndex, int posInPoly, int meshVertexIndex, Vertex* vertex)
  1030. {
  1031. assert(fbxMesh && polyIndex >=0 && posInPoly >= 0);
  1032. const bool useIndex = uvs->GetReferenceMode() != FbxGeometryElement::eDirect;
  1033. const int indexCount = useIndex ? uvs->GetIndexArray().GetCount() : 0;
  1034. int uvIndex = -1;
  1035. switch (uvs->GetMappingMode())
  1036. {
  1037. case FbxGeometryElement::eByControlPoint:
  1038. {
  1039. // Get the index of the current vertex in control points array
  1040. int polyVertIndex = fbxMesh->GetPolygonVertex(polyIndex, posInPoly);
  1041. // The UV index depends on the reference mode
  1042. uvIndex = useIndex ? uvs->GetIndexArray().GetAt(polyVertIndex) : polyVertIndex;
  1043. }
  1044. break;
  1045. case FbxGeometryElement::eByPolygonVertex:
  1046. if (meshVertexIndex < indexCount)
  1047. {
  1048. uvIndex = useIndex ? uvs->GetIndexArray().GetAt(meshVertexIndex) : meshVertexIndex;
  1049. }
  1050. break;
  1051. default:
  1052. // Only support eByPolygonVertex and eByControlPoint mappings
  1053. break;
  1054. }
  1055. vertex->hasTexCoord[uvSetIndex] = true;
  1056. // Store UV information in vertex
  1057. if (uvIndex != -1)
  1058. {
  1059. FbxVector2 uvValue = uvs->GetDirectArray().GetAt(uvIndex);
  1060. vertex->texCoord[uvSetIndex].x = (float)uvValue[0];
  1061. vertex->texCoord[uvSetIndex].y = (float)uvValue[1];
  1062. }
  1063. }
  1064. void loadNormal(FbxMesh* fbxMesh, int vertexIndex, int controlPointIndex, Vertex* vertex)
  1065. {
  1066. if (fbxMesh->GetElementNormalCount() > 0)
  1067. {
  1068. // Get only the first
  1069. FbxGeometryElementNormal* normal = fbxMesh->GetElementNormal(0);
  1070. FbxGeometryElement::EMappingMode mappingMode = normal->GetMappingMode();
  1071. if (mappingMode == FbxGeometryElement::eByControlPoint)
  1072. {
  1073. switch (normal->GetReferenceMode())
  1074. {
  1075. case FbxGeometryElement::eDirect:
  1076. {
  1077. FbxVector4 vec4 = normal->GetDirectArray().GetAt(controlPointIndex);
  1078. vertex->hasNormal = true;
  1079. vertex->normal.x = (float)vec4[0];
  1080. vertex->normal.y = (float)vec4[1];
  1081. vertex->normal.z = (float)vec4[2];
  1082. }
  1083. break;
  1084. case FbxGeometryElement::eIndexToDirect:
  1085. {
  1086. int id = normal->GetIndexArray().GetAt(controlPointIndex);
  1087. FbxVector4 vec4 = normal->GetDirectArray().GetAt(id);
  1088. vertex->hasNormal = true;
  1089. vertex->normal.x = (float)vec4[0];
  1090. vertex->normal.y = (float)vec4[1];
  1091. vertex->normal.z = (float)vec4[2];
  1092. }
  1093. break;
  1094. default:
  1095. break;
  1096. }
  1097. }
  1098. else if (mappingMode == FbxGeometryElement::eByPolygonVertex)
  1099. {
  1100. switch (normal->GetReferenceMode())
  1101. {
  1102. case FbxGeometryElement::eDirect:
  1103. {
  1104. FbxVector4 vec4 = normal->GetDirectArray().GetAt(vertexIndex);
  1105. vertex->hasNormal = true;
  1106. vertex->normal.x = (float)vec4[0];
  1107. vertex->normal.y = (float)vec4[1];
  1108. vertex->normal.z = (float)vec4[2];
  1109. }
  1110. break;
  1111. case FbxGeometryElement::eIndexToDirect:
  1112. {
  1113. int id = normal->GetIndexArray().GetAt(vertexIndex);
  1114. FbxVector4 vec4 = normal->GetDirectArray().GetAt(id);
  1115. vertex->hasNormal = true;
  1116. vertex->normal.x = (float)vec4[0];
  1117. vertex->normal.y = (float)vec4[1];
  1118. vertex->normal.z = (float)vec4[2];
  1119. }
  1120. break;
  1121. default:
  1122. break;
  1123. }
  1124. }
  1125. }
  1126. }
  1127. void loadTangent(FbxMesh* fbxMesh, int vertexIndex, Vertex* vertex)
  1128. {
  1129. if (fbxMesh->GetElementTangentCount() > 0)
  1130. {
  1131. // Get only the first tangent
  1132. FbxGeometryElementTangent* tangent = fbxMesh->GetElementTangent(0);
  1133. if (tangent->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
  1134. {
  1135. switch (tangent->GetReferenceMode())
  1136. {
  1137. case FbxGeometryElement::eDirect:
  1138. {
  1139. FbxVector4 vec4 = tangent->GetDirectArray().GetAt(vertexIndex);
  1140. vertex->hasTangent = true;
  1141. vertex->tangent.x = (float)vec4[0];
  1142. vertex->tangent.y = (float)vec4[1];
  1143. vertex->tangent.z = (float)vec4[2];
  1144. }
  1145. break;
  1146. case FbxGeometryElement::eIndexToDirect:
  1147. {
  1148. int id = tangent->GetIndexArray().GetAt(vertexIndex);
  1149. FbxVector4 vec4 = tangent->GetDirectArray().GetAt(id);
  1150. vertex->hasTangent = true;
  1151. vertex->tangent.x = (float)vec4[0];
  1152. vertex->tangent.y = (float)vec4[1];
  1153. vertex->tangent.z = (float)vec4[2];
  1154. }
  1155. break;
  1156. default:
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. }
  1162. void loadBinormal(FbxMesh* fbxMesh, int vertexIndex, Vertex* vertex)
  1163. {
  1164. if (fbxMesh->GetElementBinormalCount() > 0)
  1165. {
  1166. // Get only the first binormal.
  1167. FbxGeometryElementBinormal* binormal = fbxMesh->GetElementBinormal(0);
  1168. if (binormal->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
  1169. {
  1170. switch (binormal->GetReferenceMode())
  1171. {
  1172. case FbxGeometryElement::eDirect:
  1173. {
  1174. FbxVector4 vec4 = binormal->GetDirectArray().GetAt(vertexIndex);
  1175. vertex->hasBinormal = true;
  1176. vertex->binormal.x = (float)vec4[0];
  1177. vertex->binormal.y = (float)vec4[1];
  1178. vertex->binormal.z = (float)vec4[2];
  1179. }
  1180. break;
  1181. case FbxGeometryElement::eIndexToDirect:
  1182. {
  1183. int id = binormal->GetIndexArray().GetAt(vertexIndex);
  1184. FbxVector4 vec4 = binormal->GetDirectArray().GetAt(id);
  1185. vertex->hasBinormal = true;
  1186. vertex->binormal.x = (float)vec4[0];
  1187. vertex->binormal.y = (float)vec4[1];
  1188. vertex->binormal.z = (float)vec4[2];
  1189. }
  1190. break;
  1191. default:
  1192. break;
  1193. }
  1194. }
  1195. }
  1196. }
  1197. void loadVertexColor(FbxMesh* fbxMesh, int vertexIndex, Vertex* vertex)
  1198. {
  1199. if (fbxMesh->GetElementVertexColorCount() > 0)
  1200. {
  1201. // Get only the first vertex color.
  1202. FbxGeometryElementVertexColor* vertexColor = fbxMesh->GetElementVertexColor(0);
  1203. if (vertexColor->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
  1204. {
  1205. switch (vertexColor->GetReferenceMode())
  1206. {
  1207. case FbxGeometryElement::eDirect:
  1208. {
  1209. FbxColor color = vertexColor->GetDirectArray().GetAt(vertexIndex);
  1210. vertex->hasDiffuse = true;
  1211. vertex->diffuse.x = (float)color.mRed;
  1212. vertex->diffuse.y = (float)color.mGreen;
  1213. vertex->diffuse.z = (float)color.mBlue;
  1214. vertex->diffuse.w = (float)color.mAlpha;
  1215. }
  1216. break;
  1217. case FbxGeometryElement::eIndexToDirect:
  1218. {
  1219. int id = vertexColor->GetIndexArray().GetAt(vertexIndex);
  1220. FbxColor color = vertexColor->GetDirectArray().GetAt(id);
  1221. vertex->hasDiffuse = true;
  1222. vertex->diffuse.x = (float)color.mRed;
  1223. vertex->diffuse.y = (float)color.mGreen;
  1224. vertex->diffuse.z = (float)color.mBlue;
  1225. vertex->diffuse.w = (float)color.mAlpha;
  1226. }
  1227. break;
  1228. default:
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. }
  1234. void loadBlendData(const std::vector<Vector2>& vertexWeights, Vertex* vertex)
  1235. {
  1236. size_t size = vertexWeights.size();
  1237. if (size >= 1)
  1238. {
  1239. vertex->hasWeights= true;
  1240. vertex->blendIndices.x = vertexWeights[0].x;
  1241. vertex->blendWeights.x = vertexWeights[0].y;
  1242. }
  1243. if (size >= 2)
  1244. {
  1245. vertex->blendIndices.y = vertexWeights[1].x;
  1246. vertex->blendWeights.y = vertexWeights[1].y;
  1247. }
  1248. if (size >= 3)
  1249. {
  1250. vertex->blendIndices.z = vertexWeights[2].x;
  1251. vertex->blendWeights.z = vertexWeights[2].y;
  1252. }
  1253. if (size >= 4)
  1254. {
  1255. vertex->blendIndices.w = vertexWeights[3].x;
  1256. vertex->blendWeights.w = vertexWeights[3].y;
  1257. }
  1258. //vertex->normalizeBlendWeight();
  1259. }
  1260. bool loadBlendWeights(FbxMesh* fbxMesh, std::vector<std::vector<Vector2> >& weights)
  1261. {
  1262. assert(fbxMesh);
  1263. const int vertexCount = fbxMesh->GetControlPointsCount();
  1264. FbxSkin* fbxSkin = NULL;
  1265. const int deformerCount = fbxMesh->GetDeformerCount();
  1266. for (int i = 0; i < deformerCount; ++i)
  1267. {
  1268. FbxDeformer* deformer = fbxMesh->GetDeformer(i);
  1269. if (deformer->GetDeformerType() == FbxDeformer::eSkin)
  1270. {
  1271. fbxSkin = static_cast<FbxSkin*>(deformer);
  1272. weights.resize(vertexCount);
  1273. const int clusterCount = fbxSkin->GetClusterCount();
  1274. for (int j = 0; j < clusterCount; ++j)
  1275. {
  1276. FbxCluster* cluster = fbxSkin->GetCluster(j);
  1277. assert(cluster);
  1278. FbxNode* linkedNode = cluster->GetLink();
  1279. assert(linkedNode);
  1280. const int vertexIndexCount = cluster->GetControlPointIndicesCount();
  1281. for (int k = 0; k < vertexIndexCount; ++k)
  1282. {
  1283. int index = cluster->GetControlPointIndices()[k];
  1284. if (index >= vertexCount)
  1285. {
  1286. continue;
  1287. }
  1288. double weight = cluster->GetControlPointWeights()[k];
  1289. if (weight == 0.0)
  1290. {
  1291. continue;
  1292. }
  1293. weights[index].push_back(Vector2((float)j, (float)weight));
  1294. }
  1295. }
  1296. // Only the first skin deformer will be loaded.
  1297. // There probably won't be more than one.
  1298. break;
  1299. }
  1300. }
  1301. return fbxSkin != NULL;
  1302. }
  1303. void findMinMaxTime(FbxAnimCurve* animCurve, float* startTime, float* stopTime, float* frameRate)
  1304. {
  1305. FbxTime start, stop;
  1306. FbxTimeSpan timeSpan;
  1307. animCurve->GetTimeInterval(timeSpan);
  1308. start = timeSpan.GetStart();
  1309. stop = timeSpan.GetStop();
  1310. *startTime = std::min(*startTime, (float)start.GetMilliSeconds());
  1311. *stopTime = std::max(*stopTime, (float)stop.GetMilliSeconds());
  1312. *frameRate = std::max(*frameRate, (float)stop.GetFrameRate(FbxTime::eDefaultMode));
  1313. }
  1314. void appendKeyFrame(FbxNode* fbxNode, AnimationChannel* channel, float time, const Vector3& scale, const Quaternion& rotation, const Vector3& translation)
  1315. {
  1316. // Write key time
  1317. channel->getKeyTimes().push_back(time);
  1318. // Write key values
  1319. std::vector<float>& keyValues = channel->getKeyValues();
  1320. switch (channel->getTargetAttribute())
  1321. {
  1322. case Transform::ANIMATE_SCALE:
  1323. {
  1324. keyValues.push_back(scale.x);
  1325. keyValues.push_back(scale.y);
  1326. keyValues.push_back(scale.z);
  1327. }
  1328. break;
  1329. case Transform::ANIMATE_SCALE_X:
  1330. {
  1331. keyValues.push_back(scale.x);
  1332. }
  1333. break;
  1334. case Transform::ANIMATE_SCALE_Y:
  1335. {
  1336. keyValues.push_back(scale.y);
  1337. }
  1338. break;
  1339. case Transform::ANIMATE_SCALE_Z:
  1340. {
  1341. keyValues.push_back(scale.z);
  1342. }
  1343. break;
  1344. case Transform::ANIMATE_ROTATE:
  1345. {
  1346. keyValues.push_back(rotation.x);
  1347. keyValues.push_back(rotation.y);
  1348. keyValues.push_back(rotation.z);
  1349. keyValues.push_back(rotation.w);
  1350. }
  1351. break;
  1352. case Transform::ANIMATE_TRANSLATE:
  1353. {
  1354. keyValues.push_back(translation.x);
  1355. keyValues.push_back(translation.y);
  1356. keyValues.push_back(translation.z);
  1357. }
  1358. break;
  1359. case Transform::ANIMATE_TRANSLATE_X:
  1360. {
  1361. keyValues.push_back(translation.x);
  1362. }
  1363. break;
  1364. case Transform::ANIMATE_TRANSLATE_Y:
  1365. {
  1366. keyValues.push_back(translation.y);
  1367. }
  1368. break;
  1369. case Transform::ANIMATE_TRANSLATE_Z:
  1370. {
  1371. keyValues.push_back(translation.z);
  1372. }
  1373. break;
  1374. case Transform::ANIMATE_ROTATE_TRANSLATE:
  1375. {
  1376. keyValues.push_back(rotation.x);
  1377. keyValues.push_back(rotation.y);
  1378. keyValues.push_back(rotation.z);
  1379. keyValues.push_back(rotation.w);
  1380. keyValues.push_back(translation.x);
  1381. keyValues.push_back(translation.y);
  1382. keyValues.push_back(translation.z);
  1383. }
  1384. break;
  1385. case Transform::ANIMATE_SCALE_ROTATE_TRANSLATE:
  1386. {
  1387. keyValues.push_back(scale.x);
  1388. keyValues.push_back(scale.y);
  1389. keyValues.push_back(scale.z);
  1390. keyValues.push_back(rotation.x);
  1391. keyValues.push_back(rotation.y);
  1392. keyValues.push_back(rotation.z);
  1393. keyValues.push_back(rotation.w);
  1394. keyValues.push_back(translation.x);
  1395. keyValues.push_back(translation.y);
  1396. keyValues.push_back(translation.z);
  1397. }
  1398. break;
  1399. case Transform::ANIMATE_SCALE_TRANSLATE:
  1400. {
  1401. keyValues.push_back(scale.x);
  1402. keyValues.push_back(scale.y);
  1403. keyValues.push_back(scale.z);
  1404. keyValues.push_back(translation.x);
  1405. keyValues.push_back(translation.y);
  1406. keyValues.push_back(translation.z);
  1407. }
  1408. break;
  1409. case Transform::ANIMATE_SCALE_ROTATE:
  1410. {
  1411. keyValues.push_back(scale.x);
  1412. keyValues.push_back(scale.y);
  1413. keyValues.push_back(scale.z);
  1414. keyValues.push_back(rotation.x);
  1415. keyValues.push_back(rotation.y);
  1416. keyValues.push_back(rotation.z);
  1417. keyValues.push_back(rotation.w);
  1418. }
  1419. break;
  1420. default:
  1421. {
  1422. LOG(1, "Warning: Invalid animatoin target (%d) attribute for node: %s.\n", channel->getTargetAttribute(), fbxNode->GetName());
  1423. }
  1424. return;
  1425. }
  1426. }
  1427. void decompose(FbxNode* fbxNode, float time, Vector3* scale, Quaternion* rotation, Vector3* translation)
  1428. {
  1429. FbxAMatrix fbxMatrix;
  1430. Matrix matrix;
  1431. FbxTime kTime;
  1432. kTime.SetMilliSeconds((FbxLongLong)time);
  1433. fbxMatrix = fbxNode->EvaluateLocalTransform(kTime);
  1434. copyMatrix(fbxMatrix, matrix);
  1435. matrix.decompose(scale, rotation, translation);
  1436. }
  1437. AnimationChannel* createAnimationChannel(FbxNode* fbxNode, unsigned int targetAttrib, const std::vector<float>& keyTimes, const std::vector<float>& keyValues)
  1438. {
  1439. AnimationChannel* channel = new AnimationChannel();
  1440. channel->setTargetId(fbxNode->GetName());
  1441. channel->setKeyTimes(keyTimes);
  1442. channel->setKeyValues(keyValues);
  1443. channel->setInterpolation(AnimationChannel::LINEAR);
  1444. channel->setTargetAttribute(targetAttrib);
  1445. return channel;
  1446. }
  1447. void addScaleChannel(Animation* animation, FbxNode* fbxNode, float startTime, float stopTime)
  1448. {
  1449. std::vector<float> keyTimes;
  1450. std::vector<float> keyValues;
  1451. Vector3 scale;
  1452. Quaternion rotation;
  1453. Vector3 translation;
  1454. decompose(fbxNode, startTime, &scale, &rotation, &translation);
  1455. keyTimes.push_back(startTime);
  1456. keyValues.push_back(scale.x);
  1457. keyValues.push_back(scale.y);
  1458. keyValues.push_back(scale.z);
  1459. decompose(fbxNode, stopTime, &scale, &rotation, &translation);
  1460. keyTimes.push_back(stopTime);
  1461. keyValues.push_back(scale.x);
  1462. keyValues.push_back(scale.y);
  1463. keyValues.push_back(scale.z);
  1464. AnimationChannel* channel = createAnimationChannel(fbxNode, Transform::ANIMATE_SCALE, keyTimes, keyValues);
  1465. animation->add(channel);
  1466. }
  1467. void addTranslateChannel(Animation* animation, FbxNode* fbxNode, float startTime, float stopTime)
  1468. {
  1469. std::vector<float> keyTimes;
  1470. std::vector<float> keyValues;
  1471. Vector3 scale;
  1472. Quaternion rotation;
  1473. Vector3 translation;
  1474. decompose(fbxNode, startTime, &scale, &rotation, &translation);
  1475. keyTimes.push_back(startTime);
  1476. keyValues.push_back(translation.x);
  1477. keyValues.push_back(translation.y);
  1478. keyValues.push_back(translation.z);
  1479. decompose(fbxNode, stopTime, &scale, &rotation, &translation);
  1480. keyTimes.push_back(stopTime);
  1481. keyValues.push_back(translation.x);
  1482. keyValues.push_back(translation.y);
  1483. keyValues.push_back(translation.z);
  1484. AnimationChannel* channel = createAnimationChannel(fbxNode, Transform::ANIMATE_TRANSLATE, keyTimes, keyValues);
  1485. animation->add(channel);
  1486. }
  1487. void copyMatrix(const FbxMatrix& fbxMatrix, float* matrix)
  1488. {
  1489. int i = 0;
  1490. for (int row = 0; row < 4; ++row)
  1491. {
  1492. for (int col = 0; col < 4; ++col)
  1493. {
  1494. matrix[i++] = (float)fbxMatrix.Get(row, col);
  1495. }
  1496. }
  1497. }
  1498. void copyMatrix(const FbxMatrix& fbxMatrix, Matrix& matrix)
  1499. {
  1500. int i = 0;
  1501. for (int row = 0; row < 4; ++row)
  1502. {
  1503. for (int col = 0; col < 4; ++col)
  1504. {
  1505. matrix.m[i++] = (float)fbxMatrix.Get(row, col);
  1506. }
  1507. }
  1508. }
  1509. bool isGroupAnimationPossible(FbxScene* fbxScene)
  1510. {
  1511. FbxNode* rootNode = fbxScene->GetRootNode();
  1512. if (rootNode)
  1513. {
  1514. if (isGroupAnimationPossible(rootNode))
  1515. return true;
  1516. }
  1517. return false;
  1518. }
  1519. bool isGroupAnimationPossible(FbxNode* fbxNode)
  1520. {
  1521. if (fbxNode)
  1522. {
  1523. FbxMesh* fbxMesh = fbxNode->GetMesh();
  1524. if (isGroupAnimationPossible(fbxMesh))
  1525. return true;
  1526. const int childCount = fbxNode->GetChildCount();
  1527. for (int i = 0; i < childCount; ++i)
  1528. {
  1529. if (isGroupAnimationPossible(fbxNode->GetChild(i)))
  1530. return true;
  1531. }
  1532. }
  1533. return false;
  1534. }
  1535. bool isGroupAnimationPossible(FbxMesh* fbxMesh)
  1536. {
  1537. if (fbxMesh)
  1538. {
  1539. const int deformerCount = fbxMesh->GetDeformerCount();
  1540. for (int i = 0; i < deformerCount; ++i)
  1541. {
  1542. FbxDeformer* deformer = fbxMesh->GetDeformer(i);
  1543. if (deformer->GetDeformerType() == FbxDeformer::eSkin)
  1544. {
  1545. FbxSkin* fbxSkin = static_cast<FbxSkin*>(deformer);
  1546. if (fbxSkin)
  1547. {
  1548. return true;
  1549. }
  1550. }
  1551. }
  1552. }
  1553. return false;
  1554. }
  1555. #endif