FBXSceneEncoder.cpp 43 KB

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