DAESceneEncoder.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. /*
  2. * DAESceneEncoder.h
  3. */
  4. #include "Base.h"
  5. #include "DAESceneEncoder.h"
  6. #include "DAEOptimizer.h"
  7. //#define ENCODER_PRINT_TIME 1
  8. namespace gameplay
  9. {
  10. DAESceneEncoder::DAESceneEncoder()
  11. : _collada(NULL), _dom(NULL), file(NULL), _vertexBlendWeights(NULL), _vertexBlendIndices(NULL)
  12. {
  13. }
  14. DAESceneEncoder::~DAESceneEncoder()
  15. {
  16. }
  17. unsigned int getMaxOffset(domInputLocalOffset_Array& inputArray)
  18. {
  19. unsigned int maxOffset = 0;
  20. for (unsigned int i = 0; i < (int)inputArray.getCount(); ++i)
  21. {
  22. if ( inputArray[i]->getOffset() > maxOffset )
  23. {
  24. maxOffset = (unsigned int)inputArray[i]->getOffset();
  25. }
  26. }
  27. return maxOffset;
  28. }
  29. void DAESceneEncoder::optimizeCOLLADA(const EncoderArguments& arguments, domCOLLADA* dom)
  30. {
  31. DAEOptimizer optimizer(dom);
  32. const std::vector<std::string>& groupAnimatioNodeIds = arguments.getGroupAnimationNodeId();
  33. const std::vector<std::string>& groupAnimatioIds = arguments.getGroupAnimationAnimationId();
  34. assert(groupAnimatioNodeIds.size() == groupAnimatioIds.size());
  35. size_t size = groupAnimatioNodeIds.size();
  36. if (size > 0)
  37. {
  38. begin();
  39. for (size_t i = 0; i < size; ++i)
  40. {
  41. optimizer.combineAnimations(groupAnimatioNodeIds[i], groupAnimatioIds[i]);
  42. }
  43. end("groupAnimation");
  44. }
  45. if (arguments.DAEOutputEnabled())
  46. {
  47. if (!_collada->writeTo(arguments.getFilePath(), arguments.getDAEOutputPath()))
  48. {
  49. fprintf(stderr,"Error: COLLADA failed to write the dom for file:%s\n", arguments.getDAEOutputPath().c_str());
  50. }
  51. }
  52. }
  53. void DAESceneEncoder::triangulate(DAE* dae)
  54. {
  55. daeDatabase* dataBase = dae->getDatabase();
  56. int geometryCount = (int)(dataBase->getElementCount(0, "geometry"));
  57. for (int i = 0; i < geometryCount; ++i)
  58. {
  59. // Find the next geometry element.
  60. domGeometry* domGeometry;
  61. dataBase->getElement((daeElement**)&domGeometry, i, 0, "geometry");
  62. // Get the mesh out of the geometry.
  63. const domMeshRef domMesh = domGeometry->getMesh();
  64. if (!domMesh)
  65. {
  66. continue;
  67. }
  68. // Loop over all the polygons elements.
  69. int polygonsCount = (int)(domMesh->getPolygons_array().getCount());
  70. for (int j = 0; j < polygonsCount; ++j)
  71. {
  72. // Get the polygons out of the mesh.
  73. domPolygons* domPolygons = domMesh->getPolygons_array()[j];
  74. // Create the triangles from the polygons
  75. createTrianglesFromPolygons(domMesh, domPolygons);
  76. }
  77. while (domMesh->getPolygons_array().getCount() > 0)
  78. {
  79. domPolygons* domPolygons = domMesh->getPolygons_array().get(0);
  80. // Remove the polygons from the mesh.
  81. domMesh->removeChildElement(domPolygons);
  82. }
  83. // Loop over all the polylist elements.
  84. int polylistCount = (int)(domMesh->getPolylist_array().getCount());
  85. for (int j = 0; j < polylistCount; ++j)
  86. {
  87. // Get the polylist out of the mesh.
  88. domPolylist* domPolylist = domMesh->getPolylist_array()[j];
  89. // Create the triangles from the polygon list
  90. createTrianglesFromPolylist(domMesh, domPolylist);
  91. }
  92. while (domMesh->getPolylist_array().getCount() > 0)
  93. {
  94. domPolylist* domPolylist = domMesh->getPolylist_array().get(0);
  95. // Remove the polylist from the mesh.
  96. domMesh->removeChildElement(domPolylist);
  97. }
  98. }
  99. }
  100. void DAESceneEncoder::createTrianglesFromPolygons(domMesh* domMesh, domPolygons* domPolygons)
  101. {
  102. // Create a new <triangles> inside the mesh that has the same material as the <polygons>.
  103. domTriangles* triangles = (domTriangles*)domMesh->createAndPlace("triangles");
  104. triangles->setCount(0);
  105. triangles->setMaterial(domPolygons->getMaterial());
  106. domP* domTrianglesP = (domP*)triangles->createAndPlace("p");
  107. // Give the new <triangles> the same <_dae> and <parameters> as the old <polygons>.
  108. for (unsigned int i = 0; i < domPolygons->getInput_array().getCount(); ++i)
  109. {
  110. triangles->placeElement(domPolygons->getInput_array()[i]->clone());
  111. }
  112. // Get the number of inputs and primitives for the polygons array.
  113. unsigned int inputCount = getMaxOffset(domPolygons->getInput_array()) + 1;
  114. unsigned int primitiveCount = domPolygons->getP_array().getCount();
  115. // Triangulate all the primitives, this generates all the triangles in a single <p> element.
  116. for (unsigned int j = 0; j < primitiveCount; ++j)
  117. {
  118. // Check the polygons for consistancy (some exported files have had the wrong number of indices).
  119. domP* domCurrentP = domPolygons->getP_array()[j];
  120. int elementCount = (int)(domCurrentP->getValue().getCount());
  121. if ( (elementCount % inputCount) != 0 )
  122. {
  123. // Skip this case.
  124. }
  125. else
  126. {
  127. unsigned int triangleCount = (elementCount / inputCount) - 2;
  128. // Write out the primitives as triangles, just fan using the first element as the base.
  129. unsigned int index = inputCount;
  130. for (unsigned int k = 0; k < triangleCount; ++k)
  131. {
  132. // First vertex.
  133. for (unsigned int l = 0; l < inputCount; ++l)
  134. {
  135. domTrianglesP->getValue().append(domCurrentP->getValue()[l]);
  136. }
  137. // Second vertex.
  138. for (unsigned int l = 0; l < inputCount; ++l)
  139. {
  140. domTrianglesP->getValue().append(domCurrentP->getValue()[index + l]);
  141. }
  142. // Third vertex.
  143. index += inputCount;
  144. for (unsigned int l = 0; l < inputCount; ++l)
  145. {
  146. domTrianglesP->getValue().append(domCurrentP->getValue()[index + l]);
  147. }
  148. triangles->setCount(triangles->getCount() + 1);
  149. }
  150. }
  151. }
  152. }
  153. void DAESceneEncoder::createTrianglesFromPolylist(domMesh* domMesh, domPolylist* domPolylist)
  154. {
  155. // Create a new <triangles> inside the mesh that has the same material as the <polylist>.
  156. domTriangles* triangles = (domTriangles*)domMesh->createAndPlace("triangles");
  157. triangles->setMaterial(domPolylist->getMaterial());
  158. domP* domTrianglesP = (domP*)triangles->createAndPlace("p");
  159. // Give the new <triangles> the same <_dae> and <parameters> as the old <polylist>.
  160. for (int i = 0; i < (int)(domPolylist->getInput_array().getCount()); ++i)
  161. {
  162. triangles->placeElement(domPolylist->getInput_array()[i]->clone());
  163. }
  164. // Get the number of inputs and primitives for the polygons array.
  165. unsigned int inputCount = getMaxOffset(domPolylist->getInput_array()) + 1;
  166. unsigned int primitiveCount = domPolylist->getVcount()->getValue().getCount();
  167. unsigned int offset = 0;
  168. unsigned int trianglesProcessed = 0;
  169. // Triangulate all the primitives, this generates all the triangles in a single <p> element.
  170. for (unsigned int j = 0; j < primitiveCount; ++j)
  171. {
  172. unsigned int triangleCount = (unsigned int)domPolylist->getVcount()->getValue()[j] - 2;
  173. // Write out the primitives as triangles, just fan using the first element as the base.
  174. int index = inputCount;
  175. for (unsigned int k = 0; k < triangleCount; ++k)
  176. {
  177. // First vertex.
  178. for (unsigned int l = 0; l < inputCount; ++l)
  179. {
  180. domTrianglesP->getValue().append(domPolylist->getP()->getValue()[offset + l]);
  181. }
  182. // Second vertex.
  183. for (unsigned int l = 0; l < inputCount; ++l)
  184. {
  185. domTrianglesP->getValue().append(domPolylist->getP()->getValue()[offset + index + l]);
  186. }
  187. // Third vertex.
  188. index += inputCount;
  189. for (unsigned int l = 0; l < inputCount; ++l)
  190. {
  191. domTrianglesP->getValue().append(domPolylist->getP()->getValue()[offset + index + l]);
  192. }
  193. trianglesProcessed++;
  194. }
  195. offset += (unsigned int)domPolylist->getVcount()->getValue()[j] * inputCount;
  196. }
  197. triangles->setCount(trianglesProcessed);
  198. }
  199. void DAESceneEncoder::write(const std::string& filepath, const EncoderArguments& arguments)
  200. {
  201. _begin = clock();
  202. const char* nodeId = arguments.getNodeId();
  203. bool text = arguments.textOutputEnabled();
  204. std::string filenameOnly = getFilenameFromFilePath(filepath);
  205. std::string dstPath = filepath.substr(0, filepath.find_last_of('/'));
  206. // Load the collada document
  207. _collada = new DAE();
  208. begin();
  209. _dom = _collada->open(filepath);
  210. end("Open file");
  211. if (!_dom)
  212. {
  213. fprintf(stderr,"Error: COLLADA failed to open file:%s\n", filepath.c_str());
  214. if (_collada)
  215. {
  216. delete _collada;
  217. _collada = NULL;
  218. }
  219. return;
  220. }
  221. // Run collada conditioners
  222. begin();
  223. triangulate(_collada);
  224. end("triangulate");
  225. // Optimize the dom before encoding
  226. optimizeCOLLADA(arguments, _dom);
  227. // Find the <visual_scene> element within the <scene>
  228. const domCOLLADA::domSceneRef& domScene = _dom->getScene();
  229. daeElement* scene = NULL;
  230. if (domScene && domScene->getInstance_visual_scene())
  231. {
  232. scene = domScene->getInstance_visual_scene()->getUrl().getElement();
  233. if (scene->getElementType() != COLLADA_TYPE::VISUAL_SCENE)
  234. {
  235. // This occured once where Maya exported a Node and Scene element with the same ID.
  236. fprintf(stderr,"Error: instance_visual_scene does not reference visual_scene for file:%s\n", filepath.c_str());
  237. return;
  238. }
  239. if (scene)
  240. {
  241. if (nodeId == NULL)
  242. {
  243. // If the -i <node_id> parameter was not passed then write out the entire scene.
  244. begin();
  245. loadScene((domVisual_scene*)scene);
  246. end("load scene");
  247. }
  248. else
  249. {
  250. // Resolve/Search for the node the user specified with the -i <node_id> parameter.
  251. daeSIDResolver resolver(scene, nodeId);
  252. domNode* nodeElement = daeSafeCast<domNode>(resolver.getElement());
  253. if (nodeElement)
  254. {
  255. Node* node = loadNode(nodeElement, NULL);
  256. if (node)
  257. {
  258. _gamePlayFile.addScenelessNode(node);
  259. }
  260. else
  261. {
  262. fprintf(stderr,"COLLADA File loaded to the dom, but failed to load node %s.\n", nodeId);
  263. }
  264. }
  265. else
  266. {
  267. fprintf(stderr,"COLLADA File loaded to the dom, but node was not found with node ID %s.\n", nodeId);
  268. }
  269. }
  270. }
  271. else
  272. {
  273. fprintf(stderr,"COLLADA File loaded to the dom, but query for the dom assets failed.\n");
  274. }
  275. }
  276. else
  277. {
  278. fprintf(stderr, "COLLADA File loaded to the dom, but missing <visual_scene>.\n");
  279. }
  280. // The animations should be loaded last
  281. begin();
  282. loadAnimations(_dom);
  283. end("loadAnimations");
  284. std::string dstFilename = dstPath;
  285. dstFilename.append(1, '/');
  286. dstFilename.append(getFilenameNoExt(filenameOnly));
  287. _gamePlayFile.adjust();
  288. if (text)
  289. {
  290. std::string outFile = dstFilename + ".xml";
  291. fprintf(stderr, "Saving debug file: %s\n", outFile.c_str());
  292. _gamePlayFile.saveText(outFile);
  293. }
  294. else
  295. {
  296. std::string outFile = dstFilename + ".gpb";
  297. fprintf(stderr, "Saving binary file: %s\n", outFile.c_str());
  298. begin();
  299. _gamePlayFile.saveBinary(outFile);
  300. end("save binary");
  301. }
  302. // Cleanup
  303. if (file)
  304. {
  305. fclose(file);
  306. }
  307. if (_collada)
  308. {
  309. delete _collada;
  310. _collada = NULL;
  311. }
  312. }
  313. void DAESceneEncoder::loadAnimations(const domCOLLADA* dom)
  314. {
  315. // Call loadAnimation on all <animation> elements in all <library_animations>
  316. const domLibrary_animations_Array& animationLibrarys = dom->getLibrary_animations_array();
  317. size_t animationLibrarysCount = animationLibrarys.getCount();
  318. for (size_t i = 0; i < animationLibrarysCount; ++i)
  319. {
  320. const domLibrary_animationsRef& libraryAnimation = animationLibrarys.get(i);
  321. const domAnimation_Array& animationArray = libraryAnimation->getAnimation_array();
  322. size_t animationCount = animationArray.getCount();
  323. for (size_t j = 0; j < animationCount; ++j)
  324. {
  325. const domAnimationRef& animationRef = animationArray.get(j);
  326. loadAnimation(animationRef);
  327. }
  328. }
  329. }
  330. void DAESceneEncoder::loadAnimation(const domAnimationRef animationRef)
  331. {
  332. // <channel> points to one <sampler>
  333. // <sampler> points to multiple <input> elements
  334. Animation* animation = new Animation();
  335. const char* str = animationRef->getId();
  336. if (str)
  337. {
  338. animation->setId(str);
  339. }
  340. // <channel>
  341. const domChannel_Array& channelArray = animationRef->getChannel_array();
  342. size_t channelArrayCount = channelArray.getCount();
  343. for (size_t i = 0; i < channelArrayCount; ++i)
  344. {
  345. AnimationChannel* animationChannel = new AnimationChannel();
  346. const domChannelRef& channelRef = channelArray.get(i);
  347. // <sampler>
  348. const domSamplerRef sampler = getSampler(channelRef);
  349. assert(sampler);
  350. // <input>
  351. const domInputLocal_Array& inputArray = sampler->getInput_array();
  352. size_t inputArrayCount = inputArray.getCount();
  353. for (size_t j = 0; j < inputArrayCount; ++j)
  354. {
  355. const domInputLocalRef& inputLocal = inputArray.get(j);
  356. // <source>
  357. const domSourceRef source = getSource(inputLocal, animationRef);
  358. std::string semantic = inputLocal->getSemantic();
  359. if (equals(semantic, "INTERPOLATION"))
  360. {
  361. // Interpolation source is a list of strings
  362. loadInterpolation(source, animationChannel);
  363. }
  364. else
  365. {
  366. // The other sources are lists of floats.
  367. std::vector<float> floats;
  368. copyFloats(source->getFloat_array(), &floats);
  369. if (equals(semantic, "INPUT"))
  370. {
  371. // TODO: Ensure param name is TIME?
  372. for (std::vector<float>::iterator k = floats.begin(); k != floats.end(); ++k)
  373. {
  374. // Convert seconds to milliseconds
  375. *k = *k * 1000.0f;
  376. }
  377. animationChannel->setKeyTimes(floats);
  378. }
  379. else if (equals(semantic, "OUTPUT"))
  380. {
  381. animationChannel->setKeyValues(floats);
  382. }
  383. else if (equals(semantic, "IN_TANGENT"))
  384. {
  385. animationChannel->setTangentsIn(floats);
  386. }
  387. else if (equals(semantic, "OUT_TANGENT"))
  388. {
  389. animationChannel->setTangentsOut(floats);
  390. }
  391. }
  392. }
  393. // get target attribute enum value
  394. if (loadTarget(channelRef, animationChannel))
  395. {
  396. animation->add(animationChannel);
  397. }
  398. }
  399. if (animation->getAnimationChannelCount() > 0)
  400. {
  401. _gamePlayFile.addAnimation(animation);
  402. }
  403. else
  404. {
  405. delete animation;
  406. }
  407. }
  408. void DAESceneEncoder::loadInterpolation(const domSourceRef source, AnimationChannel* animationChannel)
  409. {
  410. // COLLADA stores the interpolations as a list of strings while GBP uses unsigned int
  411. std::vector<unsigned int> values;
  412. const domName_arrayRef nameArray = getSourceNameArray(source);
  413. assert(nameArray);
  414. const domListOfNames& names = nameArray->getValue();
  415. size_t count = (size_t)names.getCount();
  416. values.resize(count);
  417. if (count > 0)
  418. {
  419. for (size_t i = 0; i < count; ++i)
  420. {
  421. values[i] = AnimationChannel::getInterpolationType(names.get(i));
  422. }
  423. // If all of the interpolation types are the same then only store the interpolation once
  424. // instead of storing the same type for each key frame.
  425. unsigned int firstType = values[0];
  426. bool allEqual = true;
  427. for (size_t i = 1; i < count; ++i)
  428. {
  429. if (firstType != values[i])
  430. {
  431. allEqual = false;
  432. break;
  433. }
  434. }
  435. if (allEqual)
  436. {
  437. values.resize(1);
  438. }
  439. }
  440. animationChannel->setInterpolations(values);
  441. }
  442. bool DAESceneEncoder::loadTarget(const domChannelRef& channelRef, AnimationChannel* animationChannel)
  443. {
  444. // GamePlay requires that animations are baked. Use "Bake Transforms" in your 3D modeling tool.
  445. // If the target of an animation is not a matrix then an error will be printed.
  446. const static char* TRANSFORM_WARNING_FORMAT = "Warning: Node \"%s\":\n %s %s\n";
  447. const static char* TRANSFORM_MESSAGE = "transform found but not supported.\n Use \"Bake Transforms\" option when exporting.";
  448. unsigned int targetProperty = 0;
  449. DAEChannelTarget channelTarget(channelRef);
  450. const char* targetId = channelTarget.getTargetId().c_str();
  451. // TODO: Do we want to support more than one? If yes then this needs to be fixed.
  452. for (size_t i = 0; i < channelTarget.getTargetAttributeCount(); ++i)
  453. {
  454. std::string prop;
  455. channelTarget.getPropertyName(i, &prop);
  456. daeElement* attributeElement = channelTarget.getTargetAttribute(i);
  457. if (attributeElement)
  458. {
  459. daeInt type = attributeElement->typeID();
  460. if (type == domRotate::ID())
  461. {
  462. printf(TRANSFORM_WARNING_FORMAT, targetId, "Rotate", TRANSFORM_MESSAGE);
  463. return false;
  464. /*
  465. // <rotate>
  466. const domRotate* rotate = daeSafeCast<domRotate>(attributeElement);
  467. if (prop.size() > 0)
  468. {
  469. if (equalsIgnoreCase(prop, "ANGLE"))
  470. {
  471. targetProperty = Transform::ANIMATE_ROTATE;
  472. // get the rotation axis
  473. const domFloat4& f = rotate->getValue();
  474. float x = (float)f.get(0);
  475. float y = (float)f.get(1);
  476. float z = (float)f.get(2);
  477. // Get the angle values that were already read
  478. const std::vector<float>& keyValues = animationChannel->getKeyValues();
  479. size_t size = keyValues.size();
  480. assert(size > 0);
  481. // COLLADA only targeted a single prop but GBP requires all 4 rotate values.
  482. // Convert (ANGLE ANGLE ANGLE) to (X Y Z ANGLE X Y Z ANGLE X Y Z ANGLE)
  483. std::vector<float> floats(size * 4);
  484. // Duplicate rotation axis. We will replace only the angle that COLLADA is targeting.
  485. for (size_t j = 0; j < size; ++j)
  486. {
  487. size_t k = j * 4;
  488. floats[k+0] = x;
  489. floats[k+1] = y;
  490. floats[k+2] = z;
  491. floats[k+3] = keyValues[j]; // angle
  492. }
  493. animationChannel->setKeyValues(floats);
  494. }
  495. }
  496. */
  497. }
  498. else if (type == domScale::ID())
  499. {
  500. printf(TRANSFORM_WARNING_FORMAT, targetId, "Scale", TRANSFORM_MESSAGE);
  501. return false;
  502. /*
  503. // <scale>
  504. //const domScale* scale = daeSafeCast<domScale>(attributeElement);
  505. if (equalsIgnoreCase(prop, "X"))
  506. {
  507. targetProperty = Transform::ANIMATE_SCALE_X;
  508. }
  509. else if (equalsIgnoreCase(prop, "Y"))
  510. {
  511. targetProperty = Transform::ANIMATE_SCALE_Y;
  512. }
  513. else if (equalsIgnoreCase(prop, "Z"))
  514. {
  515. targetProperty = Transform::ANIMATE_SCALE_Z;
  516. }
  517. else
  518. {
  519. targetProperty = Transform::ANIMATE_SCALE;
  520. }
  521. */
  522. }
  523. else if (type == domTranslate::ID())
  524. {
  525. printf(TRANSFORM_WARNING_FORMAT, targetId, "Translate", TRANSFORM_MESSAGE);
  526. return false;
  527. /*
  528. // <translate>
  529. //const domTranslate* translate = daeSafeCast<domTranslate>(attributeElement);
  530. if (equalsIgnoreCase(prop, "X"))
  531. {
  532. targetProperty = Transform::ANIMATE_TRANSLATE_X;
  533. }
  534. else if (equalsIgnoreCase(prop, "Y"))
  535. {
  536. targetProperty = Transform::ANIMATE_TRANSLATE_Y;
  537. }
  538. else if (equalsIgnoreCase(prop, "Z"))
  539. {
  540. targetProperty = Transform::ANIMATE_TRANSLATE_Z;
  541. }
  542. else
  543. {
  544. targetProperty = Transform::ANIMATE_TRANSLATE;
  545. }
  546. */
  547. }
  548. else if (type == domMatrix::ID())
  549. {
  550. // If the animation is targetting a matrix then convert it into
  551. // a scale, rotate, translate animation by decomposing the matrix.
  552. targetProperty = Transform::ANIMATE_SCALE_ROTATE_TRANSLATE;
  553. const std::vector<float>& keyValues = animationChannel->getKeyValues();
  554. assert(keyValues.size() % 16 == 0);
  555. // The matrix was 16 floats and the new values will be 10 floats
  556. size_t newSize = keyValues.size() / 16 * 10;
  557. std::vector<float> floats(newSize);
  558. size_t matrixCount = keyValues.size() / 16;
  559. for (size_t i = 0; i < matrixCount; ++i)
  560. {
  561. size_t j = i * 16;
  562. // COLLADA used row-major but the Matrix class uses column-major
  563. Matrix matrix(
  564. keyValues[j+0], keyValues[j+4], keyValues[j+8], keyValues[j+12],
  565. keyValues[j+1], keyValues[j+5], keyValues[j+9], keyValues[j+13],
  566. keyValues[j+2], keyValues[j+6], keyValues[j+10], keyValues[j+14],
  567. keyValues[j+3], keyValues[j+7], keyValues[j+11], keyValues[j+15]);
  568. Vector3 scale;
  569. Quaternion rotation;
  570. Vector3 translation;
  571. matrix.decompose(&scale, &rotation, &translation);
  572. rotation.normalize();
  573. size_t k = i * 10;
  574. floats[k+0] = scale.x;
  575. floats[k+1] = scale.y;
  576. floats[k+2] = scale.z;
  577. floats[k+3] = rotation.x;
  578. floats[k+4] = rotation.y;
  579. floats[k+5] = rotation.z;
  580. floats[k+6] = rotation.w;
  581. floats[k+7] = translation.x;
  582. floats[k+8] = translation.y;
  583. floats[k+9] = translation.z;
  584. }
  585. animationChannel->setKeyValues(floats);
  586. }
  587. }
  588. }
  589. animationChannel->setTargetAttribute(targetProperty);
  590. animationChannel->setTargetId(channelTarget.getTargetId());
  591. //animationChannel->removeDuplicates();
  592. return true;
  593. }
  594. void DAESceneEncoder::begin()
  595. {
  596. #ifdef ENCODER_PRINT_TIME
  597. _begin = clock();
  598. #endif
  599. }
  600. void DAESceneEncoder::end(const char* str)
  601. {
  602. #ifdef ENCODER_PRINT_TIME
  603. clock_t time = clock() - _begin;
  604. fprintf(stderr,"%5d %s\n", time, str);
  605. #endif
  606. }
  607. void DAESceneEncoder::copyFloats(const domFloat_array* source, std::vector<float>* target)
  608. {
  609. std::vector<float>& t = *target;
  610. size_t count = (size_t)source->getCount();
  611. t.resize(count);
  612. const domListOfFloats& listOfFloats = source->getValue();
  613. for (size_t i = 0; i < count; ++i)
  614. {
  615. t[i] = (float)listOfFloats.get(i);
  616. }
  617. }
  618. void DAESceneEncoder::loadScene(const domVisual_scene* visualScene)
  619. {
  620. Scene* scene = new Scene();
  621. const domNode_Array& nodes = visualScene->getNode_array();
  622. scene->setId(visualScene->getId());
  623. size_t childCount = nodes.getCount();
  624. for (size_t i = 0; i < childCount; ++i)
  625. {
  626. scene->add(loadNode(nodes[i], NULL));
  627. }
  628. Node* activeCameraNode = findSceneActiveCameraNode(visualScene, scene);
  629. if (activeCameraNode)
  630. {
  631. scene->setActiveCameraNode(activeCameraNode);
  632. }
  633. _gamePlayFile.addScene(scene);
  634. }
  635. Node* DAESceneEncoder::findSceneActiveCameraNode(const domVisual_scene* visualScene, Scene* scene)
  636. {
  637. // Loops through each evaluate_scene's render until an active camera node is found.
  638. // Returns the first one found.
  639. // Find the active camera
  640. const domVisual_scene::domEvaluate_scene_Array& evaluateScenes = visualScene->getEvaluate_scene_array();
  641. size_t evaluateSceneCount = evaluateScenes.getCount();
  642. for (size_t i = 0; i < evaluateSceneCount; ++i)
  643. {
  644. const domVisual_scene::domEvaluate_scene::domRender_Array& renders = evaluateScenes[i]->getRender_array();
  645. size_t renderCount = renders.getCount();
  646. for (size_t j = 0; j < renderCount; ++j)
  647. {
  648. xsAnyURI cameraNodeURI = renders[i]->getCamera_node();
  649. domNode* nodeRef = daeSafeCast<domNode>(cameraNodeURI.getElement());
  650. if (nodeRef)
  651. {
  652. std::string id = nodeRef->getId();
  653. Node* node = _gamePlayFile.getNode(id.c_str());
  654. if (node)
  655. {
  656. return node;
  657. }
  658. }
  659. }
  660. }
  661. // Find the first node in the scene that contains a camera.
  662. return scene->getFirstCameraNode();
  663. }
  664. Node* DAESceneEncoder::loadNode(domNode* n, Node* parent)
  665. {
  666. Node* node = NULL;
  667. // Check if this node has already been loaded
  668. const char* id = n->getID();
  669. if (id && strlen(id) > 0)
  670. {
  671. node = _gamePlayFile.getNode(n->getID());
  672. if (node)
  673. {
  674. return node;
  675. }
  676. }
  677. // Load the node
  678. node = new Node();
  679. if (parent)
  680. {
  681. parent->addChild(node);
  682. }
  683. if (n->getType() == NODETYPE_JOINT)
  684. {
  685. node->setIsJoint(true);
  686. }
  687. // Set node id
  688. node->setId(n->getId());
  689. // If this node has an id then add it to the ref table
  690. _gamePlayFile.addNode(node);
  691. transformNode(n, node);
  692. loadControllerInstance(n, node);
  693. loadCameraInstance(n, node);
  694. loadLightInstance(n, node);
  695. loadGeometryInstance(n, node);
  696. // Load child nodes
  697. const domNode_Array& childNodes = n->getNode_array();
  698. size_t childCount = childNodes.getCount();
  699. for (size_t i = 0; i < childCount; ++i)
  700. {
  701. loadNode(childNodes.get(i), node);
  702. }
  703. return node;
  704. }
  705. void DAESceneEncoder::transformNode(domNode* domNode, Node* node)
  706. {
  707. // Apply the transform.
  708. // Note that we only honor the first matrix transform specified for the DOM node.
  709. const domMatrix_Array& matrixArray = domNode->getMatrix_array();
  710. if (matrixArray.getCount() > 0)
  711. {
  712. const domMatrixRef& matrix = matrixArray.get(0);
  713. if (!matrix)
  714. {
  715. return;
  716. }
  717. const domFloat4x4& tx = matrix->getValue();
  718. float transform[] = {(float)tx.get(0), (float)tx.get(4), (float)tx.get(8), (float)tx.get(12),
  719. (float)tx.get(1), (float)tx.get(5), (float)tx.get(9), (float)tx.get(13),
  720. (float)tx.get(2), (float)tx.get(6), (float)tx.get(10), (float)tx.get(14),
  721. (float)tx.get(3), (float)tx.get(7), (float)tx.get(11), (float)tx.get(15)};
  722. node->setTransformMatrix(transform);
  723. }
  724. else
  725. {
  726. Matrix transform;
  727. calcTransform(domNode, transform);
  728. node->setTransformMatrix(transform.m);
  729. }
  730. // TODO: Handle transforming by other types (SRT, etc) (see "Node" child elements spec)
  731. /*Vector3 scale;
  732. Quaternion rotation;
  733. Vector3 translation;
  734. localTransform.Decompose(&scale, &rotation, &translation);
  735. node->SetScale(scale);
  736. node->SetRotation(rotation);
  737. node->SetTranslation(translation);*/
  738. }
  739. void DAESceneEncoder::calcTransform(domNode* domNode, Matrix& dstTransform)
  740. {
  741. daeTArray<daeSmartRef<daeElement> > children;
  742. domNode->getChildren(children);
  743. size_t childCount = children.getCount();
  744. for (size_t i = 0; i < childCount; ++i)
  745. {
  746. daeElementRef childElement = children[i];
  747. switch (childElement->getElementType())
  748. {
  749. case COLLADA_TYPE::TRANSLATE:
  750. {
  751. domTranslateRef translateNode = daeSafeCast<domTranslate>(childElement);
  752. float x = (float)translateNode->getValue().get(0);
  753. float y = (float)translateNode->getValue().get(1);
  754. float z = (float)translateNode->getValue().get(2);
  755. dstTransform.translate(x, y, z);
  756. break;
  757. }
  758. case COLLADA_TYPE::ROTATE:
  759. {
  760. domRotateRef rotateNode = daeSafeCast<domRotate>(childElement);
  761. float x = (float)rotateNode->getValue().get(0);
  762. float y = (float)rotateNode->getValue().get(1);
  763. float z = (float)rotateNode->getValue().get(2);
  764. float angle = MATH_DEG_TO_RAD((float)rotateNode->getValue().get(3)); // COLLADA uses degrees, gameplay uses radians
  765. if (x == 1.0f && y == 0.0f && z == 0.0f)
  766. {
  767. dstTransform.rotateX(angle);
  768. }
  769. else if (x == 0.0f && y == 1.0f && z == 0.0f)
  770. {
  771. dstTransform.rotateY(angle);
  772. }
  773. else if (x == 0.0f && y == 0.0f && z == 1.0f)
  774. {
  775. dstTransform.rotateZ(angle);
  776. }
  777. else
  778. {
  779. dstTransform.rotate(x, y, z, angle);
  780. }
  781. break;
  782. }
  783. case COLLADA_TYPE::SCALE:
  784. {
  785. domScaleRef scaleNode = daeSafeCast<domScale>(childElement);
  786. float x = (float)scaleNode->getValue().get(0);
  787. float y = (float)scaleNode->getValue().get(1);
  788. float z = (float)scaleNode->getValue().get(2);
  789. dstTransform.scale(x, y, z);
  790. break;
  791. }
  792. case COLLADA_TYPE::SKEW:
  793. warning("Skew transform found but not supported.");
  794. break;
  795. case COLLADA_TYPE::LOOKAT:
  796. warning("Lookat transform found but not supported.");
  797. break;
  798. default:
  799. break;
  800. }
  801. }
  802. }
  803. void DAESceneEncoder::loadCameraInstance(const domNode* n, Node* node)
  804. {
  805. // Does this node have any camera instances?
  806. const domInstance_camera_Array& instanceCameras = n->getInstance_camera_array();
  807. size_t instanceCameraCount = instanceCameras.getCount();
  808. for (size_t i = 0; i < instanceCameraCount; ++i)
  809. {
  810. // Get the camrea object
  811. const domInstance_camera* cameraInstanceRef = instanceCameras.get(i);
  812. xsAnyURI cameraURI = cameraInstanceRef->getUrl();
  813. domCamera* cameraRef = daeSafeCast<domCamera>(cameraURI.getElement());
  814. if (cameraRef)
  815. {
  816. Camera* camera = loadCamera(cameraRef);
  817. if (camera)
  818. {
  819. node->setCamera(camera);
  820. }
  821. }
  822. else
  823. {
  824. // warning
  825. }
  826. }
  827. }
  828. void DAESceneEncoder::loadLightInstance(const domNode* n, Node* node)
  829. {
  830. // Does this node have any light instances?
  831. const domInstance_light_Array& instanceLights = n->getInstance_light_array();
  832. size_t instanceLightCount = instanceLights.getCount();
  833. for (size_t i = 0; i < instanceLightCount; ++i)
  834. {
  835. // Get the camrea object
  836. const domInstance_light* lightInstanceRef = instanceLights.get(i);
  837. xsAnyURI lightURI = lightInstanceRef->getUrl();
  838. domLight* lightRef = daeSafeCast<domLight>(lightURI.getElement());
  839. if (lightRef)
  840. {
  841. Light* light = loadLight(lightRef);
  842. if (light)
  843. {
  844. node->setLight(light);
  845. }
  846. }
  847. else
  848. {
  849. // warning
  850. }
  851. }
  852. }
  853. void DAESceneEncoder::loadGeometryInstance(const domNode* n, Node* node)
  854. {
  855. // Does this node have any geometry instances?
  856. const domInstance_geometry_Array& instanceGeometries = n->getInstance_geometry_array();
  857. size_t instanceGeometryCount = instanceGeometries.getCount();
  858. for (size_t i = 0; i < instanceGeometryCount; ++i)
  859. {
  860. // Get the geometry object
  861. const domInstance_geometryRef geometryInstanceRef = instanceGeometries.get(i);
  862. xsAnyURI geometryURI = geometryInstanceRef->getUrl();
  863. domGeometry* geometry = daeSafeCast<domGeometry>(geometryURI.getElement());
  864. // Load the model from this geometry
  865. if (geometry)
  866. {
  867. Model* model = loadGeometry(geometry, geometryInstanceRef->getBind_material());
  868. if (model)
  869. {
  870. node->setModel(model);
  871. }
  872. }
  873. else
  874. {
  875. warning(std::string("Failed to resolve geometry url: ") + geometryURI.getURI());
  876. }
  877. }
  878. }
  879. void DAESceneEncoder::loadControllerInstance(const domNode* n, Node* node)
  880. {
  881. // Does this node have any controller instances?
  882. const domInstance_controller_Array& instanceControllers = n->getInstance_controller_array();
  883. size_t instanceControllerCount = instanceControllers.getCount();
  884. for (size_t i = 0; i < instanceControllerCount; ++i)
  885. {
  886. const domInstance_controllerRef instanceControllerRef = instanceControllers.get(i);
  887. xsAnyURI controllerURI = instanceControllerRef->getUrl();
  888. domController* controllerRef = daeSafeCast<domController>(controllerURI.getElement());
  889. if (controllerRef)
  890. {
  891. const domSkin* skinElement = controllerRef->getSkin();
  892. if (skinElement)
  893. {
  894. Model* model = loadSkin(skinElement);
  895. if (model)
  896. {
  897. domInstance_controller::domSkeleton_Array& skeletons = instanceControllerRef->getSkeleton_array();
  898. if (skeletons.getCount() == 0)
  899. {
  900. warning("No skeletons found for instance controller: ");
  901. delete model;
  902. continue;
  903. }
  904. // Load the skeleton for this skin
  905. domInstance_controller::domSkeletonRef skeleton = getSkeleton(instanceControllerRef);
  906. assert(skeleton);
  907. loadSkeleton(skeleton, model->getSkin());
  908. node->setModel(model);
  909. }
  910. }
  911. }
  912. else
  913. {
  914. // warning
  915. }
  916. _jointLookupTable.clear();
  917. _jointInverseBindPoseMatrices.clear();
  918. }
  919. }
  920. Camera* DAESceneEncoder::loadCamera(const domCamera* cameraRef)
  921. {
  922. Camera* camera = new Camera();
  923. camera->setId(cameraRef->getId());
  924. // Optics
  925. const domCamera::domOpticsRef opticsRef = cameraRef->getOptics();
  926. if (opticsRef.cast())
  927. {
  928. const domCamera::domOptics::domTechnique_commonRef techRef = opticsRef->getTechnique_common();
  929. // Orthographics
  930. const domCamera::domOptics::domTechnique_common::domOrthographicRef orthographicRef = techRef->getOrthographic();
  931. if (orthographicRef.cast())
  932. {
  933. camera->setOrthographic();
  934. camera->setAspectRatio((float)orthographicRef->getAspect_ratio()->getValue());
  935. camera->setNearPlane((float)orthographicRef->getZnear()->getValue());
  936. camera->setFarPlane((float)orthographicRef->getZfar()->getValue());
  937. const domTargetableFloatRef xmag = orthographicRef->getXmag();
  938. const domTargetableFloatRef ymag = orthographicRef->getYmag();
  939. // Viewport width
  940. if (xmag.cast())
  941. {
  942. camera->setViewportWidth((float)xmag->getValue());
  943. }
  944. // Viewport height
  945. if (ymag.cast())
  946. {
  947. camera->setViewportHeight((float)ymag->getValue());
  948. }
  949. // TODO: Viewport x and y?
  950. }
  951. // Perspective
  952. const domCamera::domOptics::domTechnique_common::domPerspectiveRef perspectiveRef = techRef->getPerspective();
  953. if (perspectiveRef.cast())
  954. {
  955. camera->setPerspective();
  956. camera->setNearPlane((float)perspectiveRef->getZnear()->getValue());
  957. camera->setFarPlane((float)perspectiveRef->getZfar()->getValue());
  958. float aspectRatio = -1.0f;
  959. if (perspectiveRef->getAspect_ratio().cast())
  960. {
  961. aspectRatio = (float)perspectiveRef->getAspect_ratio()->getValue();
  962. camera->setAspectRatio(aspectRatio);
  963. }
  964. if (perspectiveRef->getYfov().cast())
  965. {
  966. camera->setFieldOfView((float)perspectiveRef->getYfov()->getValue());
  967. }
  968. else if (perspectiveRef->getXfov().cast() && aspectRatio > 0.0f)
  969. {
  970. // The gameplaybinary stores the yfov but collada might have specified
  971. // an xfov and an aspect ratio. So use those to calculate the yfov.
  972. float xfov = (float)perspectiveRef->getXfov()->getValue();
  973. float yfov = xfov / aspectRatio;
  974. camera->setFieldOfView(yfov);
  975. }
  976. }
  977. }
  978. _gamePlayFile.addCamera(camera);
  979. return camera;
  980. }
  981. Light* DAESceneEncoder::loadLight(const domLight* lightRef)
  982. {
  983. Light* light = new Light();
  984. light->setId(lightRef->getId());
  985. const domLight::domTechnique_commonRef techRef = lightRef->getTechnique_common();
  986. // Ambient light
  987. {
  988. const domLight::domTechnique_common::domAmbientRef ambientRef = techRef->getAmbient();
  989. if (ambientRef.cast())
  990. {
  991. light->setAmbientLight();
  992. // color
  993. const domTargetableFloat3Ref float3Ref = ambientRef->getColor();
  994. const domFloat3& color3 = float3Ref->getValue();
  995. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  996. }
  997. }
  998. // Directional light
  999. {
  1000. const domLight::domTechnique_common::domDirectionalRef direcitonalRef = techRef->getDirectional();
  1001. if (direcitonalRef.cast())
  1002. {
  1003. light->setDirectionalLight();
  1004. // color
  1005. const domTargetableFloat3Ref float3Ref = direcitonalRef->getColor();
  1006. const domFloat3& color3 = float3Ref->getValue();
  1007. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1008. }
  1009. }
  1010. // Spot light
  1011. {
  1012. const domLight::domTechnique_common::domSpotRef spotRef = techRef->getSpot();
  1013. if (spotRef.cast())
  1014. {
  1015. light->setSpotLight();
  1016. // color
  1017. const domTargetableFloat3Ref float3Ref = spotRef->getColor();
  1018. const domFloat3& color3 = float3Ref->getValue();
  1019. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1020. const domTargetableFloatRef& constAtt = spotRef->getConstant_attenuation();
  1021. if (constAtt.cast())
  1022. {
  1023. light->setConstantAttenuation((float)constAtt->getValue());
  1024. }
  1025. const domTargetableFloatRef& linearAtt = spotRef->getLinear_attenuation();
  1026. if (linearAtt.cast())
  1027. {
  1028. light->setLinearAttenuation((float)linearAtt->getValue());
  1029. }
  1030. const domTargetableFloatRef& quadAtt = spotRef->getQuadratic_attenuation();
  1031. if (quadAtt.cast())
  1032. {
  1033. light->setQuadraticAttenuation((float)quadAtt->getValue());
  1034. }
  1035. const domTargetableFloatRef& falloffAngle = spotRef->getFalloff_angle();
  1036. if (falloffAngle.cast())
  1037. {
  1038. light->setFalloffAngle((float)falloffAngle->getValue());
  1039. }
  1040. const domTargetableFloatRef& falloffExp = spotRef->getFalloff_exponent();
  1041. if (falloffExp.cast())
  1042. {
  1043. light->setFalloffExponent((float)falloffExp->getValue());
  1044. }
  1045. }
  1046. }
  1047. // Point light
  1048. {
  1049. const domLight::domTechnique_common::domPointRef pointRef = techRef->getPoint();
  1050. if (pointRef.cast())
  1051. {
  1052. light->setPointLight();
  1053. // color
  1054. const domTargetableFloat3Ref float3Ref = pointRef->getColor();
  1055. const domFloat3& color3 = float3Ref->getValue();
  1056. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1057. const domTargetableFloatRef& constAtt = pointRef->getConstant_attenuation();
  1058. if (constAtt.cast())
  1059. {
  1060. light->setConstantAttenuation((float)constAtt->getValue());
  1061. }
  1062. const domTargetableFloatRef& linearAtt = pointRef->getLinear_attenuation();
  1063. if (linearAtt.cast())
  1064. {
  1065. light->setLinearAttenuation((float)linearAtt->getValue());
  1066. }
  1067. const domTargetableFloatRef& quadAtt = pointRef->getQuadratic_attenuation();
  1068. if (quadAtt.cast())
  1069. {
  1070. light->setQuadraticAttenuation((float)quadAtt->getValue());
  1071. }
  1072. }
  1073. }
  1074. _gamePlayFile.addLight(light);
  1075. return light;
  1076. }
  1077. void DAESceneEncoder::loadSkeleton(domInstance_controller::domSkeleton* skeletonElement, MeshSkin* skin)
  1078. {
  1079. xsAnyURI skeletonUri = skeletonElement->getValue();
  1080. daeString skeletonId = skeletonUri.getID();
  1081. daeSIDResolver resolver(skeletonUri.getElement(), skeletonId);
  1082. domNode* rootNode = daeSafeCast<domNode>(resolver.getElement());
  1083. // Get the lookup scene id (sid) and joint index.
  1084. std::string id = std::string(skeletonId);
  1085. // Has the skeleton (root joint) been loaded yet?
  1086. Node* skeleton = (Node*)_gamePlayFile.getFromRefTable(id);
  1087. // The skeleton node is not loaded yet, so let's load it now
  1088. if (skeleton == NULL)
  1089. {
  1090. // Find the top most parent of rootNode that has not yet been loaded
  1091. domNode* topLevelParent = rootNode;
  1092. while (
  1093. topLevelParent->getParent() &&
  1094. topLevelParent->getParent()->getElementType() == COLLADA_TYPE::NODE &&
  1095. _gamePlayFile.getFromRefTable(topLevelParent->getParent()->getID()) == NULL)
  1096. {
  1097. topLevelParent = (domNode*)topLevelParent->getParent();
  1098. }
  1099. // Is the parent of this node loaded yet?
  1100. Node* parentNode = NULL;
  1101. if (topLevelParent->getParent() &&
  1102. topLevelParent->getParent()->getElementType() == COLLADA_TYPE::NODE &&
  1103. _gamePlayFile.getFromRefTable(topLevelParent->getParent()->getID()) != NULL)
  1104. {
  1105. parentNode = (Node*)_gamePlayFile.getFromRefTable(topLevelParent->getParent()->getID());
  1106. }
  1107. // Finally, load the node hierarchy that includes the skeleton
  1108. skeleton = loadNode(topLevelParent, parentNode);
  1109. }
  1110. if (skeleton == NULL)
  1111. {
  1112. // This shouldn't really happen..
  1113. skeleton = new Node();
  1114. skeleton->setId(id);
  1115. _gamePlayFile.addNode(skeleton);
  1116. }
  1117. // Resolve and set joints array for skin
  1118. std::vector<Node*> _joints;
  1119. const std::vector<std::string>& jointNames = skin->getJointNames();
  1120. for (std::vector<std::string>::const_iterator i = jointNames.begin(); i != jointNames.end(); i++)
  1121. {
  1122. Object* obj = _gamePlayFile.getFromRefTable(*i);
  1123. if (obj && obj->getTypeId() == Object::NODE_ID)
  1124. {
  1125. Node* node = static_cast<Node*>(obj);
  1126. _joints.push_back(node);
  1127. }
  1128. }
  1129. skin->setJoints(_joints);
  1130. }
  1131. Model* DAESceneEncoder::loadSkin(const domSkin* skinElement)
  1132. {
  1133. ///////////////////////////// SKIN
  1134. Model* model = new Model();
  1135. MeshSkin* skin = new MeshSkin();
  1136. // Bind Shape Matrix
  1137. const domSkin::domBind_shape_matrix* bindShapeMatrix = skinElement->getBind_shape_matrix();
  1138. if (bindShapeMatrix)
  1139. {
  1140. const domFloat4x4& m = bindShapeMatrix->getValue();
  1141. float transform[] = {(float)m.get(0), (float)m.get(4), (float)m.get(8), (float)m.get(12),
  1142. (float)m.get(1), (float)m.get(5), (float)m.get(9), (float)m.get(13),
  1143. (float)m.get(2), (float)m.get(6), (float)m.get(10), (float)m.get(14),
  1144. (float)m.get(3), (float)m.get(7), (float)m.get(11), (float)m.get(15)};
  1145. skin->setBindShape(transform);
  1146. }
  1147. // Read and set our joints
  1148. domSkin::domJointsRef _joints = skinElement->getJoints();
  1149. domInputLocal_Array& jointInputs = _joints->getInput_array();
  1150. // Process "JOINT" input semantic first (we need to do this to set the joint count)
  1151. unsigned int jointCount = 0;
  1152. for (unsigned int i = 0; i < jointInputs.getCount(); ++i)
  1153. {
  1154. domInputLocalRef input = jointInputs.get(i);
  1155. std::string inputSemantic = std::string(input->getSemantic());
  1156. domURIFragmentType* sourceURI = &input->getSource();
  1157. sourceURI->resolveElement();
  1158. const domSourceRef source = (domSource*)(daeElement*)sourceURI->getElement();
  1159. if (equals(inputSemantic, "JOINT"))
  1160. {
  1161. // Get the joint Ids's
  1162. std::vector<std::string> list;
  1163. getJointNames(source, list);
  1164. // Go through the joint list and conver them from sid to id because the sid information is
  1165. // lost when converting to the gameplay binary format.
  1166. for (std::vector<std::string>::iterator i = list.begin(); i != list.end(); i++)
  1167. {
  1168. daeSIDResolver resolver(source->getDocument()->getDomRoot(), i->c_str());
  1169. daeElement* element = resolver.getElement();
  1170. if (element && element->getElementType() == COLLADA_TYPE::NODE)
  1171. {
  1172. domNodeRef node = daeSafeCast<domNode>(element);
  1173. const char* nodeId = node->getId();
  1174. if (nodeId && !equals(*i, nodeId))
  1175. {
  1176. *i = nodeId;
  1177. }
  1178. }
  1179. }
  1180. // Get the joint count and set the capacities for both the
  1181. jointCount = list.size();
  1182. _jointInverseBindPoseMatrices.reserve(jointCount);
  1183. unsigned int j = 0;
  1184. for (std::vector<std::string>::const_iterator i = list.begin(); i != list.end(); i++)
  1185. {
  1186. _jointLookupTable[*i] = j++;
  1187. }
  1188. skin->setJointNames(list);
  1189. }
  1190. }
  1191. // Make sure we have some joints
  1192. if (jointCount == 0)
  1193. {
  1194. warning("No joints found for skin: ");
  1195. return NULL;
  1196. }
  1197. // Process "INV_BIND_MATRIX" next
  1198. for (unsigned int i = 0; i < jointInputs.getCount(); ++i)
  1199. {
  1200. domInputLocalRef input = jointInputs.get(i);
  1201. std::string inputSemantic = std::string(input->getSemantic());
  1202. domURIFragmentType* sourceURI = &input->getSource();
  1203. sourceURI->resolveElement();
  1204. domSource* source = (domSource*)(daeElement*)sourceURI->getElement();
  1205. if (equals(inputSemantic, "INV_BIND_MATRIX"))
  1206. {
  1207. domListOfFloats& matrixFloats = source->getFloat_array()->getValue();
  1208. //unsigned int matrixFloatsCount = (unsigned int)source->getFloat_array()->getCount();
  1209. unsigned int jointIndex = 0;
  1210. for (unsigned int j = 0; j < jointCount; ++j)
  1211. {
  1212. Matrix matrix((float)matrixFloats.get(jointIndex + 0), (float)matrixFloats.get(jointIndex + 4), (float)matrixFloats.get(jointIndex + 8), (float)matrixFloats.get(jointIndex + 12),
  1213. (float)matrixFloats.get(jointIndex + 1), (float)matrixFloats.get(jointIndex + 5), (float)matrixFloats.get(jointIndex + 9), (float)matrixFloats.get(jointIndex + 13),
  1214. (float)matrixFloats.get(jointIndex + 2), (float)matrixFloats.get(jointIndex + 6), (float)matrixFloats.get(jointIndex + 10), (float)matrixFloats.get(jointIndex + 14),
  1215. (float)matrixFloats.get(jointIndex + 3), (float)matrixFloats.get(jointIndex + 7), (float)matrixFloats.get(jointIndex + 11), (float)matrixFloats.get(jointIndex + 15));
  1216. _jointInverseBindPoseMatrices.push_back(matrix);
  1217. jointIndex += 16;
  1218. }
  1219. }
  1220. }
  1221. skin->setBindPoses(_jointInverseBindPoseMatrices);
  1222. // Get the vertex weights inputs
  1223. domSkin::domVertex_weights* vertexWeights = skinElement->getVertex_weights();
  1224. domInputLocalOffset_Array& vertexWeightsInputs = vertexWeights->getInput_array();
  1225. unsigned int vertexWeightsCount = (unsigned int)vertexWeights->getCount();
  1226. domListOfFloats jointWeights;
  1227. for (unsigned int i = 0; i < jointInputs.getCount(); ++i)
  1228. {
  1229. domInputLocalOffsetRef input = vertexWeightsInputs.get(i);
  1230. std::string inputSemantic = std::string(input->getSemantic());
  1231. domURIFragmentType* sourceURI = &input->getSource();
  1232. sourceURI->resolveElement();
  1233. domSource* source = (domSource*)(daeElement*)sourceURI->getElement();
  1234. if (equals(inputSemantic, "WEIGHT"))
  1235. {
  1236. domFloat_array* weights = source->getFloat_array();
  1237. if (weights)
  1238. {
  1239. jointWeights = weights->getValue();
  1240. }
  1241. }
  1242. }
  1243. // Get the number of joint influences per vertex
  1244. domSkin::domVertex_weights::domVcount* vCountElement = vertexWeights->getVcount();
  1245. domListOfUInts skinVertexInfluenceCounts = vCountElement->getValue();
  1246. // Get the joint/weight pair data.
  1247. domSkin::domVertex_weights::domV* vElement = vertexWeights->getV();
  1248. domListOfInts skinVertexJointWeightPairIndices = vElement->getValue();
  1249. // Get the vertex influence count for any given vertex (up to max of 4)
  1250. unsigned int maxVertexInfluencesCount = SCENE_SKIN_VERTEXINFLUENCES_MAX;
  1251. skin->setVertexInfluenceCount(maxVertexInfluencesCount);
  1252. // Get the vertex blend weights and joint indices and
  1253. // allocate our vertex blend weights and blend indices arrays.
  1254. // These will be used and cleaned up later in LoadMesh
  1255. int skinVertexInfluenceCountTotal = skinVertexInfluenceCounts.getCount();
  1256. int totalVertexInfluencesCount = vertexWeightsCount * maxVertexInfluencesCount;
  1257. _vertexBlendWeights = new float[totalVertexInfluencesCount];
  1258. _vertexBlendIndices = new unsigned int[totalVertexInfluencesCount];
  1259. // Preset the default blend weights to 0.0f (no effect) and blend indices to 0 (uses the first which when multiplied
  1260. // will have no effect anyhow.
  1261. memset(_vertexBlendWeights, 0, totalVertexInfluencesCount * sizeof(float));
  1262. memset(_vertexBlendIndices , 0, totalVertexInfluencesCount * sizeof(unsigned int));
  1263. int vOffset = 0;
  1264. int weightOffset = 0;
  1265. // Go through all the skin vertex influence weights from the indexed data.
  1266. for (int i = 0; i < skinVertexInfluenceCountTotal; ++i)
  1267. {
  1268. // Get the influence count and directly get the vertext blend weights and indices.
  1269. unsigned int vertexInfluenceCount = (unsigned int)skinVertexInfluenceCounts.get(i);
  1270. float vertexInfluencesTotalWeights = 0.0f;
  1271. std::vector<SkinnedVertexWeightPair> vertexInfluences;
  1272. //vertexInfluences.SetCapacity(vertexInfluenceCount);
  1273. // Get the index/weight pairs and some the weight totals while at it.
  1274. for (unsigned int j = 0; j < vertexInfluenceCount; ++j)
  1275. {
  1276. float weight = (float)jointWeights.get((unsigned int)skinVertexJointWeightPairIndices[vOffset + 1]);
  1277. int index = (int)skinVertexJointWeightPairIndices[vOffset];
  1278. // Set invalid index corresponding weights to zero
  1279. if (index < 0 || index > (int)vertexWeightsCount)
  1280. {
  1281. weight = 0.0f;
  1282. index = 0;
  1283. }
  1284. SkinnedVertexWeightPair pair(weight, index);
  1285. vertexInfluences.push_back(pair);
  1286. vertexInfluencesTotalWeights += weight;
  1287. vOffset+=2;
  1288. }
  1289. // Get up the the maximum vertex weight influence count.
  1290. for (unsigned int j = 0; j < maxVertexInfluencesCount; ++j)
  1291. {
  1292. if (j < vertexInfluenceCount)
  1293. {
  1294. SkinnedVertexWeightPair pair = vertexInfluences[j];
  1295. _vertexBlendIndices[weightOffset] = pair.BlendIndex;
  1296. if (vertexInfluencesTotalWeights > 0.0f)
  1297. {
  1298. _vertexBlendWeights[weightOffset] = pair.BlendWeight;
  1299. }
  1300. else
  1301. {
  1302. if (j == 0)
  1303. {
  1304. _vertexBlendWeights[weightOffset] = 1.0f;
  1305. }
  1306. else
  1307. {
  1308. _vertexBlendWeights[weightOffset] = 0.0f;
  1309. }
  1310. }
  1311. }
  1312. weightOffset++;
  1313. }
  1314. }
  1315. model->setSkin(skin);
  1316. ///////////////////////////////////////////////////////////
  1317. // get geometry
  1318. xsAnyURI geometryURI = skinElement->getSource();
  1319. domGeometry* geometry = daeSafeCast<domGeometry>(geometryURI.getElement());
  1320. if (geometry)
  1321. {
  1322. const domMesh* meshElement = geometry->getMesh();
  1323. if (meshElement)
  1324. {
  1325. Mesh* mesh = loadMesh(meshElement, geometry->getId());
  1326. if (mesh)
  1327. {
  1328. model->setMesh(mesh);
  1329. }
  1330. }
  1331. }
  1332. ///////////////////////////////////////////////////////////
  1333. return model;
  1334. }
  1335. Model* DAESceneEncoder::loadGeometry(const domGeometry* geometry, const domBind_materialRef bindMaterial)
  1336. {
  1337. // Does this geometry have a valid mesh?
  1338. // Get the mesh for the geometry (if it has one)
  1339. const domMesh* meshElement = geometry->getMesh();
  1340. if (meshElement == NULL)
  1341. {
  1342. warning(std::string("No mesh found for geometry: ") + geometry->getId());
  1343. return NULL;
  1344. }
  1345. ///////////////////////////// GEOMETRY
  1346. // Load the mesh for this model
  1347. Mesh* mesh = loadMesh(meshElement, geometry->getId());
  1348. if (mesh == NULL)
  1349. {
  1350. return NULL;
  1351. }
  1352. // Mesh instance
  1353. Model* model = new Model();
  1354. model->setMesh(mesh);
  1355. return model;
  1356. }
  1357. Mesh* DAESceneEncoder::loadMesh(const domMesh* meshElement, const std::string& geometryId)
  1358. {
  1359. const domTriangles_Array& trianglesArray = meshElement->getTriangles_array();
  1360. unsigned int trianglesArrayCount = (unsigned int)trianglesArray.getCount();
  1361. // Ensure the data is exported as triangles.
  1362. if (trianglesArrayCount == 0)
  1363. {
  1364. warning(std::string("Geometry mesh has no triangles: ") + geometryId);
  1365. return NULL;
  1366. }
  1367. // Check if this mesh already exists
  1368. Mesh* mesh = _gamePlayFile.getMesh(geometryId.c_str());
  1369. if (mesh)
  1370. {
  1371. return mesh;
  1372. }
  1373. mesh = new Mesh();
  1374. mesh->setId(geometryId.c_str());
  1375. std::vector<DAEPolygonInput*> polygonInputs;
  1376. // Quickly just go through each triangles array and make sure they have the same number of inputs
  1377. // with the same layout.
  1378. // const domSource_Array& sourceArray = meshElement->getSource_array();
  1379. const domInputLocal_Array& vertexArray = meshElement->getVertices()->getInput_array();
  1380. unsigned int inputCount = (unsigned int)-1;
  1381. // Loop through our set of triangle lists (each list of triangles corresponds to a single MeshPart)
  1382. for (unsigned int i = 0; i < trianglesArrayCount; ++i)
  1383. {
  1384. const domTrianglesRef& triangles = trianglesArray.get(i);
  1385. const domInputLocalOffset_Array& inputArray = triangles->getInput_array();
  1386. // If not set then determine the number of input for all the triangles.
  1387. if (inputCount == -1)
  1388. {
  1389. inputCount = (unsigned int)inputArray.getCount();
  1390. int texCoordCount = 0;
  1391. for (unsigned int j = 0; j < inputCount; ++j)
  1392. {
  1393. const domInputLocalOffsetRef& input = inputArray.get(j);
  1394. std::string inputSemantic = input->getSemantic();
  1395. // If its a vertex first do an extra lookup for the inclusive inputs
  1396. if (equals(inputSemantic, "VERTEX"))
  1397. {
  1398. unsigned int vertexArrayCount = (unsigned int)vertexArray.getCount();
  1399. for (unsigned int k = 0; k < vertexArrayCount; ++k)
  1400. {
  1401. const domInputLocalRef& vertexInput = vertexArray.get(k);
  1402. std::string semantic = std::string(vertexInput->getSemantic());
  1403. int type = getVertexUsageType(semantic);
  1404. if (type == -1)
  1405. {
  1406. warning(std::string("Vertex semantic (") + semantic + ") is invalid/unsupported for geometry mesh: " + geometryId);
  1407. }
  1408. DAEPolygonInput* polygonInput = new DAEPolygonInput();
  1409. domURIFragmentType& sourceURI = vertexInput->getSource();
  1410. sourceURI.resolveElement();
  1411. domSource* source = (domSource*)(daeElement*)sourceURI.getElement();
  1412. polygonInput->offset = 0;
  1413. polygonInput->sourceValues = source->getFloat_array()->getValue();
  1414. polygonInput->type = type;
  1415. polygonInputs.push_back(polygonInput);
  1416. }
  1417. }
  1418. else
  1419. {
  1420. std::string semantic = input->getSemantic();
  1421. int type = getVertexUsageType(semantic);
  1422. if (type == -1)
  1423. {
  1424. warning(std::string("Semantic (") + semantic + ") is invalid/unsupported for geometry mesh: " + geometryId);
  1425. break;
  1426. }
  1427. if (type == TEXCOORD0)
  1428. {
  1429. // Some meshes have multiple texture coordinates
  1430. assert(texCoordCount <= 7);
  1431. type += texCoordCount;
  1432. ++texCoordCount;
  1433. }
  1434. DAEPolygonInput* polygonInput = new DAEPolygonInput();
  1435. domURIFragmentType& sourceURI = input->getSource();
  1436. sourceURI.resolveElement();
  1437. domSource* source = (domSource*)(daeElement*)sourceURI.getElement();
  1438. polygonInput->offset = (unsigned int)input->getOffset();
  1439. polygonInput->sourceValues = source->getFloat_array()->getValue();
  1440. polygonInput->type = type;
  1441. // Get the accessor info
  1442. const domSource::domTechnique_commonRef& technique = source->getTechnique_common();
  1443. if (technique.cast())
  1444. {
  1445. const domAccessorRef& accessor = technique->getAccessor();
  1446. polygonInput->accessor = accessor;
  1447. }
  1448. polygonInputs.push_back(polygonInput);
  1449. }
  1450. }
  1451. }
  1452. else
  1453. {
  1454. // If there is a triangle array with a different number of inputs, this is not supported.
  1455. if (inputCount != (unsigned int)inputArray.getCount())
  1456. {
  1457. for (size_t j = 0; j < polygonInputs.size(); ++j)
  1458. {
  1459. delete polygonInputs[j];
  1460. }
  1461. warning(std::string("Triangles do not all have the same number of input sources for geometry mesh: ") + geometryId);
  1462. return NULL;
  1463. }
  1464. else
  1465. {
  1466. // TODO: Check if they are in the same order...
  1467. }
  1468. }
  1469. }
  1470. // Now we have validated that all input in all triangles are the same and in the same input layout.
  1471. // Lets start to read them and build our subsets.
  1472. for (unsigned int i = 0; i < trianglesArrayCount; ++i)
  1473. {
  1474. // Subset to be built.
  1475. MeshPart* subset = new MeshPart();
  1476. // All of the information about the triangles and the sources to access the data from.
  1477. domTriangles* triangles = daeSafeCast<domTriangles>(trianglesArray.get(i));
  1478. // Parse the material for this subset
  1479. //string materialName = triangles->getMaterial() == NULL ? _T("") : triangles->getMaterial();
  1480. //if (materialName.size() > 0)
  1481. /// subset->material = ParseMaterial(bindMaterial, materialName);
  1482. //const domInputLocalOffset_Array& inputArray = triangles->getInput_array();
  1483. const domListOfUInts& polyInts = triangles->getP()->getValue();
  1484. unsigned int polyIntsCount = (unsigned int)polyInts.getCount();
  1485. unsigned int poly = 0;
  1486. unsigned int inputSourceCount = (unsigned int)polygonInputs.size();
  1487. unsigned int maxOffset = 0;
  1488. // Go through the polygon indices for each input source retrieve the values
  1489. // and iterate by its offset.
  1490. Vertex vertex;
  1491. for (unsigned int k = 0; k < inputSourceCount && poly < polyIntsCount;)
  1492. {
  1493. const domListOfFloats& source = polygonInputs[k]->sourceValues;
  1494. unsigned int offset = polygonInputs[k]->offset;
  1495. if (offset > maxOffset)
  1496. {
  1497. maxOffset = offset;
  1498. }
  1499. unsigned int polyIndex = (unsigned int) polyInts.get(poly + offset);
  1500. switch (polygonInputs[k]->type)
  1501. {
  1502. case POSITION:
  1503. vertex = Vertex(); // TODO
  1504. if (_vertexBlendWeights && _vertexBlendIndices)
  1505. {
  1506. vertex.hasWeights = true;
  1507. vertex.blendWeights.x = _vertexBlendWeights[polyIndex * 4];
  1508. vertex.blendWeights.y = _vertexBlendWeights[polyIndex * 4 + 1];
  1509. vertex.blendWeights.z = _vertexBlendWeights[polyIndex * 4 + 2];
  1510. vertex.blendWeights.w = _vertexBlendWeights[polyIndex * 4 + 3];
  1511. vertex.blendIndices.x = (float)_vertexBlendIndices[polyIndex * 4];
  1512. vertex.blendIndices.y = (float)_vertexBlendIndices[polyIndex * 4 + 1];
  1513. vertex.blendIndices.z = (float)_vertexBlendIndices[polyIndex * 4 + 2];
  1514. vertex.blendIndices.w = (float)_vertexBlendIndices[polyIndex * 4 + 3];
  1515. }
  1516. vertex.position.x = (float)source.get(polyIndex * 3);
  1517. vertex.position.y = (float)source.get(polyIndex * 3 + 1);
  1518. vertex.position.z = (float)source.get(polyIndex * 3 + 2);
  1519. break;
  1520. case NORMAL:
  1521. vertex.hasNormal = true;
  1522. vertex.normal.x = (float)source.get(polyIndex * 3);
  1523. vertex.normal.y = (float)source.get(polyIndex * 3 + 1);
  1524. vertex.normal.z = (float)source.get(polyIndex * 3 + 2);
  1525. break;
  1526. // TODO: We must examine the Collada input accessor and read the stride/count to verify this - not ONLY for Color, but we should be doing this for ALL components (i.e. Position, Normal, etc).
  1527. case COLOR:
  1528. {
  1529. domAccessor* accessor = polygonInputs[k]->accessor;
  1530. if (accessor)
  1531. {
  1532. vertex.hasDiffuse = true;
  1533. vertex.diffuse.w = 1.0f;
  1534. unsigned int stride = (unsigned int)polygonInputs[k]->accessor->getStride();
  1535. unsigned int index = polyIndex * stride;
  1536. const domParam_Array& paramArray = accessor->getParam_array();
  1537. const size_t paramArrayCount = paramArray.getCount();
  1538. for (size_t i = 0; i < paramArrayCount; ++i)
  1539. {
  1540. const domParamRef& param = paramArray.get(i);
  1541. const char* name = param->getName();
  1542. if (name)
  1543. {
  1544. switch (name[0])
  1545. {
  1546. case 'r':
  1547. case 'R':
  1548. vertex.diffuse.x = (float)source.get(index + i); // red
  1549. break;
  1550. case 'g':
  1551. case 'G':
  1552. vertex.diffuse.y = (float)source.get(index + i); // green
  1553. break;
  1554. case 'b':
  1555. case 'B':
  1556. vertex.diffuse.z = (float)source.get(index + i); // blue
  1557. break;
  1558. case 'a':
  1559. case 'A':
  1560. vertex.diffuse.w = (float)source.get(index + i); // alpha
  1561. break;
  1562. default:
  1563. break;
  1564. }
  1565. }
  1566. }
  1567. }
  1568. break;
  1569. }
  1570. case TANGENT:
  1571. vertex.hasTangent = true;
  1572. vertex.tangent.x = (float)source.get(polyIndex * 3);
  1573. vertex.tangent.y = (float)source.get(polyIndex * 3 + 1);
  1574. vertex.tangent.z = (float)source.get(polyIndex * 3 + 2);
  1575. break;
  1576. case BINORMAL:
  1577. vertex.hasBinormal = true;
  1578. vertex.binormal.x = (float)source.get(polyIndex * 3);
  1579. vertex.binormal.y = (float)source.get(polyIndex * 3 + 1);
  1580. vertex.binormal.z = (float)source.get(polyIndex * 3 + 2);
  1581. break;
  1582. case TEXCOORD0:
  1583. vertex.hasTexCoord = true;
  1584. if (polygonInputs[k]->accessor)
  1585. {
  1586. // TODO: This assumes (s, t) are first
  1587. unsigned int stride = (unsigned int)polygonInputs[k]->accessor->getStride();
  1588. vertex.texCoord.x = (float)source.get(polyIndex * stride);
  1589. vertex.texCoord.y = (float)source.get(polyIndex * stride + 1);
  1590. }
  1591. else
  1592. {
  1593. vertex.texCoord.x = (float)source.get(polyIndex * 2);
  1594. vertex.texCoord.y = (float)source.get(polyIndex * 2 + 1);
  1595. }
  1596. break;
  1597. case TEXCOORD1:
  1598. // TODO
  1599. break;
  1600. default:
  1601. break;
  1602. }
  1603. // On the last input source attempt to add the vertex or index an existing one.
  1604. if (k == (inputSourceCount - 1))
  1605. {
  1606. // Only add unique vertices, use a hashtable and compare the hash functions of the
  1607. // vertices. If they exist simply lookup the index of the existing ones.
  1608. // otherwise add and new one and index it.
  1609. unsigned int index;
  1610. if (mesh->contains(vertex))
  1611. {
  1612. index = mesh->getVertexIndex(vertex);
  1613. }
  1614. else
  1615. {
  1616. index = mesh->addVertex(vertex);
  1617. }
  1618. subset->addIndex(index);
  1619. poly += (maxOffset+1);
  1620. k = 0;
  1621. }
  1622. else
  1623. {
  1624. k++;
  1625. }
  1626. }
  1627. // Add our new subset for the mesh.
  1628. mesh->addMeshPart(subset);
  1629. }
  1630. bool hasNormals = mesh->vertices[0].hasNormal;
  1631. bool hasDiffuses = mesh->vertices[0].hasDiffuse;
  1632. bool hasTangents = mesh->vertices[0].hasTangent;
  1633. bool hasBinormals = mesh->vertices[0].hasBinormal;
  1634. bool hasTexCoords = mesh->vertices[0].hasTexCoord;
  1635. bool hasWeights = mesh->vertices[0].hasWeights;
  1636. // The order that the vertex elements are add to the list matters.
  1637. // It should be the same order as how the Vertex data is written.
  1638. // Position
  1639. mesh->addVetexAttribute(POSITION, Vertex::POSITION_COUNT);
  1640. // Normals
  1641. if (hasNormals)
  1642. {
  1643. mesh->addVetexAttribute(NORMAL, Vertex::NORMAL_COUNT);
  1644. }
  1645. // Tangents
  1646. if (hasTangents)
  1647. {
  1648. mesh->addVetexAttribute(TANGENT, Vertex::TANGENT_COUNT);
  1649. }
  1650. // Binormals
  1651. if (hasBinormals)
  1652. {
  1653. mesh->addVetexAttribute(BINORMAL, Vertex::BINORMAL_COUNT);
  1654. }
  1655. // Texture Coordinates
  1656. if (hasTexCoords)
  1657. {
  1658. mesh->addVetexAttribute(TEXCOORD0, Vertex::TEXCOORD_COUNT);
  1659. }
  1660. // Diffuse Color
  1661. if (hasDiffuses)
  1662. {
  1663. mesh->addVetexAttribute(COLOR, Vertex::DIFFUSE_COUNT);
  1664. }
  1665. // Skinning BlendWeights BlendIndices
  1666. if (hasWeights)
  1667. {
  1668. mesh->addVetexAttribute(BLENDWEIGHTS, Vertex::BLEND_WEIGHTS_COUNT);
  1669. mesh->addVetexAttribute(BLENDINDICES, Vertex::BLEND_INDICES_COUNT);
  1670. }
  1671. _gamePlayFile.addMesh(mesh);
  1672. return mesh;
  1673. }
  1674. void DAESceneEncoder::warning(const std::string& message)
  1675. {
  1676. printf("Warning: %s\n", message.c_str());
  1677. }
  1678. void DAESceneEncoder::warning(const char* message)
  1679. {
  1680. printf("Warning: %s\n", message);
  1681. }
  1682. int DAESceneEncoder::getVertexUsageType(const std::string& semantic)
  1683. {
  1684. if (semantic.length() > 0)
  1685. {
  1686. switch (semantic[0])
  1687. {
  1688. case 'P':
  1689. if (equals(semantic, "POSITION"))
  1690. {
  1691. return POSITION;
  1692. }
  1693. case 'N':
  1694. if (equals(semantic, "NORMAL"))
  1695. {
  1696. return NORMAL;
  1697. }
  1698. case 'C':
  1699. if (equals(semantic, "COLOR"))
  1700. {
  1701. return COLOR;
  1702. }
  1703. case 'T':
  1704. if (equals(semantic, "TANGENT"))
  1705. {
  1706. return TANGENT;
  1707. }
  1708. else if (equals(semantic, "TEXCOORD"))
  1709. {
  1710. return TEXCOORD0;
  1711. }
  1712. else if (equals(semantic, "TEXTANGENT"))
  1713. {
  1714. // Treat TEXTANGENT as TANGENT
  1715. return TANGENT;
  1716. }
  1717. else if (equals(semantic, "TEXBINORMAL"))
  1718. {
  1719. // Treat TEXBINORMAL as BINORMAL
  1720. return BINORMAL;
  1721. }
  1722. case 'B':
  1723. if (equals(semantic, "BINORMAL"))
  1724. {
  1725. return BINORMAL;
  1726. }
  1727. default:
  1728. return -1;
  1729. }
  1730. }
  1731. return -1;
  1732. }
  1733. DAESceneEncoder::DAEPolygonInput::DAEPolygonInput(void) :
  1734. offset(0),
  1735. type(0),
  1736. accessor(NULL)
  1737. {
  1738. }
  1739. DAESceneEncoder::DAEPolygonInput::~DAEPolygonInput(void)
  1740. {
  1741. }
  1742. }