DAESceneEncoder.cpp 71 KB

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