FBXSceneEncoder.cpp 45 KB

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