FBXSceneEncoder.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. #include <algorithm>
  2. #include <string>
  3. #include <sstream>
  4. #include "FBXSceneEncoder.h"
  5. #include "FBXUtil.h"
  6. #include "Sampler.h"
  7. using namespace gameplay;
  8. using std::string;
  9. using std::vector;
  10. using std::map;
  11. using std::ostringstream;
  12. // Fix bad material names
  13. static void fixMaterialName(string& name);
  14. FBXSceneEncoder::FBXSceneEncoder()
  15. : _groupAnimation(NULL), _autoGroupAnimations(false)
  16. {
  17. }
  18. FBXSceneEncoder::~FBXSceneEncoder()
  19. {
  20. }
  21. void FBXSceneEncoder::write(const string& filepath, const EncoderArguments& arguments)
  22. {
  23. FbxManager* sdkManager = FbxManager::Create();
  24. FbxIOSettings *ios = FbxIOSettings::Create(sdkManager, IOSROOT);
  25. sdkManager->SetIOSettings(ios);
  26. FbxImporter* importer = FbxImporter::Create(sdkManager,"");
  27. if (!importer->Initialize(filepath.c_str(), -1, sdkManager->GetIOSettings()))
  28. {
  29. LOG(1, "Call to FbxImporter::Initialize() failed.\n");
  30. LOG(1, "Error returned: %s\n\n", importer->GetStatus().GetErrorString());
  31. exit(-1);
  32. }
  33. FbxScene* fbxScene = FbxScene::Create(sdkManager,"__FBX_SCENE__");
  34. print("Loading FBX file.");
  35. importer->Import(fbxScene);
  36. importer->Destroy();
  37. // Determine if animations should be grouped.
  38. if (arguments.getGroupAnimationAnimationId().empty() && isGroupAnimationPossible(fbxScene))
  39. {
  40. if ( arguments.getAnimationGrouping()==EncoderArguments::ANIMATIONGROUP_AUTO ||
  41. (arguments.getAnimationGrouping()==EncoderArguments::ANIMATIONGROUP_PROMPT && promptUserGroupAnimations()))
  42. {
  43. _autoGroupAnimations = true;
  44. }
  45. }
  46. if (arguments.tangentBinormalIdCount() > 0)
  47. {
  48. generateTangentsAndBinormals(fbxScene->GetRootNode(), arguments);
  49. }
  50. print("Loading Scene.");
  51. loadScene(fbxScene);
  52. print("Load materials");
  53. loadMaterials(fbxScene);
  54. print("Loading animations.");
  55. loadAnimations(fbxScene, arguments);
  56. sdkManager->Destroy();
  57. print("Optimizing GamePlay Binary.");
  58. _gamePlayFile.adjust();
  59. if (_autoGroupAnimations)
  60. {
  61. _gamePlayFile.groupMeshSkinAnimations();
  62. }
  63. string outputFilePath = arguments.getOutputFilePath();
  64. if (arguments.textOutputEnabled())
  65. {
  66. int pos = outputFilePath.find_last_of('.');
  67. if (pos > 2)
  68. {
  69. string path = outputFilePath.substr(0, pos);
  70. path.append(".xml");
  71. LOG(1, "Saving debug file: %s\n", path.c_str());
  72. if (!_gamePlayFile.saveText(path))
  73. {
  74. LOG(1, "Error writing text file: %s\n", path.c_str());
  75. }
  76. }
  77. }
  78. else
  79. {
  80. LOG(1, "Saving binary file: %s\n", outputFilePath.c_str());
  81. if (!_gamePlayFile.saveBinary(outputFilePath))
  82. {
  83. LOG(1, "Error writing binary file: %s\n", outputFilePath.c_str());
  84. }
  85. }
  86. // Write the material file
  87. if (arguments.outputMaterialEnabled())
  88. {
  89. int pos = outputFilePath.find_last_of('.');
  90. if (pos > 2)
  91. {
  92. string path = outputFilePath.substr(0, pos);
  93. path.append(".material");
  94. writeMaterial(path);
  95. }
  96. }
  97. }
  98. bool FBXSceneEncoder::writeMaterial(const string& filepath)
  99. {
  100. FILE* file = fopen(filepath.c_str(), "w");
  101. if (!file)
  102. {
  103. return false;
  104. }
  105. // Finds the base materials that are used.
  106. std::set<Material*> baseMaterialsToWrite;
  107. for (map<string, Material*>::iterator it = _materials.begin(); it != _materials.end(); ++it)
  108. {
  109. baseMaterialsToWrite.insert(it->second->getParent());
  110. }
  111. // Write the base materials that are used.
  112. for (std::set<Material*>::iterator it = baseMaterialsToWrite.begin(); it != baseMaterialsToWrite.end(); ++it)
  113. {
  114. Material* material = *it;
  115. material->writeMaterial(file);
  116. fprintf(file, "\n");
  117. }
  118. // Write all of the non-base materials.
  119. for (map<string, Material*>::iterator it = _materials.begin(); it != _materials.end(); ++it)
  120. {
  121. (*it).second->writeMaterial(file);
  122. fprintf(file, "\n");
  123. }
  124. fclose(file);
  125. return true;
  126. }
  127. void FBXSceneEncoder::loadScene(FbxScene* fbxScene)
  128. {
  129. Scene* scene = new Scene();
  130. scene->setId(fbxScene->GetName());
  131. if (scene->getId().length() == 0)
  132. {
  133. scene->setId("__SCENE__");
  134. }
  135. // Load all of the nodes and their contents.
  136. FbxNode* rootNode = fbxScene->GetRootNode();
  137. if (rootNode)
  138. {
  139. print("Triangulate.");
  140. triangulateRecursive(rootNode);
  141. print("Load nodes.");
  142. // Don't include the FBX root node in the GPB.
  143. const int childCount = rootNode->GetChildCount();
  144. for (int i = 0; i < childCount; ++i)
  145. {
  146. Node* node = loadNode(rootNode->GetChild(i));
  147. if (node)
  148. {
  149. scene->add(node);
  150. }
  151. }
  152. }
  153. // Load the MeshSkin information from the scene's poses.
  154. loadBindShapes(fbxScene);
  155. // Find the ambient light of the scene
  156. FbxColor ambientColor = fbxScene->GetGlobalSettings().GetAmbientColor();
  157. scene->setAmbientColor((float)ambientColor.mRed, (float)ambientColor.mGreen, (float)ambientColor.mBlue);
  158. // Assign the first camera node (if there is one) in the scene as the active camera
  159. // This ensures that if there's a camera in the scene that it is assigned as the
  160. // active camera.
  161. // TODO: add logic to find the "active" camera node in the fbxScene
  162. scene->setActiveCameraNode(scene->getFirstCameraNode());
  163. _gamePlayFile.addScene(scene);
  164. }
  165. void FBXSceneEncoder::loadAnimationChannels(FbxAnimLayer* animLayer, FbxNode* fbxNode, Animation* animation)
  166. {
  167. const char* name = fbxNode->GetName();
  168. //Node* node = _gamePlayFile.getNode(name);
  169. // Determine which properties are animated on this node
  170. // Find the transform at each key frame
  171. // TODO: Ignore properties that are not animated (scale, rotation, translation)
  172. // This should result in only one animation channel per animated node.
  173. float startTime = FLT_MAX, stopTime = -1.0f, frameRate = -FLT_MAX;
  174. bool tx = false, ty = false, tz = false, rx = false, ry = false, rz = false, sx = false, sy = false, sz = false;
  175. FbxAnimCurve* animCurve = NULL;
  176. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  177. if (animCurve)
  178. {
  179. tx = true;
  180. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  181. }
  182. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  183. if (animCurve)
  184. {
  185. ty = true;
  186. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  187. }
  188. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  189. if (animCurve)
  190. {
  191. tz = true;
  192. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  193. }
  194. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  195. if (animCurve)
  196. {
  197. rx = true;
  198. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  199. }
  200. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  201. if (animCurve)
  202. {
  203. ry = true;
  204. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  205. }
  206. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  207. if (animCurve)
  208. {
  209. rz = true;
  210. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  211. }
  212. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  213. if (animCurve)
  214. {
  215. sx = true;
  216. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  217. }
  218. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  219. if (animCurve)
  220. {
  221. sy = true;
  222. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  223. }
  224. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  225. if (animCurve)
  226. {
  227. sz = true;
  228. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  229. }
  230. if (!(sx || sy || sz || rx || ry || rz || tx || ty || tz))
  231. return; // no animation channels
  232. assert(startTime != FLT_MAX);
  233. assert(stopTime >= 0.0f);
  234. // Determine which animation channels to create
  235. vector<unsigned int> channelAttribs;
  236. if (sx && sy && sz)
  237. {
  238. if (rx || ry || rz)
  239. {
  240. if (tx && ty && tz)
  241. {
  242. channelAttribs.push_back(Transform::ANIMATE_SCALE_ROTATE_TRANSLATE);
  243. }
  244. else
  245. {
  246. channelAttribs.push_back(Transform::ANIMATE_SCALE_ROTATE);
  247. if (tx)
  248. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  249. if (ty)
  250. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  251. if (tz)
  252. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  253. }
  254. }
  255. else
  256. {
  257. if (tx && ty && tz)
  258. {
  259. channelAttribs.push_back(Transform::ANIMATE_SCALE_TRANSLATE);
  260. }
  261. else
  262. {
  263. channelAttribs.push_back(Transform::ANIMATE_SCALE);
  264. if (tx)
  265. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  266. if (ty)
  267. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  268. if (tz)
  269. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  270. }
  271. }
  272. }
  273. else
  274. {
  275. if (rx || ry || rz)
  276. {
  277. if (tx && ty && tz)
  278. {
  279. channelAttribs.push_back(Transform::ANIMATE_ROTATE_TRANSLATE);
  280. }
  281. else
  282. {
  283. channelAttribs.push_back(Transform::ANIMATE_ROTATE);
  284. if (tx)
  285. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  286. if (ty)
  287. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  288. if (tz)
  289. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  290. }
  291. }
  292. else
  293. {
  294. if (tx && ty && tz)
  295. {
  296. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE);
  297. }
  298. else
  299. {
  300. if (tx)
  301. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  302. if (ty)
  303. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  304. if (tz)
  305. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  306. }
  307. }
  308. if (sx)
  309. channelAttribs.push_back(Transform::ANIMATE_SCALE_X);
  310. if (sy)
  311. channelAttribs.push_back(Transform::ANIMATE_SCALE_Y);
  312. if (sz)
  313. channelAttribs.push_back(Transform::ANIMATE_SCALE_Z);
  314. }
  315. unsigned int channelCount = channelAttribs.size();
  316. assert(channelCount > 0);
  317. // Allocate channel list
  318. const int channelStart = animation->getAnimationChannelCount();
  319. for (unsigned int i = 0; i < channelCount; ++i)
  320. {
  321. AnimationChannel* channel = new AnimationChannel();
  322. channel->setTargetId(name);
  323. channel->setInterpolation(AnimationChannel::LINEAR);
  324. channel->setTargetAttribute(channelAttribs[i]);
  325. animation->add(channel);
  326. }
  327. // Evaulate animation curve in increments of frameRate and populate channel data.
  328. FbxAMatrix fbxMatrix;
  329. Matrix matrix;
  330. double increment = 1000.0 / (double)frameRate;
  331. int frameCount = (int)ceil((double)(stopTime - startTime) / increment) + 1; // +1 because stop time is inclusive
  332. // If the animation for this node only has only 1 key frame and it is equal to the node's transform then ignore it.
  333. // This is a work around for a bug in the Blender FBX exporter.
  334. if (frameCount == 1 && fbxMatrix == fbxNode->EvaluateLocalTransform(0))
  335. {
  336. return;
  337. }
  338. for (int frame = 0; frame < frameCount; ++frame)
  339. {
  340. double time = startTime + (frame * (double)increment);
  341. // Note: We used to clamp time to stop time, but FBX sdk does not always produce
  342. // and accurate stopTime (sometimes it is rounded down for some reason), so I'm
  343. // disabling this clamping for now as it seems more accurate under normal circumstances.
  344. //time = std::min(time, (double)stopTime);
  345. // Evalulate the animation at this time
  346. FbxTime kTime;
  347. kTime.SetMilliSeconds((FbxLongLong)time);
  348. fbxMatrix = fbxNode->EvaluateLocalTransform(kTime);
  349. copyMatrix(fbxMatrix, matrix);
  350. // Decompose the evalulated transformation matrix into separate
  351. // scale, rotation and translation.
  352. Vector3 scale;
  353. Quaternion rotation;
  354. Vector3 translation;
  355. matrix.decompose(&scale, &rotation, &translation);
  356. rotation.normalize();
  357. // Append keyframe data to all channels
  358. for (unsigned int i = channelStart, channelEnd = channelStart + channelCount; i < channelEnd; ++i)
  359. {
  360. appendKeyFrame(fbxNode, animation->getAnimationChannel(i), (float)time, scale, rotation, translation);
  361. }
  362. }
  363. if (_groupAnimation != animation)
  364. {
  365. _gamePlayFile.addAnimation(animation);
  366. }
  367. }
  368. void FBXSceneEncoder::loadAnimationLayer(FbxAnimLayer* fbxAnimLayer, FbxNode* fbxNode, const EncoderArguments& arguments)
  369. {
  370. bool animationGroupId = false;
  371. const char* name = fbxNode->GetName();
  372. // Check if this node's animations are supposed to be grouped
  373. if (name && arguments.containsGroupNodeId(name))
  374. {
  375. animationGroupId = true;
  376. _groupAnimation = new Animation();
  377. _groupAnimation->setId(arguments.getAnimationId(name));
  378. }
  379. Animation* animation = _groupAnimation;
  380. if (!animation)
  381. {
  382. animation = new Animation();
  383. animation->setId(name);
  384. }
  385. loadAnimationChannels(fbxAnimLayer, fbxNode, animation);
  386. const int childCount = fbxNode->GetChildCount();
  387. for (int modelCount = 0; modelCount < childCount; ++modelCount)
  388. {
  389. loadAnimationLayer(fbxAnimLayer, fbxNode->GetChild(modelCount), arguments);
  390. }
  391. if (animationGroupId)
  392. {
  393. _gamePlayFile.addAnimation(_groupAnimation);
  394. _groupAnimation = NULL;
  395. }
  396. }
  397. void FBXSceneEncoder::loadAnimations(FbxScene* fbxScene, const EncoderArguments& arguments)
  398. {
  399. FbxAnimEvaluator* evaluator = fbxScene->GetEvaluator();
  400. if (!evaluator)
  401. return;
  402. FbxAnimStack* animStack = evaluator->GetContext();
  403. if (!animStack)
  404. return;
  405. for (int i = 0; i < fbxScene->GetSrcObjectCount<FbxAnimStack>(); ++i)
  406. {
  407. FbxAnimStack* animStack = FbxCast<FbxAnimStack>(fbxScene->GetSrcObject<FbxAnimStack>(i));
  408. int nbAnimLayers = animStack->GetMemberCount<FbxAnimLayer>();
  409. for (int l = 0; l < nbAnimLayers; ++l)
  410. {
  411. FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(l);
  412. loadAnimationLayer(animLayer, fbxScene->GetRootNode(), arguments);
  413. }
  414. }
  415. }
  416. Node* FBXSceneEncoder::loadNode(FbxNode* fbxNode)
  417. {
  418. Node* node = NULL;
  419. // Check if this node has already been loaded
  420. const char* id = fbxNode->GetName();
  421. if (id && strlen(id) > 0)
  422. {
  423. node = _gamePlayFile.getNode(fbxNode->GetName());
  424. if (node)
  425. {
  426. return node;
  427. }
  428. }
  429. node = new Node();
  430. if (id)
  431. {
  432. node->setId(id);
  433. }
  434. _gamePlayFile.addNode(node);
  435. transformNode(fbxNode, node);
  436. loadCamera(fbxNode, node);
  437. loadLight(fbxNode, node);
  438. loadModel(fbxNode, node);
  439. if (fbxNode->GetSkeleton())
  440. {
  441. // Indicate that this is a joint node for the purpose of debugging.
  442. // The XML debug output will print that this node is a joint.
  443. node->setIsJoint(true);
  444. }
  445. // Load child nodes
  446. const int childCount = fbxNode->GetChildCount();
  447. for (int i = 0; i < childCount; ++i)
  448. {
  449. Node* child = loadNode(fbxNode->GetChild(i));
  450. if (child)
  451. {
  452. node->addChild(child);
  453. }
  454. }
  455. _nodeMap[fbxNode] = node;
  456. return node;
  457. }
  458. Mesh* FBXSceneEncoder::getMesh(FbxUInt64 meshId)
  459. {
  460. // Check if this mesh was already loaded.
  461. map<FbxUInt64, Mesh*>::iterator it = _meshes.find(meshId);
  462. if (it != _meshes.end())
  463. {
  464. return it->second;
  465. }
  466. return NULL;
  467. }
  468. void FBXSceneEncoder::saveMesh(FbxUInt64 meshId, Mesh* mesh)
  469. {
  470. assert(mesh);
  471. if (!getMesh(meshId))
  472. {
  473. _meshes[meshId] = mesh;
  474. }
  475. }
  476. void FBXSceneEncoder::print(const char* str)
  477. {
  478. LOG(1, "%s\n", str);
  479. }
  480. void FBXSceneEncoder::transformNode(FbxNode* fbxNode, Node* node)
  481. {
  482. FbxAMatrix matrix;
  483. float m[16];
  484. if (fbxNode->GetCamera() || fbxNode->GetLight())
  485. {
  486. FbxAMatrix rotateAdjust;
  487. if(fbxNode->GetLight())
  488. {
  489. /*
  490. * according to the fbx-documentation the light's forward vector
  491. * points along a node's negative Y axis.
  492. * so we have to rotate it by 90° around the X-axis to correct it.
  493. */
  494. if(fbxNode->RotationActive.Get())
  495. {
  496. const FbxVector4& postRotation = fbxNode->PostRotation.Get();
  497. fbxNode->SetPostRotation(FbxNode::eSourcePivot, FbxVector4(postRotation.mData[0] + 90.0,
  498. postRotation.mData[1],
  499. postRotation.mData[2])
  500. );
  501. }
  502. else
  503. {
  504. // if the rotation is deactivated we have to rotate it anyway to get the correct transformation in the end
  505. rotateAdjust.SetR(FbxVector4(-90.0, 0.0, 0.0));
  506. }
  507. matrix = fbxNode->EvaluateLocalTransform() * rotateAdjust;
  508. }
  509. else if(fbxNode->GetCamera())
  510. {
  511. // TODO: use the EvaluateLocalTransform() function for the transformations for the camera
  512. /*
  513. * the current implementation ignores pre- and postrotation among others (usually happens with fbx-export from blender)
  514. *
  515. * Some info for a future implementation:
  516. * according to the fbx-documentation the camera's forward vector
  517. * points along a node's positive X axis.
  518. * so we have to correct it if we use the EvaluateLocalTransform-function
  519. * just rotating it by 90° around the Y axis (similar to above) doesn't work
  520. */
  521. matrix.SetTRS(fbxNode->LclTranslation.Get(), fbxNode->LclRotation.Get(), fbxNode->LclScaling.Get());
  522. }
  523. copyMatrix(matrix, m);
  524. node->setTransformMatrix(m);
  525. }
  526. else
  527. {
  528. matrix = fbxNode->EvaluateLocalTransform();
  529. copyMatrix(matrix, m);
  530. node->setTransformMatrix(m);
  531. }
  532. }
  533. Material* FBXSceneEncoder::getBaseMaterial(const char* id)
  534. {
  535. map<string, Material*>::iterator it = _baseMaterials.find(string(id));
  536. if (it != _baseMaterials.end())
  537. {
  538. return it->second;
  539. }
  540. return NULL;
  541. }
  542. static string getBaseMaterialName(Material* material)
  543. {
  544. ostringstream baseName;
  545. if (material->isTextured())
  546. {
  547. baseName << "Textured";
  548. }
  549. else
  550. {
  551. baseName << "Colored";
  552. }
  553. if (material->isLit())
  554. {
  555. if (material->isSpecular())
  556. {
  557. baseName << "Specular";
  558. }
  559. }
  560. else
  561. {
  562. baseName << "Unlit";
  563. }
  564. return baseName.str();
  565. }
  566. Material* FBXSceneEncoder::findBaseMaterial(Material* material)
  567. {
  568. string baseMaterialName = getBaseMaterialName(material);
  569. Material* baseMaterial = getBaseMaterial(baseMaterialName.c_str());
  570. if (baseMaterial)
  571. {
  572. return baseMaterial;
  573. }
  574. baseMaterial = createBaseMaterial(baseMaterialName, material);
  575. _baseMaterials[baseMaterial->getId()] = baseMaterial;
  576. return baseMaterial;
  577. }
  578. Node* FBXSceneEncoder::findNode(FbxNode* fbxNode)
  579. {
  580. if (fbxNode)
  581. {
  582. map<FbxNode*, Node*>::const_iterator it = _nodeMap.find(fbxNode);
  583. if (it != _nodeMap.end())
  584. {
  585. return it->second;
  586. }
  587. }
  588. return NULL;
  589. }
  590. Material* FBXSceneEncoder::createBaseMaterial(const string& baseMaterialName, Material* childMaterial)
  591. {
  592. Material* baseMaterial = new Material(baseMaterialName);
  593. baseMaterial->setUniform("u_worldViewProjectionMatrix", "WORLD_VIEW_PROJECTION_MATRIX");
  594. baseMaterial->setRenderState("cullFace", "true");
  595. baseMaterial->setRenderState("depthTest", "true");
  596. if (childMaterial->isLit())
  597. {
  598. baseMaterial->setLit(true);
  599. baseMaterial->setUniform("u_inverseTransposeWorldViewMatrix", "INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX");s
  600. if (childMaterial->isSpecular())
  601. {
  602. baseMaterial->addDefine(SPECULAR);
  603. baseMaterial->setUniform("u_cameraPosition", "CAMERA_WORLD_POSITION");
  604. }
  605. }
  606. if (childMaterial->isTextured())
  607. {
  608. if (childMaterial->isLit())
  609. {
  610. if (childMaterial->isBumped())
  611. {
  612. baseMaterial->setVertexShader("res/shaders/textured-bumped.vert");
  613. baseMaterial->setFragmentShader("res/shaders/textured-bumped.frag");
  614. }
  615. else
  616. {
  617. baseMaterial->setVertexShader("res/shaders/textured.vert");
  618. baseMaterial->setFragmentShader("res/shaders/textured.frag");
  619. }
  620. }
  621. else
  622. {
  623. baseMaterial->setVertexShader("res/shaders/textured-unlit.vert");
  624. baseMaterial->setFragmentShader("res/shaders/textured-unlit.frag");
  625. }
  626. Sampler* sampler = baseMaterial->createSampler(u_diffuseTexture);
  627. sampler->set("mipmap", "true");
  628. sampler->set("wrapS", CLAMP);
  629. sampler->set("wrapT", CLAMP);
  630. sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
  631. sampler->set(MAG_FILTER, LINEAR);
  632. }
  633. else
  634. {
  635. if (childMaterial->isLit())
  636. {
  637. baseMaterial->setVertexShader("res/shaders/colored.vert");
  638. baseMaterial->setFragmentShader("res/shaders/colored.frag");
  639. }
  640. else
  641. {
  642. baseMaterial->setVertexShader("res/shaders/colored-unlit.vert");
  643. baseMaterial->setFragmentShader("res/shaders/colored-unlit.frag");
  644. }
  645. }
  646. assert(baseMaterial);
  647. return baseMaterial;
  648. }
  649. void FBXSceneEncoder::loadBindShapes(FbxScene* fbxScene)
  650. {
  651. float m[16];
  652. const int poseCount = fbxScene->GetPoseCount();
  653. for (int i = 0; i < poseCount; ++i)
  654. {
  655. FbxPose* pose = fbxScene->GetPose(i);
  656. assert(pose);
  657. if (pose->IsBindPose() && pose->GetCount() > 0)
  658. {
  659. FbxNode* fbxNode = pose->GetNode(0);
  660. if (fbxNode->GetMesh() != NULL)
  661. {
  662. Node* node = _gamePlayFile.getNode(fbxNode->GetName());
  663. assert(node && node->getModel());
  664. Model* model = node->getModel();
  665. if (model && model->getSkin())
  666. {
  667. MeshSkin* skin = model->getSkin();
  668. copyMatrix(pose->GetMatrix(0), m);
  669. skin->setBindShape(m);
  670. }
  671. }
  672. }
  673. }
  674. }
  675. void FBXSceneEncoder::loadCamera(FbxNode* fbxNode, Node* node)
  676. {
  677. FbxCamera* fbxCamera = fbxNode->GetCamera();
  678. if (!fbxCamera)
  679. {
  680. return;
  681. }
  682. Camera* camera = new Camera();
  683. const char* name = fbxNode->GetName();
  684. if (name)
  685. {
  686. string id(name);
  687. id.append("_Camera");
  688. camera->setId(id);
  689. }
  690. camera->setAspectRatio(getAspectRatio(fbxCamera));
  691. camera->setNearPlane((float)fbxCamera->NearPlane.Get());
  692. camera->setFarPlane((float)fbxCamera->FarPlane.Get());
  693. if (fbxCamera->ProjectionType.Get() == FbxCamera::eOrthogonal)
  694. {
  695. camera->setOrthographic();
  696. camera->setViewportWidth((float)fbxCamera->GetApertureWidth());
  697. camera->setViewportWidth((float)fbxCamera->GetApertureHeight());
  698. // xmag in FBX can be calculated from: OrthoZoom * 30.0 / 2.0
  699. camera->setViewportWidth((float)fbxCamera->OrthoZoom.Get() * 15.0f);
  700. }
  701. else if (fbxCamera->ProjectionType.Get() == FbxCamera::ePerspective)
  702. {
  703. camera->setPerspective();
  704. camera->setFieldOfView(getFieldOfView(fbxCamera));
  705. }
  706. else
  707. {
  708. LOG(2, "Warning: Unknown camera type in node.\n");
  709. return;
  710. }
  711. _gamePlayFile.addCamera(camera);
  712. node->setCamera(camera);
  713. }
  714. void FBXSceneEncoder::loadLight(FbxNode* fbxNode, Node* node)
  715. {
  716. FbxLight* fbxLight = fbxNode->GetLight();
  717. if (!fbxLight)
  718. {
  719. return;
  720. }
  721. Light* light = new Light();
  722. const char* name = fbxNode->GetName();
  723. if (name)
  724. {
  725. string id(name);
  726. id.append("_Light");
  727. light->setId(id);
  728. }
  729. FbxDouble3 color = fbxLight->Color.Get();
  730. light->setColor((float)color[0], (float)color[1], (float)color[2]);
  731. switch (fbxLight->LightType.Get())
  732. {
  733. case FbxLight::ePoint:
  734. {
  735. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  736. switch (decayType)
  737. {
  738. case FbxLight::eNone:
  739. // FBX does not support ambients lights so ambient lights are converted
  740. // to point lights with no decay and visibility set to false.
  741. if (fbxNode->GetVisibility())
  742. {
  743. light->setPointLight();
  744. }
  745. else
  746. {
  747. light->setAmbientLight();
  748. }
  749. break;
  750. case FbxLight::eLinear:
  751. light->setPointLight();
  752. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  753. break;
  754. case FbxLight::eQuadratic:
  755. light->setPointLight();
  756. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  757. break;
  758. case FbxLight::eCubic:
  759. default:
  760. // Not supported..
  761. break;
  762. }
  763. break;
  764. }
  765. case FbxLight::eDirectional:
  766. {
  767. light->setDirectionalLight();
  768. break;
  769. }
  770. case FbxLight::eSpot:
  771. {
  772. light->setSpotLight();
  773. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  774. switch (decayType)
  775. {
  776. case FbxLight::eNone:
  777. // No decay.
  778. break;
  779. case FbxLight::eLinear:
  780. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  781. break;
  782. case FbxLight::eQuadratic:
  783. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  784. break;
  785. case FbxLight::eCubic:
  786. // Not supported..
  787. break;
  788. }
  789. light->setFalloffAngle(MATH_DEG_TO_RAD((float)fbxLight->OuterAngle.Get())); // fall off angle
  790. break;
  791. }
  792. default:
  793. {
  794. LOG(2, "Warning: Unknown light type in node.\n");
  795. return;
  796. }
  797. }
  798. _gamePlayFile.addLight(light);
  799. node->setLight(light);
  800. }
  801. void FBXSceneEncoder::loadModel(FbxNode* fbxNode, Node* node)
  802. {
  803. FbxMesh* fbxMesh = fbxNode->GetMesh();
  804. if (!fbxMesh)
  805. {
  806. return;
  807. }
  808. if (fbxMesh->IsTriangleMesh())
  809. {
  810. Mesh* mesh = loadMesh(fbxMesh);
  811. Model* model = new Model();
  812. model->setMesh(mesh);
  813. node->setModel(model);
  814. loadSkin(fbxMesh, model);
  815. if (model->getSkin())
  816. {
  817. node->resetTransformMatrix();
  818. }
  819. }
  820. }
  821. void FBXSceneEncoder::loadMaterials(FbxScene* fbxScene)
  822. {
  823. FbxNode* rootNode = fbxScene->GetRootNode();
  824. if (rootNode)
  825. {
  826. // Don't include the FBX root node
  827. const int childCount = rootNode->GetChildCount();
  828. for (int i = 0; i < childCount; ++i)
  829. {
  830. FbxNode* fbxNode = rootNode->GetChild(i);
  831. if (fbxNode)
  832. {
  833. loadMaterial(fbxNode);
  834. }
  835. }
  836. }
  837. }
  838. void FBXSceneEncoder::loadMaterial(FbxNode* fbxNode)
  839. {
  840. Node* node = findNode(fbxNode);
  841. Model* model = (node) ? node->getModel() : NULL;
  842. const int materialCount = fbxNode->GetMaterialCount();
  843. for (int index = 0; index < materialCount; ++index)
  844. {
  845. FbxSurfaceMaterial* fbxMaterial = fbxNode->GetMaterial(index);
  846. string materialName(fbxMaterial->GetName());
  847. fixMaterialName(materialName);
  848. Material* material = NULL;
  849. map<string, Material*>::iterator it = _materials.find(materialName);
  850. if (it != _materials.end())
  851. {
  852. // This material was already loaded so don't load it again
  853. material = it->second;
  854. }
  855. else
  856. {
  857. if (EncoderArguments::getInstance()->outputMaterialEnabled())
  858. {
  859. material = createMaterial(materialName, fbxMaterial, node);
  860. }
  861. else
  862. {
  863. // If outputMaterialEnabled() is not enabled then only create the materials for the purpose of writing
  864. // the material name in the GPB file. There is no need to load uniforms and samplers for the material.
  865. material = new Material(materialName);
  866. }
  867. _materials[materialName] = material;
  868. }
  869. if (materialCount == 1 && material && model)
  870. {
  871. model->setMaterial(material); // TODO: add support for materials per mesh part
  872. }
  873. else if (materialCount > 1 && material && model)
  874. {
  875. model->setMaterial(material, index);
  876. }
  877. }
  878. const int childCount = fbxNode->GetChildCount();
  879. for (int i = 0; i < childCount; ++i)
  880. {
  881. FbxNode* childNode = fbxNode->GetChild(i);
  882. if (childNode)
  883. {
  884. loadMaterial(childNode);
  885. }
  886. }
  887. }
  888. void FBXSceneEncoder::loadMaterialTextures(FbxSurfaceMaterial* fbxMaterial, Material* material)
  889. {
  890. FbxProperty fbxProperty;
  891. int textureIndex;
  892. FBXSDK_FOR_EACH_TEXTURE(textureIndex)
  893. {
  894. fbxProperty = fbxMaterial->FindProperty(FbxLayerElement::sTextureChannelNames[textureIndex]);
  895. //FindAndDisplayTextureInfoByProperty(fbxProperty, lDisplayHeader, lMaterialIndex);
  896. if ( fbxProperty.IsValid() )
  897. {
  898. int textureCount = fbxProperty.GetSrcObjectCount<FbxTexture>();
  899. for (int j = 0; j < textureCount; ++j)
  900. {
  901. FbxLayeredTexture *layeredTexture = fbxProperty.GetSrcObject<FbxLayeredTexture>(j);
  902. if (layeredTexture)
  903. {
  904. //DisplayInt(" Layered Texture: ", j);
  905. FbxLayeredTexture *layeredTexture = fbxProperty.GetSrcObject<FbxLayeredTexture>(j);
  906. int lNbTextures = layeredTexture->GetSrcObjectCount<FbxTexture>();
  907. for (int k = 0; k<lNbTextures; ++k)
  908. {
  909. FbxTexture* fbxTexture = layeredTexture->GetSrcObject<FbxTexture>(k);
  910. if (fbxTexture)
  911. {
  912. /*
  913. if (pDisplayHeader){
  914. DisplayInt(" Textures connected to Material ", pMaterialIndex);
  915. pDisplayHeader = false;
  916. }
  917. */
  918. //NOTE the blend mode is ALWAYS on the LayeredTexture and NOT the one on the texture.
  919. //Why is that? because one texture can be shared on different layered textures and might
  920. //have different blend modes.
  921. FbxLayeredTexture::EBlendMode lBlendMode;
  922. layeredTexture->GetTextureBlendMode(k, lBlendMode);
  923. //DisplayString(" Textures for ", pProperty.GetName());
  924. //DisplayInt(" Texture ", k);
  925. //DisplayTextureInfo(fbxTexture, (int) lBlendMode);
  926. }
  927. }
  928. }
  929. else if (FbxTexture* fbxTexture = fbxProperty.GetSrcObject<FbxTexture>(j))
  930. {
  931. //no layered texture simply get on the property
  932. if (FbxFileTexture* fileTexture = FbxCast<FbxFileTexture>(fbxTexture))
  933. {
  934. loadMaterialFileTexture(fileTexture, material);
  935. }
  936. }
  937. }
  938. }
  939. }
  940. }
  941. void FBXSceneEncoder::loadMaterialFileTexture(FbxFileTexture* fileTexture, Material* material)
  942. {
  943. FbxTexture::ETextureUse textureUse = fileTexture->GetTextureUse();
  944. Sampler* sampler = NULL;
  945. if (textureUse == FbxTexture::eStandard)
  946. {
  947. if (!material->getSampler("u_diffuseTexture"))
  948. sampler = material->createSampler("u_diffuseTexture");
  949. }
  950. else if (textureUse == FbxTexture::eBumpNormalMap)
  951. {
  952. if (!material->getSampler("u_normalmapTexture"))
  953. sampler = material->createSampler("u_normalmapTexture");
  954. }
  955. if (sampler)
  956. {
  957. sampler->set("absolutePath", fileTexture->GetFileName());
  958. sampler->set("relativePath", fileTexture->GetRelativeFileName());
  959. sampler->set("wrapS", fileTexture->GetWrapModeU() == FbxTexture::eClamp ? CLAMP : REPEAT);
  960. sampler->set("wrapT", fileTexture->GetWrapModeV() == FbxTexture::eClamp ? CLAMP : REPEAT);
  961. //sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
  962. //sampler->set(MAG_FILTER, LINEAR);
  963. if (textureUse == FbxTexture::eStandard)
  964. {
  965. double scaleU = fileTexture->GetScaleU();
  966. double scaleV = fileTexture->GetScaleV();
  967. if (scaleU != 1 || scaleV != 1)
  968. {
  969. ostringstream stream;
  970. stream << scaleU << ", " << scaleV;
  971. material->setUniform("u_textureRepeat", stream.str());
  972. material->addDefine(TEXTURE_REPEAT);
  973. }
  974. double translationU = fileTexture->GetTranslationU();
  975. double translationV = fileTexture->GetTranslationV();
  976. if (translationU != 0 || translationV != 0)
  977. {
  978. ostringstream stream;
  979. stream << translationU << ", " << translationV;
  980. material->setUniform("u_textureOffset", stream.str());
  981. material->addDefine(TEXTURE_OFFSET);
  982. }
  983. }
  984. }
  985. }
  986. void FBXSceneEncoder::loadMaterialUniforms(FbxSurfaceMaterial* fbxMaterial, Material* material)
  987. {
  988. if ( fbxMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId) )
  989. {
  990. FbxSurfaceLambert* lambert = FbxCast<FbxSurfaceLambert>(fbxMaterial);
  991. if (material->isLit())
  992. {
  993. FbxDouble3 ambient = lambert->Ambient.Get();
  994. if (!isBlack(ambient))
  995. {
  996. material->setUniform("u_ambientColor", toString(ambient));
  997. }
  998. }
  999. if (!material->isTextured())
  1000. {
  1001. if (!material->isDefined(VERTEX_COLOR))
  1002. {
  1003. FbxDouble3 diffuse = lambert->Diffuse.Get();
  1004. if (!isBlack(diffuse))
  1005. {
  1006. material->setUniform("u_diffuseColor", toString(diffuse, 1.0));
  1007. }
  1008. }
  1009. }
  1010. }
  1011. if (fbxMaterial->GetClassId().Is(FbxSurfacePhong::ClassId))
  1012. {
  1013. FbxSurfacePhong* phong = FbxCast<FbxSurfacePhong>(fbxMaterial);
  1014. //FbxDouble specularFactor = phong->SpecularFactor.Get();
  1015. if (material->isLit())
  1016. {
  1017. FbxDouble shininess = phong->Shininess.Get();
  1018. if (shininess > 0)
  1019. {
  1020. ostringstream stream;
  1021. stream << shininess;
  1022. material->setUniform("u_specularExponent", stream.str());
  1023. material->addDefine(SPECULAR);
  1024. }
  1025. }
  1026. //
  1027. //((FbxSurfacePhong *) fbxMaterial)->GetAmbientColor();
  1028. //((FbxSurfacePhong *) fbxMaterial)->GetDiffuseColor();
  1029. }
  1030. }
  1031. Material* FBXSceneEncoder::createMaterial(const string& name, FbxSurfaceMaterial* fbxMaterial, Node* node)
  1032. {
  1033. assert(fbxMaterial);
  1034. Material* material = new Material(name);
  1035. Model* model = (node) ? node->getModel() : NULL;
  1036. Mesh* mesh = (model) ? model->getMesh() : NULL;
  1037. if (mesh)
  1038. {
  1039. // The material should be lit if the model has normals or there are lights in the scene.
  1040. material->setLit(mesh->hasNormals() || _gamePlayFile.getLightCount() > 0);
  1041. if (mesh->hasVertexColors())
  1042. {
  1043. material->addDefine(VERTEX_COLOR);
  1044. }
  1045. }
  1046. MeshSkin* skin = (model) ? model->getSkin() : NULL;
  1047. if (skin && skin->getJointCount() > 0)
  1048. {
  1049. material->setUniform("u_matrixPalette", "MATRIX_PALETTE");
  1050. material->addDefine("SKINNING");
  1051. ostringstream stream;
  1052. stream << "SKINNING_JOINT_COUNT " << skin->getJointCount();
  1053. material->addDefine(stream.str());
  1054. }
  1055. loadMaterialTextures(fbxMaterial, material);
  1056. loadMaterialUniforms(fbxMaterial, material);
  1057. material->setParent(findBaseMaterial(material));
  1058. assert(material);
  1059. return material;
  1060. }
  1061. void FBXSceneEncoder::loadSkin(FbxMesh* fbxMesh, Model* model)
  1062. {
  1063. const int deformerCount = fbxMesh->GetDeformerCount();
  1064. for (int i = 0; i < deformerCount; ++i)
  1065. {
  1066. FbxDeformer* deformer = fbxMesh->GetDeformer(i);
  1067. if (deformer->GetDeformerType() == FbxDeformer::eSkin)
  1068. {
  1069. FbxSkin* fbxSkin = FbxCast<FbxSkin>(deformer);
  1070. MeshSkin* skin = new MeshSkin();
  1071. vector<string> jointNames;
  1072. vector<Node*> joints;
  1073. vector<Matrix> bindPoses;
  1074. const int clusterCount = fbxSkin->GetClusterCount();
  1075. for (int j = 0; j < clusterCount; ++j)
  1076. {
  1077. FbxCluster* cluster = fbxSkin->GetCluster(j);
  1078. assert(cluster);
  1079. FbxNode* linkedNode = cluster->GetLink();
  1080. if (linkedNode && linkedNode->GetSkeleton())
  1081. {
  1082. const char* jointName = linkedNode->GetName();
  1083. assert(jointName);
  1084. jointNames.push_back(jointName);
  1085. Node* joint = loadNode(linkedNode);
  1086. assert(joint);
  1087. joints.push_back(joint);
  1088. FbxAMatrix matrix;
  1089. cluster->GetTransformLinkMatrix(matrix);
  1090. Matrix m;
  1091. copyMatrix(matrix.Inverse(), m);
  1092. bindPoses.push_back(m);
  1093. }
  1094. }
  1095. skin->setJointNames(jointNames);
  1096. skin->setJoints(joints);
  1097. skin->setBindPoses(bindPoses);
  1098. model->setSkin(skin);
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. Mesh* FBXSceneEncoder::loadMesh(FbxMesh* fbxMesh)
  1104. {
  1105. // Check if this mesh has already been loaded.
  1106. Mesh* mesh = getMesh(fbxMesh->GetUniqueID());
  1107. if (mesh)
  1108. {
  1109. return mesh;
  1110. }
  1111. mesh = new Mesh();
  1112. // GamePlay requires that a mesh have a unique ID but FbxMesh doesn't have a string ID.
  1113. const char* name = fbxMesh->GetNode()->GetName();
  1114. if (name)
  1115. {
  1116. string id(name);
  1117. id.append("_Mesh");
  1118. mesh->setId(id);
  1119. }
  1120. // The number of mesh parts is equal to the number of materials that affect this mesh.
  1121. // There is always at least one mesh part.
  1122. vector<MeshPart*> meshParts;
  1123. const int materialCount = fbxMesh->GetNode()->GetMaterialCount();
  1124. int meshPartSize = (materialCount > 0) ? materialCount : 1;
  1125. for (int i = 0; i < meshPartSize; ++i)
  1126. {
  1127. meshParts.push_back(new MeshPart());
  1128. }
  1129. // Find the blend weights and blend indices if this mesh is skinned.
  1130. vector<vector<Vector2> > weights;
  1131. bool hasSkin = loadBlendWeights(fbxMesh, weights);
  1132. // Get list of uv sets for mesh
  1133. FbxStringList uvSetNameList;
  1134. fbxMesh->GetUVSetNames(uvSetNameList);
  1135. const int uvSetCount = uvSetNameList.GetCount();
  1136. int vertexIndex = 0;
  1137. FbxVector4* controlPoints = fbxMesh->GetControlPoints();
  1138. const int polygonCount = fbxMesh->GetPolygonCount();
  1139. for (int polyIndex = 0; polyIndex < polygonCount; ++polyIndex)
  1140. {
  1141. const int polygonSize = fbxMesh->GetPolygonSize(polyIndex);
  1142. for (int posInPoly = 0; posInPoly < polygonSize; ++posInPoly)
  1143. {
  1144. int controlPointIndex = fbxMesh->GetPolygonVertex(polyIndex, posInPoly);
  1145. Vertex vertex;
  1146. FbxVector4& position = controlPoints[controlPointIndex];
  1147. vertex.position.x = (float)position[0];
  1148. vertex.position.y = (float)position[1];
  1149. vertex.position.z = (float)position[2];
  1150. // Load tex coords for all uv sets
  1151. for (int uvSetIndex = 0; uvSetIndex < uvSetCount; ++uvSetIndex)
  1152. {
  1153. const FbxGeometryElementUV* uvElement = fbxMesh->GetElementUV(uvSetNameList.GetStringAt(uvSetIndex));
  1154. if (uvElement)
  1155. loadTextureCoords(fbxMesh, uvElement, uvSetIndex, polyIndex, posInPoly, vertexIndex, &vertex);
  1156. }
  1157. // Load other data
  1158. loadNormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1159. loadTangent(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1160. loadBinormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1161. loadVertexColor(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1162. if (hasSkin)
  1163. {
  1164. loadBlendData(weights[controlPointIndex], &vertex);
  1165. }
  1166. // Determine which mesh part this vertex index should be added to based on the material that affects it.
  1167. int meshPartIndex = 0;
  1168. const int elementMatrialCount = fbxMesh->GetElementMaterialCount();
  1169. for (int k = 0; k < elementMatrialCount; ++k)
  1170. {
  1171. FbxGeometryElementMaterial* elementMaterial = fbxMesh->GetElementMaterial(k);
  1172. meshPartIndex = elementMaterial->GetIndexArray().GetAt(polyIndex);
  1173. }
  1174. // Add the vertex to the mesh if it hasn't already been added and find the vertex index.
  1175. unsigned int index;
  1176. if (mesh->contains(vertex))
  1177. {
  1178. index = mesh->getVertexIndex(vertex);
  1179. }
  1180. else
  1181. {
  1182. index = mesh->addVertex(vertex);
  1183. }
  1184. meshParts[meshPartIndex]->addIndex(index);
  1185. vertexIndex++;
  1186. }
  1187. }
  1188. const size_t meshpartsSize = meshParts.size();
  1189. for (size_t i = 0; i < meshpartsSize; ++i)
  1190. {
  1191. mesh->addMeshPart(meshParts[i]);
  1192. }
  1193. // The order that the vertex elements are add to the list matters.
  1194. // It should be the same order as how the Vertex data is written.
  1195. // Position
  1196. mesh->addVetexAttribute(POSITION, Vertex::POSITION_COUNT);
  1197. const Vertex& vertex = mesh->vertices[0];
  1198. // Normals
  1199. if (vertex.hasNormal)
  1200. {
  1201. mesh->addVetexAttribute(NORMAL, Vertex::NORMAL_COUNT);
  1202. }
  1203. // Tangents
  1204. if (vertex.hasTangent)
  1205. {
  1206. mesh->addVetexAttribute(TANGENT, Vertex::TANGENT_COUNT);
  1207. }
  1208. // Binormals
  1209. if (vertex.hasBinormal)
  1210. {
  1211. mesh->addVetexAttribute(BINORMAL, Vertex::BINORMAL_COUNT);
  1212. }
  1213. // Texture Coordinates
  1214. for (unsigned int i = 0; i < MAX_UV_SETS; ++i)
  1215. {
  1216. if (vertex.hasTexCoord[i])
  1217. {
  1218. mesh->addVetexAttribute(TEXCOORD0 + i, Vertex::TEXCOORD_COUNT);
  1219. }
  1220. }
  1221. // Diffuse Color
  1222. if (vertex.hasDiffuse)
  1223. {
  1224. mesh->addVetexAttribute(COLOR, Vertex::DIFFUSE_COUNT);
  1225. }
  1226. // Skinning BlendWeights BlendIndices
  1227. if (vertex.hasWeights)
  1228. {
  1229. mesh->addVetexAttribute(BLENDWEIGHTS, Vertex::BLEND_WEIGHTS_COUNT);
  1230. mesh->addVetexAttribute(BLENDINDICES, Vertex::BLEND_INDICES_COUNT);
  1231. }
  1232. _gamePlayFile.addMesh(mesh);
  1233. saveMesh(fbxMesh->GetUniqueID(), mesh);
  1234. return mesh;
  1235. }
  1236. void FBXSceneEncoder::triangulateRecursive(FbxNode* fbxNode)
  1237. {
  1238. // Triangulate all NURBS, patch and mesh under this node recursively.
  1239. FbxNodeAttribute* nodeAttribute = fbxNode->GetNodeAttribute();
  1240. if (nodeAttribute)
  1241. {
  1242. FbxNodeAttribute::EType type = nodeAttribute->GetAttributeType();
  1243. if (type == FbxNodeAttribute::eMesh ||
  1244. type == FbxNodeAttribute::eNurbs ||
  1245. type == FbxNodeAttribute::eNurbsSurface ||
  1246. type == FbxNodeAttribute::ePatch)
  1247. {
  1248. FbxGeometryConverter converter(fbxNode->GetFbxManager());
  1249. converter.TriangulateInPlace(fbxNode);
  1250. }
  1251. }
  1252. const int childCount = fbxNode->GetChildCount();
  1253. for (int childIndex = 0; childIndex < childCount; ++childIndex)
  1254. {
  1255. triangulateRecursive(fbxNode->GetChild(childIndex));
  1256. }
  1257. }
  1258. // Functions
  1259. void fixMaterialName(string& name)
  1260. {
  1261. static int unnamedCount = 0;
  1262. for (string::size_type i = 0, len = name.length(); i < len; ++i)
  1263. {
  1264. if (!isalnum(name[i]))
  1265. name[i] = '_';
  1266. }
  1267. if (name.length() == 0)
  1268. {
  1269. ostringstream stream;
  1270. stream << "unnamed_" << (++unnamedCount);
  1271. name = stream.str();
  1272. }
  1273. }