FBXSceneEncoder.cpp 44 KB

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