colladaUtils.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _COLLADA_UTILS_H_
  23. #define _COLLADA_UTILS_H_
  24. #ifdef _MSC_VER
  25. #pragma warning(disable : 4786) // disable warning about long debug symbol names
  26. #pragma warning(disable : 4355) // disable "'this' : used in base member initializer list" warnings
  27. #endif
  28. #ifndef _MMATRIX_H_
  29. #include "math/mMatrix.h"
  30. #endif
  31. #ifndef _MQUAT_H_
  32. #include "math/mQuat.h"
  33. #endif
  34. #ifndef _TVECTOR_H_
  35. #include "core/util/tVector.h"
  36. #endif
  37. #ifndef _TSSHAPE_LOADER_H_
  38. #include "ts/loader/tsShapeLoader.h"
  39. #endif
  40. #ifndef _OPTIMIZEDPOLYLIST_H_
  41. #include "collision/optimizedPolyList.h"
  42. #endif
  43. #ifndef TINYXML_INCLUDED
  44. #include "tinyxml.h"
  45. #endif
  46. #ifndef _CONSOLE_H_
  47. #include "console/console.h"
  48. #endif
  49. #ifndef _TSSHAPEINSTANCE_H_
  50. #include "ts/tsShapeInstance.h"
  51. #endif
  52. #include "platform/tmm_off.h"
  53. #include "dae.h"
  54. #include "dae/daeErrorHandler.h"
  55. #include "dae/domAny.h"
  56. #include "dom/domProfile_COMMON.h"
  57. #include "dom/domMaterial.h"
  58. #include "dom/domGeometry.h"
  59. #include "dom/domMorph.h"
  60. #include "dom/domNode.h"
  61. #include "dom/domCOLLADA.h"
  62. #include "platform/tmm_on.h"
  63. #include "core/strings/findMatch.h"
  64. namespace ColladaUtils
  65. {
  66. struct ImportOptions
  67. {
  68. enum eLodType
  69. {
  70. DetectDTS = 0,
  71. SingleSize,
  72. TrailingNumber,
  73. NumLodTypes
  74. };
  75. domUpAxisType upAxis; // Override for the collada <up_axis> element
  76. F32 unit; // Override for the collada <unit> element
  77. eLodType lodType; // LOD type option
  78. S32 singleDetailSize; // Detail size for all meshes in the model
  79. String matNamePrefix; // Prefix to apply to collada material names
  80. String alwaysImport; // List of node names (with wildcards) to import, even if in the neverImport list
  81. String neverImport; // List of node names (with wildcards) to ignore on loading
  82. String alwaysImportMesh; // List of mesh names (with wildcards) to import, even if in the neverImportMesh list
  83. String neverImportMesh; // List of mesh names (with wildcards) to ignore on loading
  84. String neverImportMat; // List of material names (with wildcards) to ignore on loading
  85. bool ignoreNodeScale; // Ignore <scale> elements in <node>s
  86. bool adjustCenter; // Translate model so origin is at the center
  87. bool adjustFloor; // Translate model so origin is at the bottom
  88. bool forceUpdateMaterials; // Force update of materials.cs
  89. bool useDiffuseNames; // Use diffuse texture as the material name
  90. ImportOptions()
  91. {
  92. reset();
  93. }
  94. void reset()
  95. {
  96. upAxis = UPAXISTYPE_COUNT;
  97. unit = -1.0f;
  98. lodType = TrailingNumber;
  99. singleDetailSize = 2;
  100. matNamePrefix = "";
  101. alwaysImport = "";
  102. neverImport = String(Con::getVariable("$TSShapeConstructor::neverImport"));
  103. alwaysImportMesh = "";
  104. neverImportMesh = String(Con::getVariable("$TSShapeConstructor::neverImportMesh"));
  105. neverImportMat = String(Con::getVariable("$TSShapeConstructor::neverImportMat"));
  106. ignoreNodeScale = false;
  107. adjustCenter = false;
  108. adjustFloor = false;
  109. forceUpdateMaterials = false;
  110. useDiffuseNames = false;
  111. }
  112. };
  113. ImportOptions& getOptions();
  114. struct ExportData
  115. {
  116. struct detailLevel
  117. {
  118. OptimizedPolyList mesh;
  119. S32 size;
  120. Map<int, int> materialRefList;
  121. };
  122. struct meshLODData
  123. {
  124. Vector<detailLevel> meshDetailLevels;
  125. TSShapeInstance* shapeInst;
  126. MatrixF meshTransform;
  127. SceneObject* originatingObject;
  128. Point3F scale;
  129. S32 hasDetailLevel(S32 size)
  130. {
  131. for (U32 i = 0; i < meshDetailLevels.size(); ++i)
  132. {
  133. U32 mdlSize = meshDetailLevels[i].size;
  134. if (mdlSize == size)
  135. return i;
  136. }
  137. return -1;
  138. }
  139. meshLODData() : shapeInst(nullptr), meshTransform(true), originatingObject(nullptr), scale(0)
  140. {}
  141. };
  142. struct colMesh
  143. {
  144. OptimizedPolyList mesh;
  145. String colMeshName;
  146. };
  147. Vector<detailLevel> detailLevels;
  148. Vector<meshLODData> meshData;
  149. Vector<colMesh> colMeshes;
  150. Vector<BaseMatInstance*> materials;
  151. void processData();
  152. S32 hasDetailLevel(U32 dl)
  153. {
  154. for (U32 i = 0; i < detailLevels.size(); i++)
  155. {
  156. if (detailLevels[i].size == dl)
  157. return i;
  158. }
  159. return -1;
  160. }
  161. S32 hasMaterialInstance(BaseMatInstance* matInst)
  162. {
  163. for (U32 i = 0; i < materials.size(); i++)
  164. {
  165. if (materials[i] == matInst)
  166. return i;
  167. }
  168. return -1;
  169. }
  170. S32 numberOfDetailLevels()
  171. {
  172. Vector<S32> detailLevelIdxs;
  173. for (U32 i = 0; i < meshData.size(); ++i)
  174. {
  175. for (U32 d = 0; d < meshData[i].meshDetailLevels.size(); ++d)
  176. {
  177. detailLevelIdxs.push_back_unique(meshData[i].meshDetailLevels[d].size);
  178. }
  179. }
  180. return detailLevelIdxs.size();
  181. }
  182. static S32 _Sort(const S32 *p1, const S32 *p2)
  183. {
  184. S32 e1 = (*p1);
  185. S32 e2 = (*p2);
  186. if (e1 > e2)
  187. return 1;
  188. else if (e1 < e2)
  189. return -1;
  190. return 0;
  191. }
  192. S32 getDetailLevelSize(U32 detailIdx)
  193. {
  194. Vector<S32> detailLevelIdxs;
  195. for (U32 i = 0; i < meshData.size(); ++i)
  196. {
  197. for (U32 d = 0; d < meshData[i].meshDetailLevels.size(); ++d)
  198. {
  199. S32 mdlSize = meshData[i].meshDetailLevels[d].size;
  200. detailLevelIdxs.push_back_unique(mdlSize);
  201. }
  202. }
  203. if (detailIdx >= detailLevelIdxs.size())
  204. return -1;
  205. detailLevelIdxs.sort(&_Sort);
  206. return detailLevelIdxs[detailIdx];
  207. }
  208. };
  209. void convertTransform(MatrixF& m);
  210. void collapsePath(std::string& path);
  211. // Apply the set of Collada conditioners (suited for loading Collada models into Torque)
  212. void applyConditioners(domCOLLADA* root);
  213. const domProfile_COMMON* findEffectCommonProfile(const domEffect* effect);
  214. const domCommon_color_or_texture_type_complexType* findEffectDiffuse(const domEffect* effect);
  215. const domCommon_color_or_texture_type_complexType* findEffectSpecular(const domEffect* effect);
  216. const domFx_sampler2D_common_complexType* getTextureSampler(const domEffect* effect, const domCommon_color_or_texture_type_complexType* texture);
  217. String getSamplerImagePath(const domEffect* effect, const domFx_sampler2D_common_complexType* sampler2D);
  218. String resolveImagePath(const domImage* image);
  219. // Collada export helper functions
  220. Torque::Path findTexture(const Torque::Path& diffuseMap);
  221. void exportColladaHeader(TiXmlElement* rootNode);
  222. void exportColladaMaterials(TiXmlElement* rootNode, const OptimizedPolyList& mesh, Vector<String>& matNames, const Torque::Path& colladaFile);
  223. void exportColladaTriangles(TiXmlElement* meshNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames);
  224. void exportColladaMesh(TiXmlElement* rootNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames);
  225. void exportColladaScene(TiXmlElement* rootNode, const String& meshName, const Vector<String>& matNames);
  226. void exportColladaMaterials(TiXmlElement* rootNode, const ExportData& exportData, const Torque::Path& colladaFile);
  227. void exportColladaMesh(TiXmlElement* rootNode, const ExportData& exportData, const String& meshName);
  228. void exportColladaCollisionTriangles(TiXmlElement* meshNode, const ExportData& exportData, const U32 collisionIdx);
  229. void exportColladaTriangles(TiXmlElement* meshNode, const ExportData& exportData, const U32 detailLevel, const String& meshName);
  230. void exportColladaScene(TiXmlElement* rootNode, const ExportData& exportData, const String& meshName);
  231. // Export an OptimizedPolyList to a simple Collada file
  232. void exportToCollada(const Torque::Path& colladaFile, const OptimizedPolyList& mesh, const String& meshName = String::EmptyString);
  233. void exportToCollada(const Torque::Path& colladaFile, const ExportData& exportData);
  234. };
  235. //-----------------------------------------------------------------------------
  236. // Helper Classes
  237. //
  238. // The Collada DOM uses a different class for each XML element, and there is very
  239. // little class inheritance, even though many elements have the same attributes
  240. // and children. This makes the DOM a bit ugly to work with, and the following
  241. // templates attempt to make this situation a bit nicer by providing a common way
  242. // to access common elements, while retaining the strong typing of the DOM classes.
  243. //-----------------------------------------------------------------------------
  244. /// Convert from the Collada transform types to a Torque MatrixF
  245. template<class T> inline MatrixF vecToMatrixF(const domListOfFloats& vec) { return MatrixF(true); }
  246. /// Collada <translate>: [x_translate, y_translate, z_translate]
  247. template<> inline MatrixF vecToMatrixF<domTranslate>(const domListOfFloats& vec)
  248. {
  249. MatrixF mat(true);
  250. mat.setPosition(Point3F(vec[0], vec[1], vec[2]));
  251. return mat;
  252. }
  253. /// Collada <scale>: [x_scale, y_scale, z_scale]
  254. template<> inline MatrixF vecToMatrixF<domScale>(const domListOfFloats& vec)
  255. {
  256. MatrixF mat(true);
  257. mat.scale(Point3F(vec[0], vec[1], vec[2]));
  258. return mat;
  259. }
  260. /// Collada <rotate>: [rotation_axis, angle_in_degrees]
  261. template<> inline MatrixF vecToMatrixF<domRotate>(const domListOfFloats& vec)
  262. {
  263. AngAxisF aaxis(Point3F(vec[0], vec[1], vec[2]), -(vec[3] * M_PI) / 180.0f);
  264. MatrixF mat(true);
  265. aaxis.setMatrix(&mat);
  266. return mat;
  267. }
  268. /// Collada <matrix>: same form as TGE (woohoo!)
  269. template<> inline MatrixF vecToMatrixF<domMatrix>(const domListOfFloats& vec)
  270. {
  271. MatrixF mat;
  272. for (S32 i = 0; i < 16; i++)
  273. mat[i] = vec[i];
  274. return mat;
  275. }
  276. /// Collada <skew>: [angle_in_degrees, rotation_axis, translation_axis]
  277. /// skew transform code adapted from GMANMatrix4 implementation
  278. template<> inline MatrixF vecToMatrixF<domSkew>(const domListOfFloats& vec)
  279. {
  280. F32 angle = -(vec[0] * M_PI) / 180.0f;
  281. Point3F rotAxis(vec[1], vec[2], vec[3]);
  282. Point3F transAxis(vec[4], vec[5], vec[6]);
  283. transAxis.normalize();
  284. Point3F a1 = transAxis * mDot(rotAxis, transAxis);
  285. Point3F a2 = rotAxis - a1;
  286. a2.normalize();
  287. F32 an1 = mDot(rotAxis, a2);
  288. F32 an2 = mDot(rotAxis, transAxis);
  289. F32 rx = an1 * mCos(angle) - an2 * mSin(angle);
  290. F32 ry = an1 * mSin(angle) + an2 * mCos(angle);
  291. // Check for rotation parallel to translation
  292. F32 alpha = (an1 == 0) ? 0 : (ry/rx - an2/an1);
  293. MatrixF mat(true);
  294. mat(0,0) = a2.x * transAxis.x * alpha + 1.0;
  295. mat(1,0) = a2.y * transAxis.x * alpha;
  296. mat(2,0) = a2.z * transAxis.x * alpha;
  297. mat(0,1) = a2.x * transAxis.y * alpha;
  298. mat(1,1) = a2.y * transAxis.y * alpha + 1.0;
  299. mat(2,1) = a2.z * transAxis.y * alpha;
  300. mat(0,2) = a2.x * transAxis.z * alpha;
  301. mat(1,2) = a2.y * transAxis.z * alpha;
  302. mat(2,2) = a2.z * transAxis.z * alpha + 1.0;
  303. return mat;
  304. }
  305. /// Collada <lookat>: [eye, target, up]
  306. template<> inline MatrixF vecToMatrixF<domLookat>(const domListOfFloats& vec)
  307. {
  308. Point3F eye(vec[0], vec[1], vec[2]);
  309. Point3F target(vec[3], vec[4], vec[5]);
  310. Point3F up(vec[6], vec[7], vec[8]);
  311. Point3F fwd = target - eye;
  312. fwd.normalizeSafe();
  313. Point3F right = mCross(fwd, up);
  314. right.normalizeSafe();
  315. up = mCross(right, fwd);
  316. up.normalizeSafe();
  317. MatrixF mat(true);
  318. mat.setColumn(0, right);
  319. mat.setColumn(1, fwd);
  320. mat.setColumn(2, up);
  321. mat.setColumn(3, eye);
  322. return mat;
  323. }
  324. //-----------------------------------------------------------------------------
  325. /// Try to get a name for the element using the following attributes (in order):
  326. /// name, sid, id, "null"
  327. template<class T> inline const char* _GetNameOrId(const T* element)
  328. {
  329. return element ? (element->getName() ? element->getName() : (element->getId() ? element->getId() : "null")) : "null";
  330. }
  331. template<> inline const char* _GetNameOrId(const domInstance_geometry* element)
  332. {
  333. return element ? (element->getName() ? element->getName() : (element->getSid() ? element->getSid() : "null")) : "null";
  334. }
  335. template<> inline const char* _GetNameOrId(const domInstance_controller* element)
  336. {
  337. return element ? (element->getName() ? element->getName() : (element->getSid() ? element->getSid() : "null")) : "null";
  338. }
  339. //-----------------------------------------------------------------------------
  340. // Collada <source>s are extremely flexible, and thus difficult to access in a nice
  341. // way. This class attempts to provide a clean interface to convert Collada source
  342. // data to the appropriate Torque data structure without losing any of the flexibility
  343. // of the underlying Collada DOM.
  344. //
  345. // Some of the conversions we need to handle are:
  346. // - daeString to const char*
  347. // - daeIDRef to const char*
  348. // - double to F32
  349. // - double to Point2F
  350. // - double to Point3F
  351. // - double to MatrixF
  352. //
  353. // The _SourceReader object is initialized with a list of parameter names that it
  354. // tries to match to <param> elements in the source accessor to figure out how to
  355. // pull values out of the 1D source array. Note that no type checking of any kind
  356. // is done until we actually try to extract values from the source.
  357. class _SourceReader
  358. {
  359. const domSource* source; // the wrapped Collada source
  360. const domAccessor* accessor; // shortcut to the source accessor
  361. Vector<U32> offsets; // offset of each of the desired values to pull from the source array
  362. public:
  363. _SourceReader() : source(0), accessor(0) {}
  364. void reset()
  365. {
  366. source = 0;
  367. accessor = 0;
  368. offsets.clear();
  369. }
  370. //------------------------------------------------------
  371. // Initialize the _SourceReader object
  372. bool initFromSource(const domSource* src, const char* paramNames[] = 0)
  373. {
  374. source = src;
  375. accessor = source->getTechnique_common()->getAccessor();
  376. offsets.clear();
  377. // The source array has groups of values in a 1D stream => need to map the
  378. // input param names to source params to determine the offset within the
  379. // group for each desired value
  380. U32 paramCount = 0;
  381. while (paramNames && paramNames[paramCount][0]) {
  382. // lookup the index of the source param that matches the input param
  383. offsets.push_back(paramCount);
  384. for (U32 iParam = 0; iParam < accessor->getParam_array().getCount(); iParam++) {
  385. if (accessor->getParam_array()[iParam]->getName() &&
  386. dStrEqual(accessor->getParam_array()[iParam]->getName(), paramNames[paramCount])) {
  387. offsets.last() = iParam;
  388. break;
  389. }
  390. }
  391. paramCount++;
  392. }
  393. // If no input params were specified, just map the source params directly
  394. if (!offsets.size()) {
  395. for (S32 iParam = 0; iParam < accessor->getParam_array().getCount(); iParam++)
  396. offsets.push_back(iParam);
  397. }
  398. return true;
  399. }
  400. //------------------------------------------------------
  401. // Shortcut to the size of the array (should be the number of destination objects)
  402. S32 size() const { return accessor ? accessor->getCount() : 0; }
  403. // Get the number of elements per group in the source
  404. S32 stride() const { return accessor ? accessor->getStride() : 0; }
  405. //------------------------------------------------------
  406. // Get a pointer to the start of a group of values (index advances by stride)
  407. //template<class T> T getArrayData(S32 index) const { return 0; }
  408. const double* getStringArrayData(S32 index) const
  409. {
  410. if ((index >= 0) && (index < size())) {
  411. if (source->getFloat_array())
  412. return &source->getFloat_array()->getValue()[index*stride()];
  413. }
  414. return 0;
  415. }
  416. //------------------------------------------------------
  417. // Read a single value from the source array
  418. //template<class T> T getValue(S32 index) const { return T; }
  419. const char* getStringValue(S32 index) const
  420. {
  421. if ((index >= 0) && (index < size())) {
  422. // could be plain strings or IDREFs
  423. if (source->getName_array())
  424. return source->getName_array()->getValue()[index*stride()];
  425. else if (source->getIDREF_array())
  426. return source->getIDREF_array()->getValue()[index*stride()].getID();
  427. }
  428. return "";
  429. }
  430. F32 getFloatValue(S32 index) const
  431. {
  432. F32 value(0);
  433. if (const double* data = getStringArrayData(index))
  434. return data[offsets[0]];
  435. return value;
  436. }
  437. Point2F getPoint2FValue(S32 index) const
  438. {
  439. Point2F value(0, 0);
  440. if (const double* data = getStringArrayData(index))
  441. value.set(data[offsets[0]], data[offsets[1]]);
  442. return value;
  443. }
  444. Point3F getPoint3FValue(S32 index) const
  445. {
  446. Point3F value(1, 0, 0);
  447. if (const double* data = getStringArrayData(index))
  448. value.set(data[offsets[0]], data[offsets[1]], data[offsets[2]]);
  449. return value;
  450. }
  451. ColorI getColorIValue(S32 index) const
  452. {
  453. ColorI value(255, 255, 255, 255);
  454. if (const double* data = getStringArrayData(index))
  455. {
  456. value.red = data[offsets[0]] * 255.0;
  457. value.green = data[offsets[1]] * 255.0;
  458. value.blue = data[offsets[2]] * 255.0;
  459. if ( stride() == 4 )
  460. value.alpha = data[offsets[3]] * 255.0;
  461. }
  462. return value;
  463. }
  464. MatrixF getMatrixFValue(S32 index) const
  465. {
  466. MatrixF value(true);
  467. if (const double* data = getStringArrayData(index)) {
  468. for (S32 i = 0; i < 16; i++)
  469. value[i] = data[i];
  470. }
  471. return value;
  472. }
  473. };
  474. //-----------------------------------------------------------------------------
  475. // Collada geometric primitives: Use the BasePrimitive class to access the
  476. // different primitive types in a nice way.
  477. class BasePrimitive
  478. {
  479. public:
  480. virtual ~BasePrimitive() { }
  481. /// Return true if the element is a geometric primitive type
  482. static bool isPrimitive(const daeElement* element)
  483. {
  484. switch (element->getElementType()) {
  485. case COLLADA_TYPE::TRIANGLES: case COLLADA_TYPE::POLYLIST:
  486. case COLLADA_TYPE::POLYGONS: case COLLADA_TYPE::TRIFANS:
  487. case COLLADA_TYPE::TRISTRIPS: case COLLADA_TYPE::CAPSULE:
  488. case COLLADA_TYPE::CYLINDER: case COLLADA_TYPE::LINES:
  489. case COLLADA_TYPE::LINESTRIPS: case COLLADA_TYPE::PLANE:
  490. case COLLADA_TYPE::SPLINE: case COLLADA_TYPE::SPHERE:
  491. case COLLADA_TYPE::TAPERED_CAPSULE: case COLLADA_TYPE::TAPERED_CYLINDER:
  492. return true;
  493. }
  494. return false;
  495. }
  496. /// Return true if the element is a supported primitive type
  497. static bool isSupportedPrimitive(const daeElement* element)
  498. {
  499. switch (element->getElementType()) {
  500. case COLLADA_TYPE::TRIANGLES:
  501. case COLLADA_TYPE::TRISTRIPS:
  502. case COLLADA_TYPE::TRIFANS:
  503. case COLLADA_TYPE::POLYLIST:
  504. case COLLADA_TYPE::POLYGONS:
  505. return true;
  506. }
  507. return false;
  508. }
  509. /// Construct a child class based on the type of Collada element
  510. static BasePrimitive* get(const daeElement* element);
  511. /// Methods to be implemented for each supported Collada geometric element
  512. virtual const char* getElementName() = 0;
  513. virtual const char* getMaterial() = 0;
  514. virtual const domInputLocalOffset_Array& getInputs() = 0;
  515. virtual S32 getStride() const = 0;
  516. virtual const domListOfUInts *getTriangleData() = 0;
  517. };
  518. /// Template child class for supported Collada primitive elements
  519. template<class T> class ColladaPrimitive : public BasePrimitive
  520. {
  521. T* primitive;
  522. domListOfUInts *pTriangleData;
  523. S32 stride;
  524. public:
  525. ColladaPrimitive(const daeElement* e) : pTriangleData(0)
  526. {
  527. // Cast to geometric primitive element
  528. primitive = daeSafeCast<T>(const_cast<daeElement*>(e));
  529. // Determine stride
  530. stride = 0;
  531. for (S32 iInput = 0; iInput < getInputs().getCount(); iInput++) {
  532. if (getInputs()[iInput]->getOffset() >= stride)
  533. stride = getInputs()[iInput]->getOffset() + 1;
  534. }
  535. }
  536. ~ColladaPrimitive()
  537. {
  538. delete pTriangleData;
  539. }
  540. /// Most primitives can use these common implementations
  541. const char* getElementName() { return primitive->getElementName(); }
  542. const char* getMaterial() { return (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImportMat, primitive->getMaterial(), false)) ? NULL : primitive->getMaterial(); }
  543. const domInputLocalOffset_Array& getInputs() { return primitive->getInput_array(); }
  544. S32 getStride() const { return stride; }
  545. /// Each supported primitive needs to implement this method (and convert
  546. /// to triangles if required)
  547. const domListOfUInts *getTriangleData() { return NULL; }
  548. };
  549. //-----------------------------------------------------------------------------
  550. // <triangles>
  551. template<> inline const domListOfUInts *ColladaPrimitive<domTriangles>::getTriangleData()
  552. {
  553. // Return the <p> integer list directly
  554. return (primitive->getP() ? &(primitive->getP()->getValue()) : NULL);
  555. }
  556. //-----------------------------------------------------------------------------
  557. // <tristrips>
  558. template<> inline const domListOfUInts *ColladaPrimitive<domTristrips>::getTriangleData()
  559. {
  560. if (!pTriangleData)
  561. {
  562. // Convert strips to triangles
  563. pTriangleData = new domListOfUInts();
  564. for (S32 iStrip = 0; iStrip < primitive->getCount(); iStrip++) {
  565. domP* P = primitive->getP_array()[iStrip];
  566. // Ignore invalid P arrays
  567. if (!P || !P->getValue().getCount())
  568. continue;
  569. domUint* pSrcData = &(P->getValue()[0]);
  570. size_t numTriangles = (P->getValue().getCount() / stride) - 2;
  571. // Convert the strip back to a triangle list
  572. domUint* v0 = pSrcData;
  573. for (S32 iTri = 0; iTri < numTriangles; iTri++, v0 += stride) {
  574. if (iTri & 0x1)
  575. {
  576. // CW triangle
  577. pTriangleData->appendArray(stride, v0);
  578. pTriangleData->appendArray(stride, v0 + 2*stride);
  579. pTriangleData->appendArray(stride, v0 + stride);
  580. }
  581. else
  582. {
  583. // CCW triangle
  584. pTriangleData->appendArray(stride*3, v0);
  585. }
  586. }
  587. }
  588. }
  589. return pTriangleData;
  590. }
  591. //-----------------------------------------------------------------------------
  592. // <trifans>
  593. template<> inline const domListOfUInts *ColladaPrimitive<domTrifans>::getTriangleData()
  594. {
  595. if (!pTriangleData)
  596. {
  597. // Convert strips to triangles
  598. pTriangleData = new domListOfUInts();
  599. for (S32 iStrip = 0; iStrip < primitive->getCount(); iStrip++) {
  600. domP* P = primitive->getP_array()[iStrip];
  601. // Ignore invalid P arrays
  602. if (!P || !P->getValue().getCount())
  603. continue;
  604. domUint* pSrcData = &(P->getValue()[0]);
  605. size_t numTriangles = (P->getValue().getCount() / stride) - 2;
  606. // Convert the fan back to a triangle list
  607. domUint* v0 = pSrcData + stride;
  608. for (S32 iTri = 0; iTri < numTriangles; iTri++, v0 += stride) {
  609. pTriangleData->appendArray(stride, pSrcData); // shared vertex
  610. pTriangleData->appendArray(stride, v0); // previous vertex
  611. pTriangleData->appendArray(stride, v0+stride); // current vertex
  612. }
  613. }
  614. }
  615. return pTriangleData;
  616. }
  617. //-----------------------------------------------------------------------------
  618. // <polygons>
  619. template<> inline const domListOfUInts *ColladaPrimitive<domPolygons>::getTriangleData()
  620. {
  621. if (!pTriangleData)
  622. {
  623. // Convert polygons to triangles
  624. pTriangleData = new domListOfUInts();
  625. for (S32 iPoly = 0; iPoly < primitive->getCount(); iPoly++) {
  626. domP* P = primitive->getP_array()[iPoly];
  627. // Ignore invalid P arrays
  628. if (!P || !P->getValue().getCount())
  629. continue;
  630. domUint* pSrcData = &(P->getValue()[0]);
  631. size_t numPoints = P->getValue().getCount() / stride;
  632. // Use a simple tri-fan (centered at the first point) method of
  633. // converting the polygon to triangles.
  634. domUint* v0 = pSrcData;
  635. pSrcData += stride;
  636. for (S32 iTri = 0; iTri < numPoints-2; iTri++) {
  637. pTriangleData->appendArray(stride, v0);
  638. pTriangleData->appendArray(stride*2, pSrcData);
  639. pSrcData += stride;
  640. }
  641. }
  642. }
  643. return pTriangleData;
  644. }
  645. //-----------------------------------------------------------------------------
  646. // <polylist>
  647. template<> inline const domListOfUInts *ColladaPrimitive<domPolylist>::getTriangleData()
  648. {
  649. if (!pTriangleData)
  650. {
  651. // Convert polygons to triangles
  652. pTriangleData = new domListOfUInts();
  653. // Check that the P element has the right number of values (this
  654. // has been seen with certain models exported using COLLADAMax)
  655. const domListOfUInts& vcount = primitive->getVcount()->getValue();
  656. U32 expectedCount = 0;
  657. for (S32 iPoly = 0; iPoly < vcount.getCount(); iPoly++)
  658. expectedCount += vcount[iPoly];
  659. expectedCount *= stride;
  660. if (!primitive->getP() || !primitive->getP()->getValue().getCount() ||
  661. (primitive->getP()->getValue().getCount() != expectedCount) )
  662. {
  663. Con::warnf("<polylist> element found with invalid <p> array. This primitive will be ignored.");
  664. return pTriangleData;
  665. }
  666. domUint* pSrcData = &(primitive->getP()->getValue()[0]);
  667. for (S32 iPoly = 0; iPoly < vcount.getCount(); iPoly++) {
  668. // Use a simple tri-fan (centered at the first point) method of
  669. // converting the polygon to triangles.
  670. domUint* v0 = pSrcData;
  671. pSrcData += stride;
  672. for (S32 iTri = 0; iTri < vcount[iPoly]-2; iTri++) {
  673. pTriangleData->appendArray(stride, v0);
  674. pTriangleData->appendArray(stride*2, pSrcData);
  675. pSrcData += stride;
  676. }
  677. pSrcData += stride;
  678. }
  679. }
  680. return pTriangleData;
  681. }
  682. //-----------------------------------------------------------------------------
  683. /// Convert a custom parameter string to a particular type
  684. template<typename T> inline T convert(const char* value) { return value; }
  685. template<> inline bool convert(const char* value) { return dAtob(value); }
  686. template<> inline S32 convert(const char* value) { return dAtoi(value); }
  687. template<> inline F64 convert(const char* value) { return dAtof(value); }
  688. template<> inline F32 convert(const char* value) { return convert<double>(value); }
  689. //-----------------------------------------------------------------------------
  690. /// Collada animation data
  691. struct AnimChannels : public Vector<struct AnimData*>
  692. {
  693. daeElement *element;
  694. AnimChannels(daeElement* el) : element(el)
  695. {
  696. element->setUserData(this);
  697. }
  698. ~AnimChannels()
  699. {
  700. if (element)
  701. element->setUserData(0);
  702. }
  703. };
  704. struct AnimData
  705. {
  706. bool enabled; ///!< Used to select animation channels for the current clip
  707. _SourceReader input;
  708. _SourceReader output;
  709. _SourceReader inTangent;
  710. _SourceReader outTangent;
  711. _SourceReader interpolation;
  712. U32 targetValueOffset; ///< Offset into the target element (for arrays of values)
  713. U32 targetValueCount; ///< Number of values animated (from OUTPUT source array)
  714. /// Get the animation channels for the Collada element (if any)
  715. static AnimChannels* getAnimChannels(const daeElement* element)
  716. {
  717. return element ? (AnimChannels*)const_cast<daeElement*>(element)->getUserData() : 0;
  718. }
  719. AnimData() : enabled(false) { }
  720. void parseTargetString(const char* target, S32 fullCount, const char* elements[]);
  721. F32 invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const;
  722. void interpValue(F32 t, U32 offset, double* value) const;
  723. void interpValue(F32 t, U32 offset, const char** value) const;
  724. };
  725. //-----------------------------------------------------------------------------
  726. // Collada allows any element with an SID or ID attribute to be the target of
  727. // an animation channel, which is very flexible, but awkward to work with. Some
  728. // examples of animated values are:
  729. // - single float
  730. // - single int
  731. // - single bool
  732. // - single string
  733. // - list of floats (transform elements or morph weights)
  734. //
  735. // This class provides a generic way to check if an element is animated, and
  736. // to get the value of the element at a given time.
  737. template<class T>
  738. struct AnimatedElement
  739. {
  740. const daeElement* element; ///< The Collada element (can be NULL)
  741. T defaultVal; ///< Default value (used when element is NULL)
  742. AnimatedElement(const daeElement* e=0) : element(e) { }
  743. /// Check if the element has any animations channels
  744. bool isAnimated() { return (AnimData::getAnimChannels(element) != 0); }
  745. bool isAnimated(F32 start, F32 end) { return isAnimated(); }
  746. /// Get the value of the element at the specified time
  747. T getValue(F32 time)
  748. {
  749. // If the element is NULL, just use the default (handy for <extra> profiles which
  750. // may or may not be present in the document)
  751. T value(defaultVal);
  752. if (const domAny* param = daeSafeCast<domAny>(const_cast<daeElement*>(element))) {
  753. // If the element is not animated, just use its current value
  754. value = convert<T>(param->getValue());
  755. // Animate the value
  756. const AnimChannels* channels = AnimData::getAnimChannels(element);
  757. if (channels && (time >= 0)) {
  758. for (S32 iChannel = 0; iChannel < channels->size(); iChannel++) {
  759. const AnimData* animData = (*channels)[iChannel];
  760. if (animData->enabled)
  761. animData->interpValue(time, 0, &value);
  762. }
  763. }
  764. }
  765. return value;
  766. }
  767. };
  768. template<class T> struct AnimatedElementList : public AnimatedElement<T>
  769. {
  770. AnimatedElementList(const daeElement* e=0) : AnimatedElement<T>(e) { }
  771. // @todo: Disable morph animations for now since they are not supported by T3D
  772. bool isAnimated() { return false; }
  773. bool isAnimated(F32 start, F32 end) { return false; }
  774. // Get the value of the element list at the specified time
  775. T getValue(F32 time)
  776. {
  777. T vec(this->defaultVal);
  778. if (this->element) {
  779. // Get a copy of the vector
  780. vec = *(T*)const_cast<daeElement*>(this->element)->getValuePointer();
  781. // Animate the vector
  782. const AnimChannels* channels = AnimData::getAnimChannels(this->element);
  783. if (channels && (time >= 0)) {
  784. for (S32 iChannel = 0; iChannel < channels->size(); iChannel++) {
  785. const AnimData* animData = (*channels)[iChannel];
  786. if (animData->enabled) {
  787. for (S32 iValue = 0; iValue < animData->targetValueCount; iValue++)
  788. animData->interpValue(time, iValue, &vec[animData->targetValueOffset + iValue]);
  789. }
  790. }
  791. }
  792. }
  793. return vec;
  794. }
  795. };
  796. // Strongly typed animated values
  797. typedef AnimatedElement<double> AnimatedFloat;
  798. typedef AnimatedElement<bool> AnimatedBool;
  799. typedef AnimatedElement<S32> AnimatedInt;
  800. typedef AnimatedElement<const char*> AnimatedString;
  801. typedef AnimatedElementList<domListOfFloats> AnimatedFloatList;
  802. #endif // _COLLADA_UTILS_H_