FBXSceneEncoder.cpp 43 KB

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