FBXSceneEncoder.cpp 56 KB

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