FBXSceneEncoder.cpp 51 KB

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