FBXSceneEncoder.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  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->GetLastErrorString());
  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");
  600. // Always use directional light
  601. baseMaterial->setUniform("u_lightDirection", "SCENE_LIGHT_DIRECTION");
  602. baseMaterial->setUniform("u_lightColor", "SCENE_LIGHT_COLOR");
  603. if (childMaterial->isSpecular())
  604. {
  605. baseMaterial->addDefine(SPECULAR);
  606. baseMaterial->setUniform("u_cameraPosition", "CAMERA_WORLD_POSITION");
  607. }
  608. }
  609. if (childMaterial->isTextured())
  610. {
  611. if (childMaterial->isLit())
  612. {
  613. if (childMaterial->isBumped())
  614. {
  615. baseMaterial->setVertexShader("res/shaders/textured-bumped.vert");
  616. baseMaterial->setFragmentShader("res/shaders/textured-bumped.frag");
  617. }
  618. else
  619. {
  620. baseMaterial->setVertexShader("res/shaders/textured.vert");
  621. baseMaterial->setFragmentShader("res/shaders/textured.frag");
  622. }
  623. }
  624. else
  625. {
  626. baseMaterial->setVertexShader("res/shaders/textured-unlit.vert");
  627. baseMaterial->setFragmentShader("res/shaders/textured-unlit.frag");
  628. }
  629. Sampler* sampler = baseMaterial->createSampler(u_diffuseTexture);
  630. sampler->set("mipmap", "true");
  631. sampler->set("wrapS", CLAMP);
  632. sampler->set("wrapT", CLAMP);
  633. sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
  634. sampler->set(MAG_FILTER, LINEAR);
  635. }
  636. else
  637. {
  638. if (childMaterial->isLit())
  639. {
  640. baseMaterial->setVertexShader("res/shaders/colored.vert");
  641. baseMaterial->setFragmentShader("res/shaders/colored.frag");
  642. }
  643. else
  644. {
  645. baseMaterial->setVertexShader("res/shaders/colored-unlit.vert");
  646. baseMaterial->setFragmentShader("res/shaders/colored-unlit.frag");
  647. }
  648. }
  649. assert(baseMaterial);
  650. return baseMaterial;
  651. }
  652. void FBXSceneEncoder::loadBindShapes(FbxScene* fbxScene)
  653. {
  654. float m[16];
  655. const int poseCount = fbxScene->GetPoseCount();
  656. for (int i = 0; i < poseCount; ++i)
  657. {
  658. FbxPose* pose = fbxScene->GetPose(i);
  659. assert(pose);
  660. if (pose->IsBindPose() && pose->GetCount() > 0)
  661. {
  662. FbxNode* fbxNode = pose->GetNode(0);
  663. if (fbxNode->GetMesh() != NULL)
  664. {
  665. Node* node = _gamePlayFile.getNode(fbxNode->GetName());
  666. assert(node && node->getModel());
  667. Model* model = node->getModel();
  668. if (model && model->getSkin())
  669. {
  670. MeshSkin* skin = model->getSkin();
  671. copyMatrix(pose->GetMatrix(0), m);
  672. skin->setBindShape(m);
  673. }
  674. }
  675. }
  676. }
  677. }
  678. void FBXSceneEncoder::loadCamera(FbxNode* fbxNode, Node* node)
  679. {
  680. FbxCamera* fbxCamera = fbxNode->GetCamera();
  681. if (!fbxCamera)
  682. {
  683. return;
  684. }
  685. Camera* camera = new Camera();
  686. const char* name = fbxNode->GetName();
  687. if (name)
  688. {
  689. string id(name);
  690. id.append("_Camera");
  691. camera->setId(id);
  692. }
  693. camera->setAspectRatio(getAspectRatio(fbxCamera));
  694. camera->setNearPlane((float)fbxCamera->NearPlane.Get());
  695. camera->setFarPlane((float)fbxCamera->FarPlane.Get());
  696. if (fbxCamera->ProjectionType.Get() == FbxCamera::eOrthogonal)
  697. {
  698. camera->setOrthographic();
  699. camera->setViewportWidth((float)fbxCamera->GetApertureWidth());
  700. camera->setViewportWidth((float)fbxCamera->GetApertureHeight());
  701. // xmag in FBX can be calculated from: OrthoZoom * 30.0 / 2.0
  702. camera->setViewportWidth((float)fbxCamera->OrthoZoom.Get() * 15.0f);
  703. }
  704. else if (fbxCamera->ProjectionType.Get() == FbxCamera::ePerspective)
  705. {
  706. camera->setPerspective();
  707. camera->setFieldOfView(getFieldOfView(fbxCamera));
  708. }
  709. else
  710. {
  711. LOG(2, "Warning: Unknown camera type in node.\n");
  712. return;
  713. }
  714. _gamePlayFile.addCamera(camera);
  715. node->setCamera(camera);
  716. }
  717. void FBXSceneEncoder::loadLight(FbxNode* fbxNode, Node* node)
  718. {
  719. FbxLight* fbxLight = fbxNode->GetLight();
  720. if (!fbxLight)
  721. {
  722. return;
  723. }
  724. Light* light = new Light();
  725. const char* name = fbxNode->GetName();
  726. if (name)
  727. {
  728. string id(name);
  729. id.append("_Light");
  730. light->setId(id);
  731. }
  732. FbxDouble3 color = fbxLight->Color.Get();
  733. light->setColor((float)color[0], (float)color[1], (float)color[2]);
  734. switch (fbxLight->LightType.Get())
  735. {
  736. case FbxLight::ePoint:
  737. {
  738. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  739. switch (decayType)
  740. {
  741. case FbxLight::eNone:
  742. // FBX does not support ambients lights so ambient lights are converted
  743. // to point lights with no decay and visibility set to false.
  744. if (fbxNode->GetVisibility())
  745. {
  746. light->setPointLight();
  747. }
  748. else
  749. {
  750. light->setAmbientLight();
  751. }
  752. break;
  753. case FbxLight::eLinear:
  754. light->setPointLight();
  755. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  756. break;
  757. case FbxLight::eQuadratic:
  758. light->setPointLight();
  759. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  760. break;
  761. case FbxLight::eCubic:
  762. default:
  763. // Not supported..
  764. break;
  765. }
  766. break;
  767. }
  768. case FbxLight::eDirectional:
  769. {
  770. light->setDirectionalLight();
  771. break;
  772. }
  773. case FbxLight::eSpot:
  774. {
  775. light->setSpotLight();
  776. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  777. switch (decayType)
  778. {
  779. case FbxLight::eNone:
  780. // No decay.
  781. break;
  782. case FbxLight::eLinear:
  783. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  784. break;
  785. case FbxLight::eQuadratic:
  786. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  787. break;
  788. case FbxLight::eCubic:
  789. // Not supported..
  790. break;
  791. }
  792. light->setFalloffAngle(MATH_DEG_TO_RAD((float)fbxLight->OuterAngle.Get())); // fall off angle
  793. break;
  794. }
  795. default:
  796. {
  797. LOG(2, "Warning: Unknown light type in node.\n");
  798. return;
  799. }
  800. }
  801. _gamePlayFile.addLight(light);
  802. node->setLight(light);
  803. }
  804. void FBXSceneEncoder::loadModel(FbxNode* fbxNode, Node* node)
  805. {
  806. FbxMesh* fbxMesh = fbxNode->GetMesh();
  807. if (!fbxMesh)
  808. {
  809. return;
  810. }
  811. if (fbxMesh->IsTriangleMesh())
  812. {
  813. Mesh* mesh = loadMesh(fbxMesh);
  814. Model* model = new Model();
  815. model->setMesh(mesh);
  816. node->setModel(model);
  817. loadSkin(fbxMesh, model);
  818. if (model->getSkin())
  819. {
  820. node->resetTransformMatrix();
  821. }
  822. }
  823. }
  824. void FBXSceneEncoder::loadMaterials(FbxScene* fbxScene)
  825. {
  826. FbxNode* rootNode = fbxScene->GetRootNode();
  827. if (rootNode)
  828. {
  829. // Don't include the FBX root node
  830. const int childCount = rootNode->GetChildCount();
  831. for (int i = 0; i < childCount; ++i)
  832. {
  833. FbxNode* fbxNode = rootNode->GetChild(i);
  834. if (fbxNode)
  835. {
  836. loadMaterial(fbxNode);
  837. }
  838. }
  839. }
  840. }
  841. void FBXSceneEncoder::loadMaterial(FbxNode* fbxNode)
  842. {
  843. Node* node = findNode(fbxNode);
  844. Model* model = (node) ? node->getModel() : NULL;
  845. const int materialCount = fbxNode->GetMaterialCount();
  846. for (int index = 0; index < materialCount; ++index)
  847. {
  848. FbxSurfaceMaterial* fbxMaterial = fbxNode->GetMaterial(index);
  849. string materialName(fbxMaterial->GetName());
  850. fixMaterialName(materialName);
  851. Material* material = NULL;
  852. map<string, Material*>::iterator it = _materials.find(materialName);
  853. if (it != _materials.end())
  854. {
  855. // This material was already loaded so don't load it again
  856. material = it->second;
  857. }
  858. else
  859. {
  860. if (EncoderArguments::getInstance()->outputMaterialEnabled())
  861. {
  862. material = createMaterial(materialName, fbxMaterial, node);
  863. }
  864. else
  865. {
  866. // If outputMaterialEnabled() is not enabled then only create the materials for the purpose of writing
  867. // the material name in the GPB file. There is no need to load uniforms and samplers for the material.
  868. material = new Material(materialName);
  869. }
  870. _materials[materialName] = material;
  871. }
  872. if (materialCount == 1 && material && model)
  873. {
  874. model->setMaterial(material); // TODO: add support for materials per mesh part
  875. }
  876. else if (materialCount > 1 && material && model)
  877. {
  878. model->setMaterial(material, index);
  879. }
  880. }
  881. const int childCount = fbxNode->GetChildCount();
  882. for (int i = 0; i < childCount; ++i)
  883. {
  884. FbxNode* childNode = fbxNode->GetChild(i);
  885. if (childNode)
  886. {
  887. loadMaterial(childNode);
  888. }
  889. }
  890. }
  891. void FBXSceneEncoder::loadMaterialTextures(FbxSurfaceMaterial* fbxMaterial, Material* material)
  892. {
  893. FbxProperty fbxProperty;
  894. int textureIndex;
  895. FBXSDK_FOR_EACH_TEXTURE(textureIndex)
  896. {
  897. fbxProperty = fbxMaterial->FindProperty(FbxLayerElement::sTextureChannelNames[textureIndex]);
  898. //FindAndDisplayTextureInfoByProperty(fbxProperty, lDisplayHeader, lMaterialIndex);
  899. if ( fbxProperty.IsValid() )
  900. {
  901. int textureCount = fbxProperty.GetSrcObjectCount<FbxTexture>();
  902. for (int j = 0; j < textureCount; ++j)
  903. {
  904. FbxLayeredTexture *layeredTexture = fbxProperty.GetSrcObject<FbxLayeredTexture>(j);
  905. if (layeredTexture)
  906. {
  907. //DisplayInt(" Layered Texture: ", j);
  908. FbxLayeredTexture *layeredTexture = fbxProperty.GetSrcObject<FbxLayeredTexture>(j);
  909. int lNbTextures = layeredTexture->GetSrcObjectCount<FbxTexture>();
  910. for (int k = 0; k<lNbTextures; ++k)
  911. {
  912. FbxTexture* fbxTexture = layeredTexture->GetSrcObject<FbxTexture>(k);
  913. if (fbxTexture)
  914. {
  915. /*
  916. if (pDisplayHeader){
  917. DisplayInt(" Textures connected to Material ", pMaterialIndex);
  918. pDisplayHeader = false;
  919. }
  920. */
  921. //NOTE the blend mode is ALWAYS on the LayeredTexture and NOT the one on the texture.
  922. //Why is that? because one texture can be shared on different layered textures and might
  923. //have different blend modes.
  924. FbxLayeredTexture::EBlendMode lBlendMode;
  925. layeredTexture->GetTextureBlendMode(k, lBlendMode);
  926. //DisplayString(" Textures for ", pProperty.GetName());
  927. //DisplayInt(" Texture ", k);
  928. //DisplayTextureInfo(fbxTexture, (int) lBlendMode);
  929. }
  930. }
  931. }
  932. else if (FbxTexture* fbxTexture = fbxProperty.GetSrcObject<FbxTexture>(j))
  933. {
  934. //no layered texture simply get on the property
  935. if (FbxFileTexture* fileTexture = FbxCast<FbxFileTexture>(fbxTexture))
  936. {
  937. loadMaterialFileTexture(fileTexture, material);
  938. }
  939. }
  940. }
  941. }
  942. }
  943. }
  944. void FBXSceneEncoder::loadMaterialFileTexture(FbxFileTexture* fileTexture, Material* material)
  945. {
  946. FbxTexture::ETextureUse textureUse = fileTexture->GetTextureUse();
  947. Sampler* sampler = NULL;
  948. if (textureUse == FbxTexture::eStandard)
  949. {
  950. if (!material->getSampler("u_diffuseTexture"))
  951. sampler = material->createSampler("u_diffuseTexture");
  952. }
  953. else if (textureUse == FbxTexture::eBumpNormalMap)
  954. {
  955. if (!material->getSampler("u_normalmapTexture"))
  956. sampler = material->createSampler("u_normalmapTexture");
  957. }
  958. if (sampler)
  959. {
  960. sampler->set("absolutePath", fileTexture->GetFileName());
  961. sampler->set("relativePath", fileTexture->GetRelativeFileName());
  962. sampler->set("wrapS", fileTexture->GetWrapModeU() == FbxTexture::eClamp ? CLAMP : REPEAT);
  963. sampler->set("wrapT", fileTexture->GetWrapModeV() == FbxTexture::eClamp ? CLAMP : REPEAT);
  964. //sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
  965. //sampler->set(MAG_FILTER, LINEAR);
  966. if (textureUse == FbxTexture::eStandard)
  967. {
  968. double scaleU = fileTexture->GetScaleU();
  969. double scaleV = fileTexture->GetScaleV();
  970. if (scaleU != 1 || scaleV != 1)
  971. {
  972. ostringstream stream;
  973. stream << scaleU << ", " << scaleV;
  974. material->setUniform("u_textureRepeat", stream.str());
  975. material->addDefine(TEXTURE_REPEAT);
  976. }
  977. double translationU = fileTexture->GetTranslationU();
  978. double translationV = fileTexture->GetTranslationV();
  979. if (translationU != 0 || translationV != 0)
  980. {
  981. ostringstream stream;
  982. stream << translationU << ", " << translationV;
  983. material->setUniform("u_textureOffset", stream.str());
  984. material->addDefine(TEXTURE_OFFSET);
  985. }
  986. }
  987. }
  988. }
  989. void FBXSceneEncoder::loadMaterialUniforms(FbxSurfaceMaterial* fbxMaterial, Material* material)
  990. {
  991. if ( fbxMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId) )
  992. {
  993. FbxSurfaceLambert* lambert = FbxCast<FbxSurfaceLambert>(fbxMaterial);
  994. if (material->isLit())
  995. {
  996. FbxDouble3 ambient = lambert->Ambient.Get();
  997. if (!isBlack(ambient))
  998. {
  999. material->setUniform("u_ambientColor", toString(ambient));
  1000. }
  1001. }
  1002. if (!material->isTextured())
  1003. {
  1004. if (!material->isDefined(VERTEX_COLOR))
  1005. {
  1006. FbxDouble3 diffuse = lambert->Diffuse.Get();
  1007. if (!isBlack(diffuse))
  1008. {
  1009. material->setUniform("u_diffuseColor", toString(diffuse, 1.0));
  1010. }
  1011. }
  1012. }
  1013. }
  1014. if (fbxMaterial->GetClassId().Is(FbxSurfacePhong::ClassId))
  1015. {
  1016. FbxSurfacePhong* phong = FbxCast<FbxSurfacePhong>(fbxMaterial);
  1017. //FbxDouble specularFactor = phong->SpecularFactor.Get();
  1018. if (material->isLit())
  1019. {
  1020. FbxDouble shininess = phong->Shininess.Get();
  1021. if (shininess > 0)
  1022. {
  1023. ostringstream stream;
  1024. stream << shininess;
  1025. material->setUniform("u_specularExponent", stream.str());
  1026. material->addDefine(SPECULAR);
  1027. }
  1028. }
  1029. //
  1030. //((FbxSurfacePhong *) fbxMaterial)->GetAmbientColor();
  1031. //((FbxSurfacePhong *) fbxMaterial)->GetDiffuseColor();
  1032. }
  1033. }
  1034. Material* FBXSceneEncoder::createMaterial(const string& name, FbxSurfaceMaterial* fbxMaterial, Node* node)
  1035. {
  1036. assert(fbxMaterial);
  1037. Material* material = new Material(name);
  1038. Model* model = (node) ? node->getModel() : NULL;
  1039. Mesh* mesh = (model) ? model->getMesh() : NULL;
  1040. if (mesh)
  1041. {
  1042. // The material should be lit if the model has normals or there are lights in the scene.
  1043. material->setLit(mesh->hasNormals() || _gamePlayFile.getLightCount() > 0);
  1044. if (mesh->hasVertexColors())
  1045. {
  1046. material->addDefine(VERTEX_COLOR);
  1047. }
  1048. }
  1049. MeshSkin* skin = (model) ? model->getSkin() : NULL;
  1050. if (skin && skin->getJointCount() > 0)
  1051. {
  1052. material->setUniform("u_matrixPalette", "MATRIX_PALETTE");
  1053. material->addDefine("SKINNING");
  1054. ostringstream stream;
  1055. stream << "SKINNING_JOINT_COUNT " << skin->getJointCount();
  1056. material->addDefine(stream.str());
  1057. }
  1058. loadMaterialTextures(fbxMaterial, material);
  1059. loadMaterialUniforms(fbxMaterial, material);
  1060. material->setParent(findBaseMaterial(material));
  1061. assert(material);
  1062. return material;
  1063. }
  1064. void FBXSceneEncoder::loadSkin(FbxMesh* fbxMesh, Model* model)
  1065. {
  1066. const int deformerCount = fbxMesh->GetDeformerCount();
  1067. for (int i = 0; i < deformerCount; ++i)
  1068. {
  1069. FbxDeformer* deformer = fbxMesh->GetDeformer(i);
  1070. if (deformer->GetDeformerType() == FbxDeformer::eSkin)
  1071. {
  1072. FbxSkin* fbxSkin = FbxCast<FbxSkin>(deformer);
  1073. MeshSkin* skin = new MeshSkin();
  1074. vector<string> jointNames;
  1075. vector<Node*> joints;
  1076. vector<Matrix> bindPoses;
  1077. const int clusterCount = fbxSkin->GetClusterCount();
  1078. for (int j = 0; j < clusterCount; ++j)
  1079. {
  1080. FbxCluster* cluster = fbxSkin->GetCluster(j);
  1081. assert(cluster);
  1082. FbxNode* linkedNode = cluster->GetLink();
  1083. if (linkedNode && linkedNode->GetSkeleton())
  1084. {
  1085. const char* jointName = linkedNode->GetName();
  1086. assert(jointName);
  1087. jointNames.push_back(jointName);
  1088. Node* joint = loadNode(linkedNode);
  1089. assert(joint);
  1090. joints.push_back(joint);
  1091. FbxAMatrix matrix;
  1092. cluster->GetTransformLinkMatrix(matrix);
  1093. Matrix m;
  1094. copyMatrix(matrix.Inverse(), m);
  1095. bindPoses.push_back(m);
  1096. }
  1097. }
  1098. skin->setJointNames(jointNames);
  1099. skin->setJoints(joints);
  1100. skin->setBindPoses(bindPoses);
  1101. model->setSkin(skin);
  1102. break;
  1103. }
  1104. }
  1105. }
  1106. Mesh* FBXSceneEncoder::loadMesh(FbxMesh* fbxMesh)
  1107. {
  1108. // Check if this mesh has already been loaded.
  1109. Mesh* mesh = getMesh(fbxMesh->GetUniqueID());
  1110. if (mesh)
  1111. {
  1112. return mesh;
  1113. }
  1114. mesh = new Mesh();
  1115. // GamePlay requires that a mesh have a unique ID but FbxMesh doesn't have a string ID.
  1116. const char* name = fbxMesh->GetNode()->GetName();
  1117. if (name)
  1118. {
  1119. string id(name);
  1120. id.append("_Mesh");
  1121. mesh->setId(id);
  1122. }
  1123. // The number of mesh parts is equal to the number of materials that affect this mesh.
  1124. // There is always at least one mesh part.
  1125. vector<MeshPart*> meshParts;
  1126. const int materialCount = fbxMesh->GetNode()->GetMaterialCount();
  1127. int meshPartSize = (materialCount > 0) ? materialCount : 1;
  1128. for (int i = 0; i < meshPartSize; ++i)
  1129. {
  1130. meshParts.push_back(new MeshPart());
  1131. }
  1132. // Find the blend weights and blend indices if this mesh is skinned.
  1133. vector<vector<Vector2> > weights;
  1134. bool hasSkin = loadBlendWeights(fbxMesh, weights);
  1135. // Get list of uv sets for mesh
  1136. FbxStringList uvSetNameList;
  1137. fbxMesh->GetUVSetNames(uvSetNameList);
  1138. const int uvSetCount = uvSetNameList.GetCount();
  1139. int vertexIndex = 0;
  1140. FbxVector4* controlPoints = fbxMesh->GetControlPoints();
  1141. const int polygonCount = fbxMesh->GetPolygonCount();
  1142. for (int polyIndex = 0; polyIndex < polygonCount; ++polyIndex)
  1143. {
  1144. const int polygonSize = fbxMesh->GetPolygonSize(polyIndex);
  1145. for (int posInPoly = 0; posInPoly < polygonSize; ++posInPoly)
  1146. {
  1147. int controlPointIndex = fbxMesh->GetPolygonVertex(polyIndex, posInPoly);
  1148. Vertex vertex;
  1149. FbxVector4& position = controlPoints[controlPointIndex];
  1150. vertex.position.x = (float)position[0];
  1151. vertex.position.y = (float)position[1];
  1152. vertex.position.z = (float)position[2];
  1153. // Load tex coords for all uv sets
  1154. for (int uvSetIndex = 0; uvSetIndex < uvSetCount; ++uvSetIndex)
  1155. {
  1156. const FbxGeometryElementUV* uvElement = fbxMesh->GetElementUV(uvSetNameList.GetStringAt(uvSetIndex));
  1157. if (uvElement)
  1158. loadTextureCoords(fbxMesh, uvElement, uvSetIndex, polyIndex, posInPoly, vertexIndex, &vertex);
  1159. }
  1160. // Load other data
  1161. loadNormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1162. loadTangent(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1163. loadBinormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1164. loadVertexColor(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1165. if (hasSkin)
  1166. {
  1167. loadBlendData(weights[controlPointIndex], &vertex);
  1168. }
  1169. // Determine which mesh part this vertex index should be added to based on the material that affects it.
  1170. int meshPartIndex = 0;
  1171. const int elementMatrialCount = fbxMesh->GetElementMaterialCount();
  1172. for (int k = 0; k < elementMatrialCount; ++k)
  1173. {
  1174. FbxGeometryElementMaterial* elementMaterial = fbxMesh->GetElementMaterial(k);
  1175. meshPartIndex = elementMaterial->GetIndexArray().GetAt(polyIndex);
  1176. }
  1177. // Add the vertex to the mesh if it hasn't already been added and find the vertex index.
  1178. unsigned int index;
  1179. if (mesh->contains(vertex))
  1180. {
  1181. index = mesh->getVertexIndex(vertex);
  1182. }
  1183. else
  1184. {
  1185. index = mesh->addVertex(vertex);
  1186. }
  1187. meshParts[meshPartIndex]->addIndex(index);
  1188. vertexIndex++;
  1189. }
  1190. }
  1191. const size_t meshpartsSize = meshParts.size();
  1192. for (size_t i = 0; i < meshpartsSize; ++i)
  1193. {
  1194. mesh->addMeshPart(meshParts[i]);
  1195. }
  1196. // The order that the vertex elements are add to the list matters.
  1197. // It should be the same order as how the Vertex data is written.
  1198. // Position
  1199. mesh->addVetexAttribute(POSITION, Vertex::POSITION_COUNT);
  1200. const Vertex& vertex = mesh->vertices[0];
  1201. // Normals
  1202. if (vertex.hasNormal)
  1203. {
  1204. mesh->addVetexAttribute(NORMAL, Vertex::NORMAL_COUNT);
  1205. }
  1206. // Tangents
  1207. if (vertex.hasTangent)
  1208. {
  1209. mesh->addVetexAttribute(TANGENT, Vertex::TANGENT_COUNT);
  1210. }
  1211. // Binormals
  1212. if (vertex.hasBinormal)
  1213. {
  1214. mesh->addVetexAttribute(BINORMAL, Vertex::BINORMAL_COUNT);
  1215. }
  1216. // Texture Coordinates
  1217. for (unsigned int i = 0; i < MAX_UV_SETS; ++i)
  1218. {
  1219. if (vertex.hasTexCoord[i])
  1220. {
  1221. mesh->addVetexAttribute(TEXCOORD0 + i, Vertex::TEXCOORD_COUNT);
  1222. }
  1223. }
  1224. // Diffuse Color
  1225. if (vertex.hasDiffuse)
  1226. {
  1227. mesh->addVetexAttribute(COLOR, Vertex::DIFFUSE_COUNT);
  1228. }
  1229. // Skinning BlendWeights BlendIndices
  1230. if (vertex.hasWeights)
  1231. {
  1232. mesh->addVetexAttribute(BLENDWEIGHTS, Vertex::BLEND_WEIGHTS_COUNT);
  1233. mesh->addVetexAttribute(BLENDINDICES, Vertex::BLEND_INDICES_COUNT);
  1234. }
  1235. _gamePlayFile.addMesh(mesh);
  1236. saveMesh(fbxMesh->GetUniqueID(), mesh);
  1237. return mesh;
  1238. }
  1239. void FBXSceneEncoder::triangulateRecursive(FbxNode* fbxNode)
  1240. {
  1241. // Triangulate all NURBS, patch and mesh under this node recursively.
  1242. FbxNodeAttribute* nodeAttribute = fbxNode->GetNodeAttribute();
  1243. if (nodeAttribute)
  1244. {
  1245. FbxNodeAttribute::EType type = nodeAttribute->GetAttributeType();
  1246. if (type == FbxNodeAttribute::eMesh ||
  1247. type == FbxNodeAttribute::eNurbs ||
  1248. type == FbxNodeAttribute::eNurbsSurface ||
  1249. type == FbxNodeAttribute::ePatch)
  1250. {
  1251. FbxGeometryConverter converter(fbxNode->GetFbxManager());
  1252. converter.TriangulateInPlace(fbxNode);
  1253. }
  1254. }
  1255. const int childCount = fbxNode->GetChildCount();
  1256. for (int childIndex = 0; childIndex < childCount; ++childIndex)
  1257. {
  1258. triangulateRecursive(fbxNode->GetChild(childIndex));
  1259. }
  1260. }
  1261. // Functions
  1262. void fixMaterialName(string& name)
  1263. {
  1264. static int unnamedCount = 0;
  1265. for (string::size_type i = 0, len = name.length(); i < len; ++i)
  1266. {
  1267. if (!isalnum(name[i]))
  1268. name[i] = '_';
  1269. }
  1270. if (name.length() == 0)
  1271. {
  1272. ostringstream stream;
  1273. stream << "unnamed_" << (++unnamedCount);
  1274. name = stream.str();
  1275. }
  1276. }