2
0

colladaUtils.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064
  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. #include <algorithm>
  23. #include "console/console.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "ts/collada/colladaUtils.h"
  26. #include "materials/matInstance.h"
  27. //special handling for export classes
  28. #include "persistence/taml/fsTinyXml.h"
  29. #include "T3D/convexShape.h"
  30. using namespace ColladaUtils;
  31. #define MAX_PATH_LENGTH 256
  32. // Helper macro to create Collada elements
  33. #define CREATE_ELEMENT(container, name, type) \
  34. type* name = daeSafeCast<type>(container->createAndPlace(#name));
  35. ColladaUtils::ImportOptions& ColladaUtils::getOptions()
  36. {
  37. static ImportOptions options;
  38. return options;
  39. }
  40. //------------------------------------------------------------------------------
  41. // Utility functions
  42. // Convert a transform from the Collada model coordinate system to the DTS coordinate
  43. // system
  44. void ColladaUtils::convertTransform(MatrixF& mat)
  45. {
  46. MatrixF rot(true);
  47. switch (ColladaUtils::getOptions().upAxis)
  48. {
  49. case UPAXISTYPE_X_UP:
  50. // rotate 90 around Y-axis, then 90 around Z-axis
  51. rot(0,0) = 0.0f; rot(1,0) = 1.0f;
  52. rot(1,1) = 0.0f; rot(2,1) = 1.0f;
  53. rot(0,2) = 1.0f; rot(2,2) = 0.0f;
  54. // pre-multiply the transform by the rotation matrix
  55. mat.mulL(rot);
  56. break;
  57. case UPAXISTYPE_Y_UP:
  58. // rotate 180 around Y-axis, then 90 around X-axis
  59. rot(0,0) = -1.0f;
  60. rot(1,1) = 0.0f; rot(2,1) = 1.0f;
  61. rot(1,2) = 1.0f; rot(2,2) = 0.0f;
  62. // pre-multiply the transform by the rotation matrix
  63. mat.mulL(rot);
  64. break;
  65. case UPAXISTYPE_Z_UP:
  66. default:
  67. // nothing to do
  68. break;
  69. }
  70. }
  71. /// Find the COMMON profile element in an effect
  72. const domProfile_COMMON* ColladaUtils::findEffectCommonProfile(const domEffect* effect)
  73. {
  74. if (effect) {
  75. // Find the COMMON profile
  76. const domFx_profile_abstract_Array& profiles = effect->getFx_profile_abstract_array();
  77. for (S32 iProfile = 0; iProfile < profiles.getCount(); iProfile++) {
  78. if (profiles[iProfile]->getElementType() == COLLADA_TYPE::PROFILE_COMMON)
  79. return daeSafeCast<domProfile_COMMON>(profiles[iProfile]);
  80. }
  81. }
  82. return NULL;
  83. }
  84. /// Find the <diffuse> element in the COMMON profile of an effect
  85. const domCommon_color_or_texture_type_complexType* ColladaUtils::findEffectDiffuse(const domEffect* effect)
  86. {
  87. const domProfile_COMMON* profile = findEffectCommonProfile(effect);
  88. if (profile) {
  89. if (profile->getTechnique()->getLambert())
  90. return profile->getTechnique()->getLambert()->getDiffuse();
  91. else if (profile->getTechnique()->getPhong())
  92. return profile->getTechnique()->getPhong()->getDiffuse();
  93. else if (profile->getTechnique()->getBlinn())
  94. return profile->getTechnique()->getBlinn()->getDiffuse();
  95. }
  96. return NULL;
  97. }
  98. /// Find the <specular> element in the COMMON profile of an effect
  99. const domCommon_color_or_texture_type_complexType* ColladaUtils::findEffectSpecular(const domEffect* effect)
  100. {
  101. const domProfile_COMMON* profile = findEffectCommonProfile(effect);
  102. if (profile) {
  103. if (profile->getTechnique()->getLambert())
  104. return NULL; // no <specular> element for Lambert shader
  105. else if (profile->getTechnique()->getPhong())
  106. return profile->getTechnique()->getPhong()->getSpecular();
  107. else if (profile->getTechnique()->getBlinn())
  108. return profile->getTechnique()->getBlinn()->getSpecular();
  109. }
  110. return NULL;
  111. }
  112. const domFx_sampler2D_common_complexType* ColladaUtils::getTextureSampler(const domEffect* effect,
  113. const domCommon_color_or_texture_type_complexType* texture)
  114. {
  115. // <texture texture="new_param_SID">.<newparam>.<sampler2D>
  116. if (texture) {
  117. const domCommon_color_or_texture_type_complexType::domTexture* domTex = texture->getTexture();
  118. if (domTex && domTex->getTexture()) {
  119. daeSIDResolver resolver(const_cast<domEffect*>(effect), domTex->getTexture());
  120. const domCommon_newparam_type* param = daeSafeCast<domCommon_newparam_type>(resolver.getElement());
  121. if (param)
  122. return param->getSampler2D();
  123. }
  124. }
  125. return NULL;
  126. }
  127. String ColladaUtils::getSamplerImagePath(const domEffect* effect,
  128. const domFx_sampler2D_common_complexType* sampler2D)
  129. {
  130. // <sampler2D>.<source>.<newparam>.<surface>.<init_from>.<image>.<init_from>
  131. const domProfile_COMMON* profile = findEffectCommonProfile(effect);
  132. if (profile && sampler2D && sampler2D->getSource()) {
  133. // Resolve the SID to get the <surface> param
  134. daeSIDResolver resolver(const_cast<domProfile_COMMON*>(profile), sampler2D->getSource()->getValue());
  135. domCommon_newparam_type* surfaceParam = daeSafeCast<domCommon_newparam_type>(resolver.getElement());
  136. // Get the surface <init_from> element
  137. if (surfaceParam && surfaceParam->getSurface()) {
  138. const domFx_surface_init_common* surfaceInit = surfaceParam->getSurface()->getFx_surface_init_common();
  139. if (surfaceInit && surfaceInit->getInit_from_array().getCount()) {
  140. // Resolve the ID to get the <image>, then read the texture path
  141. xsIDREF& idRef = surfaceInit->getInit_from_array()[0]->getValue();
  142. const domImage* image = daeSafeCast<domImage>(idRef.getElement());
  143. if (image && image->getInit_from())
  144. return resolveImagePath(image);
  145. }
  146. }
  147. }
  148. return "";
  149. }
  150. // Resolve image path into something we can use.
  151. String ColladaUtils::resolveImagePath(const domImage* image)
  152. {
  153. // 1. If the URI string contains an absolute path, use it if
  154. // it is inside the Torque folder, otherwise force textures
  155. // to be in the same folder as the shape.
  156. // 2. If the URI string contains a relative path, append it
  157. // to the shape path (since materials.tscript cannot handle
  158. // relative paths).
  159. Torque::Path imagePath;
  160. String imageStr(image->getInit_from()->getValue().originalStr().c_str());
  161. // Trim leading "file://"
  162. if (imageStr.compare("file://", 7) == 0)
  163. imageStr.erase(0, 7);
  164. // Trim leading slash from absolute windows paths. eg. /D:/
  165. if ((imageStr.compare("/", 1) == 0) && (imageStr.find(':') == 2))
  166. imageStr.erase(0, 1);
  167. // Replace %20 with space
  168. imageStr.replace("%20", " ");
  169. if (Platform::isFullPath(imageStr))
  170. {
  171. // Absolute path => check for outside the Torque game folder
  172. imagePath = String( Platform::makeRelativePathName(imageStr, Platform::getMainDotCsDir()) );
  173. if ( !imagePath.getRoot().isEmpty() || // different drive (eg. C:/ vs D:/)
  174. (imagePath.getPath().find("/") == 0) || // different OS (eg. /home vs C:/home)
  175. (imagePath.getPath().find("../") == 0) ) // same drive, outside Torque game folder
  176. {
  177. // Force these to the shape folder
  178. imagePath.setRoot("");
  179. imagePath.setPath("");
  180. }
  181. }
  182. else
  183. {
  184. // Relative path => prepend with shape path
  185. Torque::Path tempPath(imageStr);
  186. imagePath = TSShapeLoader::getShapePath();
  187. imagePath.appendPath(tempPath);
  188. imagePath.setFileName(tempPath.getFileName());
  189. }
  190. // No need to specify the path if it is in the same folder as the model
  191. if (imagePath.getPath() == TSShapeLoader::getShapePath().getPath())
  192. imagePath.setPath("");
  193. // Don't care about the extension
  194. imagePath.setExtension("");
  195. return imagePath.getFullPath();
  196. }
  197. //-----------------------------------------------------------------------------
  198. // Construct the appropriate child class
  199. BasePrimitive* BasePrimitive::get(const daeElement* element)
  200. {
  201. switch (element->getElementType()) {
  202. case COLLADA_TYPE::TRIANGLES: return new ColladaPrimitive<domTriangles>(element);
  203. case COLLADA_TYPE::TRISTRIPS: return new ColladaPrimitive<domTristrips>(element);
  204. case COLLADA_TYPE::TRIFANS: return new ColladaPrimitive<domTrifans>(element);
  205. case COLLADA_TYPE::POLYGONS: return new ColladaPrimitive<domPolygons>(element);
  206. case COLLADA_TYPE::POLYLIST: return new ColladaPrimitive<domPolylist>(element);
  207. default: return 0;
  208. }
  209. }
  210. //------------------------------------------------------------------------------
  211. // Collada animation curves
  212. /// Determine which elements are being targeted
  213. void AnimData::parseTargetString(const char* target, S32 fullCount, const char* elements[])
  214. {
  215. // Assume targeting all elements at offset 0
  216. targetValueCount = fullCount;
  217. targetValueOffset = 0;
  218. // Check for array syntax: (n) or (n)(m)
  219. if (const char* p = dStrchr(target, '(')) {
  220. S32 indN, indM;
  221. if (dSscanf(p, "(%d)(%d)", &indN, &indM) == 2) {
  222. targetValueOffset = (indN * 4) + indM; // @todo: 4x4 matrix only
  223. targetValueCount = 1;
  224. }
  225. else if (dSscanf(p, "(%d)", &indN) == 1) {
  226. targetValueOffset = indN;
  227. targetValueCount = 1;
  228. }
  229. }
  230. else if (const char* p2 = dStrrchr(target, '.')) {
  231. // Check for named elements
  232. for (S32 iElem = 0; elements[iElem][0] != 0; iElem++) {
  233. if (!String::compare(p2, elements[iElem])) {
  234. targetValueOffset = iElem;
  235. targetValueCount = 1;
  236. break;
  237. }
  238. }
  239. }
  240. }
  241. /// Solve the cubic spline B(s) = param for s
  242. F32 AnimData::invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const
  243. {
  244. const F64 INVERTPARAMCUBIC_TOL = 1.0e-09;
  245. const F64 INVERTPARAMCUBIC_SMALLERTOL = 1.0e-20;
  246. const F64 INVERTPARAMCUBIC_MAXIT = 100;
  247. // check input value for outside range
  248. if ((param - x0) < INVERTPARAMCUBIC_SMALLERTOL)
  249. return 0.0f;
  250. else if ((x3 - param) < INVERTPARAMCUBIC_SMALLERTOL)
  251. return 1.0f;
  252. U32 iterations = 0;
  253. // de Casteljau Subdivision.
  254. F32 u = 0.0f;
  255. F32 v = 1.0f;
  256. while (iterations < INVERTPARAMCUBIC_MAXIT) {
  257. F64 a = (x0 + x1)*0.5f;
  258. F64 b = (x1 + x2)*0.5f;
  259. F64 c = (x2 + x3)*0.5f;
  260. F64 d = (a + b)*0.5f;
  261. F64 e = (b + c)*0.5f;
  262. F64 f = (d + e)*0.5f;
  263. if (mFabs(f - param) < INVERTPARAMCUBIC_TOL)
  264. break;
  265. if (f < param) {
  266. x0 = f;
  267. x1 = e;
  268. x2 = c;
  269. u = (u + v)*0.5f;
  270. }
  271. else {
  272. x1 = a;
  273. x2 = d;
  274. x3 = f;
  275. v = (u + v)*0.5f;
  276. }
  277. iterations++;
  278. }
  279. return mClampF((u+v)*0.5f, 0.0f, 1.0f);
  280. }
  281. /// Get the interpolated value at time 't'
  282. void AnimData::interpValue(F32 t, U32 offset, double* value) const
  283. {
  284. // handle degenerate animation data
  285. if (input.size() == 0)
  286. {
  287. *value = 0.0f;
  288. return;
  289. }
  290. else if (input.size() == 1)
  291. {
  292. *value = output.getStringArrayData(0)[offset];
  293. return;
  294. }
  295. // clamp time to valid range
  296. F32 curveStart = input.getFloatValue(0);
  297. F32 curveEnd = input.getFloatValue(input.size()-1);
  298. t = mClampF(t, curveStart, curveEnd);
  299. // find the index of the input keyframe BEFORE 't'
  300. S32 index;
  301. for (index = 0; index < input.size()-2; index++) {
  302. if (input.getFloatValue(index + 1) > t)
  303. break;
  304. }
  305. // get the data for the two control points either side of 't'
  306. Point2F v0;
  307. v0.x = input.getFloatValue(index);
  308. v0.y = output.getStringArrayData(index)[offset];
  309. Point2F v3;
  310. v3.x = input.getFloatValue(index + 1);
  311. v3.y = output.getStringArrayData(index + 1)[offset];
  312. // If spline interpolation is specified but the tangents are not available,
  313. // default to LINEAR.
  314. const char* interp_method = interpolation.getStringValue(index);
  315. if (dStrEqual(interp_method, "BEZIER") ||
  316. dStrEqual(interp_method, "HERMITE") ||
  317. dStrEqual(interp_method, "CARDINAL")) {
  318. const double* inArray = inTangent.getStringArrayData(index + 1);
  319. const double* outArray = outTangent.getStringArrayData(index);
  320. if (!inArray || !outArray)
  321. interp_method = "LINEAR";
  322. }
  323. if (dStrEqual(interp_method, "STEP")) {
  324. // STEP interpolation
  325. *value = v0.y;
  326. }
  327. else if (dStrEqual(interp_method, "BEZIER") ||
  328. dStrEqual(interp_method, "HERMITE") ||
  329. dStrEqual(interp_method, "CARDINAL") ||
  330. dStrEqual(interp_method, "BSPLINE"))
  331. {
  332. // Cubic spline interpolation. The only difference between the 4 supported
  333. // forms is in the calculation of the other 2 control points:
  334. // BEZIER: control points are specified explicitly
  335. // HERMITE: tangents are specified, need to offset to get the control points
  336. // CARDINAL: (baked) tangents are specified, need to offset to get the control points
  337. // BSPLINE: control points are based on previous and next points
  338. // Get the 2 extra control points
  339. Point2F v1, v2;
  340. if (dStrEqual(interp_method, "BSPLINE")) {
  341. // v0 and v3 are the center points => need to
  342. // get the control points before and after them
  343. v1 = v0;
  344. v2 = v3;
  345. if (index > 0) {
  346. v0.x = input.getFloatValue(index-1);
  347. v0.y = output.getStringArrayData(index-1)[offset];
  348. }
  349. else {
  350. // mirror P1 through P0
  351. v0 = v1 + (v1 - v2);
  352. }
  353. if (index < (input.size()-2)) {
  354. v3.x = input.getFloatValue(index+2);
  355. v3.y = output.getStringArrayData(index+2)[offset];
  356. }
  357. else {
  358. // mirror P0 through P1
  359. v3 = v2 + (v2 - v1);
  360. }
  361. }
  362. else {
  363. const double* inArray = inTangent.getStringArrayData(index + 1);
  364. const double* outArray = outTangent.getStringArrayData(index);
  365. if (output.stride() == inTangent.stride()) {
  366. // This degenerate form (1D control points) does 2 things wrong:
  367. // 1) it does not specify the key (time) value
  368. // 2) the control point is specified as a tangent for both bezier and hermite
  369. // => interpolate to get the key values, and offset the tangent values
  370. v1.set((v0.x*2 + v3.x)/3, v0.y + outArray[offset]);
  371. v2.set((v0.x + v3.x*2)/3, v3.y - inArray[offset]);
  372. }
  373. else {
  374. // the expected form (2D control points)
  375. v1.set(outArray[offset*2], outArray[offset*2+1]);
  376. v2.set(inArray[offset*2], inArray[offset*2+1]);
  377. // if this is a hermite or cardinal spline, treat the values as tangents
  378. if (dStrEqual(interp_method, "HERMITE") || dStrEqual(interp_method, "CARDINAL")) {
  379. v1.set(v0.x + v1.x, v3.y - v1.y);
  380. v2.set(v0.x + v2.x, v3.x - v2.y);
  381. }
  382. }
  383. }
  384. // find 's' that gives the desired 't' value
  385. F32 s = invertParamCubic(t, v0.x, v1.x, v2.x, v3.x);
  386. // Calculate the output value using Bernstein evaluation and the
  387. // computed 's' value
  388. F32 c = 3.0f*(v1.y - v0.y);
  389. F32 e = 3.0f*(v2.y - v1.y);
  390. *value = (((v3.y - v0.y - e)*s + e - c)*s + c)*s + v0.y;
  391. }
  392. else {
  393. // default to LINEAR interpolation
  394. F32 s = mClampF((t - v0.x) / (v3.x - v0.x), 0.0f, 1.0f);
  395. *value = v0.y + (v3.y - v0.y) * s;
  396. }
  397. }
  398. void AnimData::interpValue(F32 t, U32 offset, const char** value) const
  399. {
  400. if (input.size() == 0)
  401. *value = "";
  402. else if (input.size() == 1)
  403. *value = output.getStringValue(0);
  404. else
  405. {
  406. // clamp time to valid range
  407. F32 curveStart = input.getFloatValue(0);
  408. F32 curveEnd = input.getFloatValue(input.size()-1);
  409. t = mClampF(t, curveStart, curveEnd);
  410. // find the index of the input keyframe BEFORE 't'
  411. S32 index;
  412. for (index = 0; index < input.size()-2; index++) {
  413. if (input.getFloatValue(index + 1) > t)
  414. break;
  415. }
  416. // String values only support STEP interpolation, so just get the
  417. // value at the input keyframe
  418. *value = output.getStringValue(index);
  419. }
  420. }
  421. //------------------------------------------------------------------------------
  422. // Collada document conditioners
  423. static void conditioner_fixupTextureSIDs(domCOLLADA* root)
  424. {
  425. for (S32 iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) {
  426. domLibrary_effects* lib = root->getLibrary_effects_array()[iLib];
  427. for (S32 iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) {
  428. domEffect* effect = lib->getEffect_array()[iEffect];
  429. const domCommon_color_or_texture_type_complexType* diffuse = findEffectDiffuse(effect);
  430. if (!diffuse || !diffuse->getTexture())
  431. continue;
  432. // Resolve the SID => if it is an <image>, add <sampler2D> and
  433. // <surface> elements to conform to the Collada spec.
  434. const char *image_sid = diffuse->getTexture()->getTexture();
  435. daeSIDResolver resolver(effect, image_sid);
  436. if (!daeSafeCast<domImage>(resolver.getElement()))
  437. continue;
  438. daeErrorHandler::get()->handleWarning(avar("Fixup %s <diffuse>.<texture> "
  439. "pointing at <image> instead of <sampler2D>", effect->getID()));
  440. // Generate SIDs for the new sampler2D and surface elements
  441. std::string sampler_sid(std::string(image_sid) + "-sampler");
  442. std::string surface_sid(std::string(image_sid) + "-surface");
  443. domProfile_COMMON* profile = const_cast<domProfile_COMMON*>(findEffectCommonProfile(effect));
  444. // Create <newparam>.<sampler2D>.<source>
  445. {
  446. CREATE_ELEMENT(profile, newparam, domCommon_newparam_type)
  447. CREATE_ELEMENT(newparam, sampler2D, domFx_sampler2D_common)
  448. CREATE_ELEMENT(sampler2D, source, domFx_sampler2D_common_complexType::domSource)
  449. newparam->setSid(sampler_sid.c_str());
  450. source->setValue(surface_sid.c_str());
  451. }
  452. // Create <newparam>.<surface>.<init_from>
  453. {
  454. CREATE_ELEMENT(profile, newparam, domCommon_newparam_type)
  455. CREATE_ELEMENT(newparam, surface, domFx_surface_common)
  456. CREATE_ELEMENT(surface, init_from, domFx_surface_init_from_common)
  457. CREATE_ELEMENT(surface, format, domFx_surface_common_complexType::domFormat)
  458. newparam->setSid(surface_sid.c_str());
  459. surface->setType(FX_SURFACE_TYPE_ENUM_2D);
  460. format->setValue("A8R8G8B8");
  461. init_from->setValue(image_sid);
  462. }
  463. // Store sampler2D sid in the <diffuse>.<texture> "texture" attribute
  464. diffuse->getTexture()->setTexture(sampler_sid.c_str());
  465. }
  466. }
  467. }
  468. static void conditioner_fixupImageURIs(domCOLLADA* root)
  469. {
  470. for (S32 iLib = 0; iLib < root->getLibrary_images_array().getCount(); iLib++) {
  471. domLibrary_images* lib = root->getLibrary_images_array()[iLib];
  472. for (S32 iImage = 0; iImage < lib->getImage_array().getCount(); iImage++) {
  473. domImage* image = lib->getImage_array()[iImage];
  474. if (image->getInit_from()) {
  475. xsAnyURI& uri = image->getInit_from()->getValue();
  476. // Replace '\' with '/'
  477. if (uri.originalStr().find("\\") != std::string::npos) {
  478. daeErrorHandler::get()->handleWarning(avar("Fixup invalid URI "
  479. "in %s: \"%s\"", image->getID(), uri.originalStr().c_str()));
  480. std::string str(uri.originalStr());
  481. std::replace(str.begin(), str.end(), '\\', '/');
  482. uri.set(str);
  483. }
  484. // Detect file://texture.jpg => this is an invalid URI and will
  485. // not be parsed correctly
  486. if (uri.scheme() == "file" &&
  487. uri.pathFile().empty() &&
  488. !uri.authority().empty()) {
  489. daeErrorHandler::get()->handleWarning(avar("Fixup invalid URI "
  490. "in %s: \"%s\"", image->getID(), uri.originalStr().c_str()));
  491. uri.set(uri.authority());
  492. }
  493. }
  494. }
  495. }
  496. }
  497. static void conditioner_fixupTransparency(domCOLLADA* root)
  498. {
  499. // Transparency is another example of something simple made complicated by
  500. // Collada. There are two (optional) elements that determine transparency:
  501. //
  502. // <transparent>: a color
  503. // <transparency>: a percentage applied to the color values
  504. //
  505. // Additionally, <transparent> has an optional "opaque" attribute that changes
  506. // the way transparency is determined. If set to A_ONE (the default), only the
  507. // alpha value of the transparent color is used, and a value of "1" means fully
  508. // opaque. If set to RGB_ZERO, only the RGB values of transparent are used, and
  509. // a value of "0" means fully opaque.
  510. //
  511. // To further complicate matters, Google Sketchup (all versions) and FeelingSoftware
  512. // ColladaMax (pre 3.03) export materials with the transparency element inverted
  513. // (1-transparency)
  514. // Get the <authoring_tool> string
  515. const char *authoringTool = "";
  516. if (const domAsset* asset = root->getAsset()) {
  517. for (S32 iContrib = 0; iContrib < asset->getContributor_array().getCount(); iContrib++) {
  518. const domAsset::domContributor* contrib = asset->getContributor_array()[iContrib];
  519. if (contrib->getAuthoring_tool()) {
  520. authoringTool = contrib->getAuthoring_tool()->getValue();
  521. break;
  522. }
  523. }
  524. }
  525. // Check for a match with the known problem-tools
  526. bool invertTransparency = false;
  527. const char *toolNames[] = { "FBX COLLADA exporter", "Google SketchUp",
  528. "Illusoft Collada Exporter", "FCollada" };
  529. for (S32 iName = 0; iName < (sizeof(toolNames)/sizeof(toolNames[0])); iName++) {
  530. if (dStrstr(authoringTool, toolNames[iName])) {
  531. invertTransparency = true;
  532. break;
  533. }
  534. }
  535. if (!invertTransparency)
  536. return;
  537. // Invert transparency as required for each effect
  538. for (S32 iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) {
  539. domLibrary_effects* lib = root->getLibrary_effects_array()[iLib];
  540. for (S32 iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) {
  541. domEffect* effect = lib->getEffect_array()[iEffect];
  542. // Find the common profile
  543. const domProfile_COMMON* commonProfile = findEffectCommonProfile(effect);
  544. if (!commonProfile)
  545. continue;
  546. domCommon_transparent_type* transparent = 0;
  547. if (commonProfile->getTechnique()->getConstant())
  548. transparent = commonProfile->getTechnique()->getConstant()->getTransparent();
  549. else if (commonProfile->getTechnique()->getLambert())
  550. transparent = commonProfile->getTechnique()->getLambert()->getTransparent();
  551. else if (commonProfile->getTechnique()->getPhong())
  552. transparent = commonProfile->getTechnique()->getPhong()->getTransparent();
  553. else if (commonProfile->getTechnique()->getBlinn())
  554. transparent = commonProfile->getTechnique()->getBlinn()->getTransparent();
  555. if (!transparent)
  556. continue;
  557. // If the shader "opaque" attribute is not specified, set it to
  558. // RGB_ZERO (the opposite of the Collada default), as this is what
  559. // the bad exporter tools seem to assume.
  560. if (!transparent->isAttributeSet("opaque")) {
  561. daeErrorHandler::get()->handleWarning(avar("Setting <transparent> "
  562. "\"opaque\" attribute to RGB_ZERO for %s <effect>", effect->getID()));
  563. transparent->setOpaque(FX_OPAQUE_ENUM_RGB_ZERO);
  564. }
  565. }
  566. }
  567. }
  568. static void conditioner_checkBindShapeMatrix(domCOLLADA* root)
  569. {
  570. for (S32 iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) {
  571. domLibrary_controllers* lib = root->getLibrary_controllers_array().get(iLib);
  572. for (S32 iCon = 0; iCon < lib->getController_array().getCount(); iCon++) {
  573. domController* con = lib->getController_array().get(iCon);
  574. if (con->getSkin() && con->getSkin()->getBind_shape_matrix()) {
  575. MatrixF mat = vecToMatrixF<domMatrix>(con->getSkin()->getBind_shape_matrix()->getValue());
  576. if (!mat.fullInverse()) {
  577. daeErrorHandler::get()->handleWarning(avar("<bind_shape_matrix> "
  578. "in %s <controller> is not invertible (may cause problems with "
  579. "skinning)", con->getID()));
  580. }
  581. }
  582. }
  583. }
  584. }
  585. static void conditioner_fixupVertexWeightJoints(domCOLLADA* root)
  586. {
  587. for (S32 iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) {
  588. domLibrary_controllers* lib = root->getLibrary_controllers_array().get(iLib);
  589. for (S32 iCon = 0; iCon < lib->getController_array().getCount(); iCon++) {
  590. domController* con = lib->getController_array().get(iCon);
  591. if (con->getSkin() && con->getSkin()->getVertex_weights())
  592. {
  593. domInputLocalOffset_Array& vw_inputs = con->getSkin()->getVertex_weights()->getInput_array();
  594. for (S32 vInput = 0; vInput < vw_inputs.getCount(); vInput++) {
  595. domInputLocalOffset *vw_input = vw_inputs.get(vInput);
  596. if (dStrEqual(vw_input->getSemantic(), "JOINT")) {
  597. // Check if this input points at a float array (bad)
  598. domSource* vw_source = daeSafeCast<domSource>(vw_input->getSource().getElement());
  599. if (vw_source->getFloat_array()) {
  600. // Copy the value from the <joints> JOINTS input instead
  601. domInputLocal_Array& joint_inputs = con->getSkin()->getJoints()->getInput_array();
  602. for (S32 jInput = 0; jInput < joint_inputs.getCount(); jInput++) {
  603. domInputLocal *joint_input = joint_inputs.get(jInput);
  604. if (dStrEqual(joint_input->getSemantic(), "JOINT")) {
  605. vw_input->setSource(joint_input->getSource());
  606. break;
  607. }
  608. }
  609. }
  610. }
  611. }
  612. }
  613. }
  614. }
  615. }
  616. static void conditioner_createDefaultClip(domCOLLADA* root)
  617. {
  618. // Check if the document has any <animation_clip>s
  619. for (S32 iLib = 0; iLib < root->getLibrary_animation_clips_array().getCount(); iLib++) {
  620. if (root->getLibrary_animation_clips_array()[iLib]->getAnimation_clip_array().getCount())
  621. return;
  622. }
  623. // Get all top-level <animation>s into an array
  624. domAnimation_Array animations;
  625. for (S32 iAnimLib = 0; iAnimLib < root->getLibrary_animations_array().getCount(); iAnimLib++) {
  626. const domLibrary_animations* libraryAnims = root->getLibrary_animations_array()[iAnimLib];
  627. for (S32 iAnim = 0; iAnim < libraryAnims->getAnimation_array().getCount(); iAnim++)
  628. animations.append(libraryAnims->getAnimation_array()[iAnim]);
  629. }
  630. if (!animations.getCount())
  631. return;
  632. daeErrorHandler::get()->handleWarning("Creating cyclic animation clip to "
  633. "hold all animations");
  634. // Get animation_clip library (create one if necessary)
  635. if (!root->getLibrary_animation_clips_array().getCount()) {
  636. root->createAndPlace("library_animation_clips");
  637. }
  638. domLibrary_animation_clips* libraryClips = root->getLibrary_animation_clips_array()[0];
  639. // Create new animation_clip for the default sequence
  640. CREATE_ELEMENT(libraryClips, animation_clip, domAnimation_clip)
  641. animation_clip->setName("ambient");
  642. animation_clip->setId("dummy_ambient_clip");
  643. animation_clip->setStart(0);
  644. animation_clip->setEnd(0);
  645. // Add all top_level animations to the clip (sub-animations will be included
  646. // when the clip is procesed)
  647. for (S32 iAnim = 0; iAnim < animations.getCount(); iAnim++) {
  648. if (!animations[iAnim]->getId())
  649. animations[iAnim]->setId(avar("dummy-animation-id%d", iAnim));
  650. CREATE_ELEMENT(animation_clip, instance_animation, domInstanceWithExtra)
  651. std::string url(std::string("#") + animations[iAnim]->getId());
  652. instance_animation->setUrl(url.c_str());
  653. }
  654. // Add the 'Torque' profile to specify the 'Cyclic' flag
  655. CREATE_ELEMENT(animation_clip, extra, domExtra)
  656. CREATE_ELEMENT(extra, technique, domTechnique)
  657. CREATE_ELEMENT(technique, any, domAny)
  658. technique->setProfile("Torque");
  659. any->setElementName("cyclic");
  660. any->setValue("1");
  661. }
  662. static void conditioner_fixupAnimation(domAnimation* anim)
  663. {
  664. S32 visibilityLen = dStrlen("/visibility");
  665. for (S32 iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) {
  666. // Get the animation elements: <channel>, <sampler>
  667. domChannel* channel = anim->getChannel_array()[iChannel];
  668. domSampler* sampler = daeSafeCast<domSampler>(channel->getSource().getElement());
  669. if (!sampler)
  670. continue;
  671. /*
  672. // If using a spline interpolation type but no tangents are specified,
  673. // fall back to LINEAR interpolation.
  674. bool isSpline = false;
  675. bool foundInTangent = false;
  676. bool foundOutTangent = false;
  677. for (int iInput = 0; iInput < sampler->getInput_array().getCount(); iInput++) {
  678. const char *semantic = sampler->getInput_array()[iInput]->getSemantic();
  679. if (dStrEqual(semantic, "INTERPOLATION")) {
  680. if (
  681. }
  682. if (dStrEqual(semantic, "IN_TANGENT"))
  683. foundInTangent = true;
  684. if (dStrEqual(semantic, "OUT_TANGENT"))
  685. foundOutTangent = true;
  686. }
  687. if (isSpline && (!foundInTangent || !foundOutTangent)) {
  688. daeErrorHandler::get()->handleWarning(avar("%s type interpolation "
  689. "specified for %s, but IN/OUT TANGENTS are not provided. Using "
  690. "LINEAR interpolation instead.");
  691. }
  692. */
  693. // Find the animation channel target
  694. daeSIDResolver resolver(channel, channel->getTarget());
  695. daeElement* target = resolver.getElement();
  696. if (!target) {
  697. // Some exporters generate visibility animations but don't add the
  698. // FCOLLADA extension, so the target doesn't actually exist! Detect
  699. // this situation and add the extension manually so the animation
  700. // still works.
  701. if (dStrEndsWith(channel->getTarget(), "/visibility")) {
  702. // Get parent SID string
  703. char *parentSID = dStrdup(channel->getTarget());
  704. parentSID[dStrlen(parentSID) - visibilityLen] = '\0';
  705. // Find the parent element (should be a <node>)
  706. daeSIDResolver parentResolver(channel, parentSID);
  707. daeElement* parent = parentResolver.getElement();
  708. delete [] parentSID;
  709. if (parent && (parent->getElementType() == COLLADA_TYPE::NODE)) {
  710. // Create the FCOLLADA extension
  711. daeErrorHandler::get()->handleWarning(avar("Creating missing "
  712. "visibility animation target: %s", channel->getTarget()));
  713. // Check if the <visibility> element exists but is missing the SID
  714. daeElement* vis = parent->getDescendant("visibility");
  715. if (vis)
  716. {
  717. vis->setAttribute("sid", "visibility");
  718. }
  719. else
  720. {
  721. CREATE_ELEMENT(parent, extra, domExtra)
  722. CREATE_ELEMENT(extra, technique, domTechnique)
  723. CREATE_ELEMENT(technique, any, domAny)
  724. technique->setProfile("FCOLLADA");
  725. any->setElementName("visibility");
  726. any->setAttribute("sid", "visibility");
  727. any->setValue(""); // real initial value will be set when animation is processed in ColladaShapeLoader::processAnimation
  728. }
  729. }
  730. }
  731. }
  732. }
  733. // Process child animations
  734. for (S32 iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++)
  735. conditioner_fixupAnimation(anim->getAnimation_array()[iAnim]);
  736. }
  737. /// Apply the set of model conditioners
  738. void ColladaUtils::applyConditioners(domCOLLADA* root)
  739. {
  740. //--------------------------------------------------------------------------
  741. // The built-in MAX FBX exporter specifies an <image> SID in the <texture>
  742. // "texture" attribute instead of a <newparam> SID. Detect and fix this.
  743. conditioner_fixupTextureSIDs(root);
  744. //--------------------------------------------------------------------------
  745. // The built-in MAX FBX exporter also generates invalid URI paths in the
  746. // <image>.<init_from> tag, so fix that up too.
  747. conditioner_fixupImageURIs(root);
  748. //--------------------------------------------------------------------------
  749. // Many exporters get transparency backwards. Check if the model was exported
  750. // by one with a known issue and correct it.
  751. conditioner_fixupTransparency(root);
  752. //--------------------------------------------------------------------------
  753. // Some exporters (AutoDesk) generate invalid bind_shape matrices. Warn if
  754. // the bind_shape_matrix is not invertible.
  755. conditioner_checkBindShapeMatrix(root);
  756. //--------------------------------------------------------------------------
  757. // The PoserPro exporter points the <vertex_weights> JOINT input to the
  758. // inverse bind matrices instead of the joint names array. Detect and fix it.
  759. conditioner_fixupVertexWeightJoints(root);
  760. //--------------------------------------------------------------------------
  761. // If the model contains <animation>s but no <animation_clip>s, just put all
  762. // top level animations into a single clip.
  763. conditioner_createDefaultClip(root);
  764. //--------------------------------------------------------------------------
  765. // Apply some animation fixups:
  766. // 1) Some exporters (eg. Blender) generate "BEZIER" type animation curves,
  767. // but do not specify the IN and OUT tangent data arrays. Detect this and
  768. // fall back to LINEAR interpolation.
  769. // 2) Some exporters generate visibility animations but don't add the FCOLLADA
  770. // extension, so the target doesn't actually exist! Detect this situation
  771. // and add the extension manually so the animation still works.
  772. for (S32 iLib = 0; iLib < root->getLibrary_animations_array().getCount(); iLib++) {
  773. const domLibrary_animations* lib = root->getLibrary_animations_array()[iLib];
  774. for (S32 iAnim = 0; iAnim < lib->getAnimation_array().getCount(); iAnim++)
  775. conditioner_fixupAnimation(lib->getAnimation_array()[iAnim]);
  776. }
  777. }
  778. Torque::Path ColladaUtils::findTexture(const Torque::Path& diffuseMap)
  779. {
  780. Vector<Torque::Path> foundPaths;
  781. GBitmap::sFindFiles(diffuseMap, &foundPaths);
  782. if (foundPaths.size() > 0)
  783. return Torque::Path(foundPaths[0]);
  784. // If unable to load texture in current directory
  785. // look in the parent directory. But never look in the root.
  786. Torque::Path newPath(diffuseMap);
  787. String filePath = newPath.getPath();
  788. String::SizeType slash = filePath.find('/', filePath.length(), String::Right);
  789. if (slash != String::NPos)
  790. {
  791. slash = filePath.find('/', filePath.length(), String::Right);
  792. if (slash != String::NPos)
  793. {
  794. String truncPath = filePath.substr(0, slash);
  795. newPath.setPath(truncPath);
  796. return findTexture(newPath);
  797. }
  798. }
  799. return String::EmptyString;
  800. }
  801. void ColladaUtils::exportColladaHeader(tinyxml2::XMLElement* rootNode)
  802. {
  803. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  804. tinyxml2::XMLElement* assetNode = doc->NewElement("asset");
  805. rootNode->LinkEndChild(assetNode);
  806. tinyxml2::XMLElement* contributorNode = doc->NewElement("contributor");
  807. assetNode->LinkEndChild(contributorNode);
  808. tinyxml2::XMLElement* authorNode = doc->NewElement("author");
  809. contributorNode->LinkEndChild(authorNode);
  810. tinyxml2::XMLText* authorNodeText = doc->NewText("Torque3D MIT User");
  811. authorNode->LinkEndChild(authorNodeText);
  812. tinyxml2::XMLElement* authoringToolNode = doc->NewElement("authoring_tool");
  813. contributorNode->LinkEndChild(authoringToolNode);
  814. tinyxml2::XMLText* authorText = doc->NewText(avar("%s %s Object Exporter", getEngineProductString(), getVersionString()));
  815. authoringToolNode->LinkEndChild(authorText);
  816. //tinyxml2::XMLElement* commentsNode = doc->NewElement("comments");
  817. //contributorNode->LinkEndChild(commentsNode);
  818. // Get the current time
  819. Platform::LocalTime lt;
  820. Platform::getLocalTime(lt);
  821. String localTime = Platform::localTimeToString(lt);
  822. localTime.replace('\t', ' ');
  823. tinyxml2::XMLElement* createdNode = doc->NewElement("created");
  824. assetNode->LinkEndChild(createdNode);
  825. tinyxml2::XMLText* createdText = doc->NewText(avar("%s", localTime.c_str()));
  826. createdNode->LinkEndChild(createdText);
  827. tinyxml2::XMLElement* modifiedNode = doc->NewElement("modified");
  828. assetNode->LinkEndChild(modifiedNode);
  829. tinyxml2::XMLText* modifiedText = doc->NewText(avar("%s", localTime.c_str()));
  830. modifiedNode->LinkEndChild(modifiedText);
  831. //tinyxml2::XMLElement* revisionNode = doc->NewElement("revision");
  832. //assetNode->LinkEndChild(revisionNode);
  833. //tinyxml2::XMLElement* titleNode = doc->NewElement("title");
  834. //assetNode->LinkEndChild(titleNode);
  835. //tinyxml2::XMLElement* subjectNode = doc->NewElement("subject");
  836. //assetNode->LinkEndChild(subjectNode);
  837. //tinyxml2::XMLElement* keywordsNode = doc->NewElement("keywords");
  838. //assetNode->LinkEndChild(keywordsNode);
  839. // Torque uses Z_UP with 1 unit equal to 1 meter by default
  840. tinyxml2::XMLElement* unitNode = doc->NewElement("unit");
  841. assetNode->LinkEndChild(unitNode);
  842. unitNode->SetAttribute("name", "meter");
  843. unitNode->SetAttribute("meter", "1");
  844. tinyxml2::XMLElement* axisNode = doc->NewElement("up_axis");
  845. assetNode->LinkEndChild(axisNode);
  846. tinyxml2::XMLText* axisText = doc->NewText("Z_UP");
  847. axisNode->LinkEndChild(axisText);
  848. }
  849. void ColladaUtils::exportColladaMaterials(tinyxml2::XMLElement* rootNode, const OptimizedPolyList& mesh, Vector<String>& matNames, const Torque::Path& colladaFile)
  850. {
  851. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  852. // First the image library
  853. tinyxml2::XMLElement* imgLibNode = doc->NewElement("library_images");
  854. rootNode->LinkEndChild(imgLibNode);
  855. for (U32 i = 0; i < mesh.mMaterialList.size(); i++)
  856. {
  857. BaseMatInstance* baseInst = mesh.mMaterialList[i];
  858. matNames.push_back(String::ToString("Material%d", i));
  859. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  860. if (!mat)
  861. continue;
  862. String diffuseMap;
  863. if (mat->getName() && mat->getName()[0])
  864. matNames.last() = mat->mMapTo;
  865. // Handle an auto-generated "Default Material" specially
  866. if (mat->isAutoGenerated())
  867. {
  868. Torque::Path diffusePath;
  869. if (mat->mDiffuseMapName[0] != StringTable->EmptyString())
  870. diffusePath = Torque::Path(mat->mDiffuseMapName[0]);
  871. else
  872. diffusePath = String("warningMat");
  873. matNames.last() = diffusePath.getFileName();
  874. diffuseMap += diffusePath.getFullFileName();
  875. }
  876. else
  877. {
  878. if (mat->mDiffuseMapName[0] != StringTable->EmptyString())
  879. diffuseMap += Torque::Path(mat->mDiffuseMapName[0]);
  880. else
  881. diffuseMap += "warningMat";
  882. }
  883. Torque::Path diffusePath = findTexture(colladaFile.getPath() + "/" + diffuseMap);
  884. // If we didn't get a path
  885. if (diffusePath.getFullPath().isNotEmpty())
  886. diffuseMap = Torque::Path::MakeRelativePath(diffusePath, colladaFile);
  887. tinyxml2::XMLElement* imageNode = doc->NewElement("image");
  888. imgLibNode->LinkEndChild(imageNode);
  889. imageNode->SetAttribute("id", avar("%s", matNames.last().c_str()));
  890. imageNode->SetAttribute("name", avar("%s", matNames.last().c_str()));
  891. tinyxml2::XMLElement* initNode = doc->NewElement("init_from");
  892. imageNode->LinkEndChild(initNode);
  893. tinyxml2::XMLText* initText = doc->NewText(avar("file://%s", diffuseMap.c_str())); // "the file://" is needed to load the texture in some old apps (ex: 3ds Max 2009)
  894. initNode->LinkEndChild(initText);
  895. }
  896. // Next the effects library
  897. tinyxml2::XMLElement* effectLibNode = doc->NewElement("library_effects");
  898. rootNode->LinkEndChild(effectLibNode);
  899. for (U32 i = 0; i < mesh.mMaterialList.size(); i++)
  900. {
  901. BaseMatInstance* baseInst = mesh.mMaterialList[i];
  902. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  903. if (!mat)
  904. continue;
  905. tinyxml2::XMLElement* effectNode = doc->NewElement("effect");
  906. effectLibNode->LinkEndChild(effectNode);
  907. effectNode->SetAttribute("id", avar("%s-effect", matNames[i].c_str()));
  908. effectNode->SetAttribute("name", avar("%s-effect", matNames[i].c_str()));
  909. tinyxml2::XMLElement* profileNode = doc->NewElement("profile_COMMON");
  910. effectNode->LinkEndChild(profileNode);
  911. // ---------------------------
  912. tinyxml2::XMLElement* newParamNode = doc->NewElement("newparam");
  913. profileNode->LinkEndChild(newParamNode);
  914. newParamNode->SetAttribute("sid", avar("%s-surface", matNames[i].c_str()));
  915. tinyxml2::XMLElement* surfaceNode = doc->NewElement("surface");
  916. newParamNode->LinkEndChild(surfaceNode);
  917. surfaceNode->SetAttribute("type", "2D");
  918. tinyxml2::XMLElement* initNode2 = doc->NewElement("init_from");
  919. surfaceNode->LinkEndChild(initNode2);
  920. tinyxml2::XMLText* init2Text = doc->NewText(avar("%s", matNames[i].c_str()));
  921. initNode2->LinkEndChild(init2Text);
  922. tinyxml2::XMLElement* formatNode = doc->NewElement("format");
  923. surfaceNode->LinkEndChild(formatNode);
  924. tinyxml2::XMLText* formatText = doc->NewText("A8R8G8B8");
  925. formatNode->LinkEndChild(formatText);
  926. // ---------------------------
  927. tinyxml2::XMLElement* newParam2Node = doc->NewElement("newparam");
  928. profileNode->LinkEndChild(newParam2Node);
  929. newParam2Node->SetAttribute("sid", avar("%s-sampler", matNames[i].c_str()));
  930. tinyxml2::XMLElement* sampler2DNode = doc->NewElement("sampler2D");
  931. newParam2Node->LinkEndChild(sampler2DNode);
  932. tinyxml2::XMLElement* sourceSampler2DNode = doc->NewElement("source");
  933. sampler2DNode->LinkEndChild(sourceSampler2DNode);
  934. tinyxml2::XMLText* sourceSampler2DText = doc->NewText(avar("%s-surface", matNames[i].c_str()));
  935. sourceSampler2DNode->LinkEndChild(sourceSampler2DText);
  936. // ---------------------------
  937. tinyxml2::XMLElement* techniqueNode = doc->NewElement("technique");
  938. profileNode->LinkEndChild(techniqueNode);
  939. techniqueNode->SetAttribute("sid", "common");
  940. tinyxml2::XMLElement* blinnNode = doc->NewElement("blinn");
  941. techniqueNode->LinkEndChild(blinnNode);
  942. // ---------------------------
  943. tinyxml2::XMLElement* emissionNode = doc->NewElement("emission");
  944. blinnNode->LinkEndChild(emissionNode);
  945. tinyxml2::XMLElement* colorEmissionNode = doc->NewElement("color");
  946. emissionNode->LinkEndChild(colorEmissionNode);
  947. colorEmissionNode->SetAttribute("sid", "emission");
  948. tinyxml2::XMLText* colorEmissionNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  949. colorEmissionNode->LinkEndChild(colorEmissionNodeText);
  950. // ---------------------------
  951. tinyxml2::XMLElement* ambientNode = doc->NewElement("ambient");
  952. blinnNode->LinkEndChild(ambientNode);
  953. tinyxml2::XMLElement* colorAmbientNode = doc->NewElement("color");
  954. ambientNode->LinkEndChild(colorAmbientNode);
  955. colorAmbientNode->SetAttribute("sid", "ambient");
  956. tinyxml2::XMLText* colorAmbientNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  957. colorAmbientNode->LinkEndChild(colorAmbientNodeText);
  958. // ---------------------------
  959. tinyxml2::XMLElement* diffuseNode = doc->NewElement("diffuse");
  960. blinnNode->LinkEndChild(diffuseNode);
  961. tinyxml2::XMLElement* textureDiffuseNode = doc->NewElement("texture");
  962. diffuseNode->LinkEndChild(textureDiffuseNode);
  963. textureDiffuseNode->SetAttribute("texture", avar("%s-sampler", matNames[i].c_str()));
  964. textureDiffuseNode->SetAttribute("texcoord", "UVMap");
  965. // Extra info useful for getting the texture to show up correctly in MAYA and 3DS Max
  966. tinyxml2::XMLElement* extraNode = doc->NewElement("extra");
  967. textureDiffuseNode->LinkEndChild(extraNode);
  968. tinyxml2::XMLElement* extraTechNode = doc->NewElement("technique");
  969. extraNode->LinkEndChild(extraTechNode);
  970. extraTechNode->SetAttribute("profile", "MAYA");
  971. tinyxml2::XMLElement* extraWrapUNode = doc->NewElement("wrapU");
  972. extraTechNode->LinkEndChild(extraWrapUNode);
  973. extraWrapUNode->SetAttribute("sid", "wrapU0");
  974. tinyxml2::XMLText* extraWrapUText = doc->NewText("TRUE");
  975. extraWrapUNode->LinkEndChild(extraWrapUText);
  976. tinyxml2::XMLElement* extraWrapVNode = doc->NewElement("wrapV");
  977. extraTechNode->LinkEndChild(extraWrapVNode);
  978. extraWrapVNode->SetAttribute("sid", "wrapV0");
  979. tinyxml2::XMLText* extraWrapVText = doc->NewText("TRUE");
  980. extraWrapVNode->LinkEndChild(extraWrapVText);
  981. tinyxml2::XMLElement* extraBlendNode = doc->NewElement("blend_mode");
  982. extraTechNode->LinkEndChild(extraBlendNode);
  983. tinyxml2::XMLText* extraBlendText = doc->NewText("ADD");
  984. extraBlendNode->LinkEndChild(extraBlendText);
  985. // ---------------------------
  986. tinyxml2::XMLElement* specularNode = doc->NewElement("specular");
  987. blinnNode->LinkEndChild(specularNode);
  988. tinyxml2::XMLElement* colorSpecularNode = doc->NewElement("color");
  989. specularNode->LinkEndChild(colorSpecularNode);
  990. colorSpecularNode->SetAttribute("sid", "specular");
  991. tinyxml2::XMLText* colorSpecularNodeText = doc->NewText("0.5 0.5 0.5 1.0");
  992. colorSpecularNode->LinkEndChild(colorSpecularNodeText);
  993. // ---------------------------
  994. tinyxml2::XMLElement* shininessNode = doc->NewElement("shininess");
  995. blinnNode->LinkEndChild(shininessNode);
  996. tinyxml2::XMLElement* colorShininessNode = doc->NewElement("float");
  997. shininessNode->LinkEndChild(colorShininessNode);
  998. colorShininessNode->SetAttribute("sid", "shininess");
  999. tinyxml2::XMLText* colorShininessNodeText = doc->NewText("1.0");
  1000. colorShininessNode->LinkEndChild(colorShininessNodeText);
  1001. // ---------------------------
  1002. tinyxml2::XMLElement* reflectiveNode = doc->NewElement("reflective");
  1003. blinnNode->LinkEndChild(reflectiveNode);
  1004. tinyxml2::XMLElement* colorReflectiveNode = doc->NewElement("color");
  1005. reflectiveNode->LinkEndChild(colorReflectiveNode);
  1006. colorReflectiveNode->SetAttribute("sid", "reflective");
  1007. tinyxml2::XMLText* colorReflectiveNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  1008. colorReflectiveNode->LinkEndChild(colorReflectiveNodeText);
  1009. // ---------------------------
  1010. tinyxml2::XMLElement* reflectivityNode = doc->NewElement("reflectivity");
  1011. blinnNode->LinkEndChild(reflectivityNode);
  1012. tinyxml2::XMLElement* floatReflectivityNode = doc->NewElement("float");
  1013. reflectivityNode->LinkEndChild(floatReflectivityNode);
  1014. floatReflectivityNode->SetAttribute("sid", "reflectivity");
  1015. tinyxml2::XMLText* floatReflectivityText = doc->NewText("0.5");
  1016. floatReflectivityNode->LinkEndChild(floatReflectivityText);
  1017. // ---------------------------
  1018. tinyxml2::XMLElement* transparentNode = doc->NewElement("transparent");
  1019. blinnNode->LinkEndChild(transparentNode);
  1020. transparentNode->SetAttribute("opaque", "RGB_ZERO");
  1021. tinyxml2::XMLElement* colorTransparentNode = doc->NewElement("color");
  1022. transparentNode->LinkEndChild(colorTransparentNode);
  1023. colorTransparentNode->SetAttribute("sid", "transparent");
  1024. tinyxml2::XMLText* colorTransparentNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  1025. colorTransparentNode->LinkEndChild(colorTransparentNodeText);
  1026. // ---------------------------
  1027. tinyxml2::XMLElement* transparencyNode = doc->NewElement("transparency");
  1028. blinnNode->LinkEndChild(transparencyNode);
  1029. tinyxml2::XMLElement* floatTransparencyNode = doc->NewElement("float");
  1030. transparencyNode->LinkEndChild(floatTransparencyNode);
  1031. floatTransparencyNode->SetAttribute("sid", "transparency");
  1032. tinyxml2::XMLText* floatTransparencyText = doc->NewText("0.0");
  1033. floatTransparencyNode->LinkEndChild(floatTransparencyText);
  1034. // ---------------------------
  1035. tinyxml2::XMLElement* refractionNode = doc->NewElement("index_of_refraction");
  1036. blinnNode->LinkEndChild(refractionNode);
  1037. tinyxml2::XMLElement* colorRefractionNode = doc->NewElement("float");
  1038. refractionNode->LinkEndChild(colorRefractionNode);
  1039. colorRefractionNode->SetAttribute("sid", "index_of_refraction");
  1040. tinyxml2::XMLText* colorRefractionNodeText = doc->NewText("1");
  1041. colorRefractionNode->LinkEndChild(colorRefractionNodeText);
  1042. }
  1043. // Finally the material library
  1044. tinyxml2::XMLElement* matLibNode = doc->NewElement("library_materials");
  1045. rootNode->LinkEndChild(matLibNode);
  1046. for (U32 i = 0; i < mesh.mMaterialList.size(); i++)
  1047. {
  1048. BaseMatInstance* baseInst = mesh.mMaterialList[i];
  1049. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  1050. if (!mat)
  1051. continue;
  1052. tinyxml2::XMLElement* materialNode = doc->NewElement("material");
  1053. matLibNode->LinkEndChild(materialNode);
  1054. materialNode->SetAttribute("id", avar("%s-material", matNames[i].c_str()));
  1055. materialNode->SetAttribute("name", matNames[i].c_str());
  1056. tinyxml2::XMLElement* instEffectNode = doc->NewElement("instance_effect");
  1057. materialNode->LinkEndChild(instEffectNode);
  1058. instEffectNode->SetAttribute("url", avar("#%s-effect", matNames[i].c_str()));
  1059. }
  1060. }
  1061. void ColladaUtils::exportColladaMaterials(tinyxml2::XMLElement* rootNode, const ExportData& exportData, const Torque::Path& colladaFile)
  1062. {
  1063. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  1064. // First the image library
  1065. tinyxml2::XMLElement* imgLibNode = doc->NewElement("library_images");
  1066. rootNode->LinkEndChild(imgLibNode);
  1067. Vector<String> matNames;
  1068. for (U32 i = 0; i < exportData.materials.size(); i++)
  1069. {
  1070. BaseMatInstance* baseInst = exportData.materials[i];
  1071. matNames.push_back(String::ToString("Material%d", i));
  1072. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  1073. if (!mat)
  1074. continue;
  1075. String diffuseMap;
  1076. if (mat->getName() && mat->getName()[0])
  1077. matNames.last() = mat->mMapTo;
  1078. // Handle an auto-generated "Default Material" specially
  1079. if (mat->isAutoGenerated())
  1080. {
  1081. Torque::Path diffusePath;
  1082. if (mat->mDiffuseMapName[0] != StringTable->EmptyString())
  1083. diffusePath = Torque::Path(mat->mDiffuseMapName[0]);
  1084. else
  1085. diffusePath = String("warningMat");
  1086. matNames.last() = diffusePath.getFileName();
  1087. diffuseMap += diffusePath.getFullFileName();
  1088. }
  1089. else
  1090. {
  1091. if (mat->mDiffuseMapName[0] != StringTable->EmptyString())
  1092. diffuseMap += Torque::Path(mat->mDiffuseMapName[0]);
  1093. else
  1094. diffuseMap += "warningMat";
  1095. }
  1096. Torque::Path diffusePath = findTexture(colladaFile.getPath() + "/" + diffuseMap);
  1097. // If we didn't get a path
  1098. if (diffusePath.getFullPath().isNotEmpty())
  1099. diffuseMap = Torque::Path::MakeRelativePath(diffusePath, colladaFile);
  1100. tinyxml2::XMLElement* imageNode = doc->NewElement("image");
  1101. imgLibNode->LinkEndChild(imageNode);
  1102. imageNode->SetAttribute("id", avar("%s", matNames.last().c_str()));
  1103. imageNode->SetAttribute("name", avar("%s", matNames.last().c_str()));
  1104. tinyxml2::XMLElement* initNode = doc->NewElement("init_from");
  1105. imageNode->LinkEndChild(initNode);
  1106. tinyxml2::XMLText* initText = doc->NewText(avar("file://%s", diffuseMap.c_str())); // "the file://" is needed to load the texture in some old apps (ex: 3ds Max 2009)
  1107. initNode->LinkEndChild(initText);
  1108. }
  1109. // Next the effects library
  1110. tinyxml2::XMLElement* effectLibNode = doc->NewElement("library_effects");
  1111. rootNode->LinkEndChild(effectLibNode);
  1112. for (U32 i = 0; i < exportData.materials.size(); i++)
  1113. {
  1114. BaseMatInstance* baseInst = exportData.materials[i];
  1115. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  1116. if (!mat)
  1117. continue;
  1118. tinyxml2::XMLElement* effectNode = doc->NewElement("effect");
  1119. effectLibNode->LinkEndChild(effectNode);
  1120. effectNode->SetAttribute("id", avar("%s-effect", matNames[i].c_str()));
  1121. effectNode->SetAttribute("name", avar("%s-effect", matNames[i].c_str()));
  1122. tinyxml2::XMLElement* profileNode = doc->NewElement("profile_COMMON");
  1123. effectNode->LinkEndChild(profileNode);
  1124. // ---------------------------
  1125. tinyxml2::XMLElement* newParamNode = doc->NewElement("newparam");
  1126. profileNode->LinkEndChild(newParamNode);
  1127. newParamNode->SetAttribute("sid", avar("%s-surface", matNames[i].c_str()));
  1128. tinyxml2::XMLElement* surfaceNode = doc->NewElement("surface");
  1129. newParamNode->LinkEndChild(surfaceNode);
  1130. surfaceNode->SetAttribute("type", "2D");
  1131. tinyxml2::XMLElement* initNode2 = doc->NewElement("init_from");
  1132. surfaceNode->LinkEndChild(initNode2);
  1133. tinyxml2::XMLText* init2Text = doc->NewText(avar("%s", matNames[i].c_str()));
  1134. initNode2->LinkEndChild(init2Text);
  1135. tinyxml2::XMLElement* formatNode = doc->NewElement("format");
  1136. surfaceNode->LinkEndChild(formatNode);
  1137. tinyxml2::XMLText* formatText = doc->NewText("A8R8G8B8");
  1138. formatNode->LinkEndChild(formatText);
  1139. // ---------------------------
  1140. tinyxml2::XMLElement* newParam2Node = doc->NewElement("newparam");
  1141. profileNode->LinkEndChild(newParam2Node);
  1142. newParam2Node->SetAttribute("sid", avar("%s-sampler", matNames[i].c_str()));
  1143. tinyxml2::XMLElement* sampler2DNode = doc->NewElement("sampler2D");
  1144. newParam2Node->LinkEndChild(sampler2DNode);
  1145. tinyxml2::XMLElement* sourceSampler2DNode = doc->NewElement("source");
  1146. sampler2DNode->LinkEndChild(sourceSampler2DNode);
  1147. tinyxml2::XMLText* sourceSampler2DText = doc->NewText(avar("%s-surface", matNames[i].c_str()));
  1148. sourceSampler2DNode->LinkEndChild(sourceSampler2DText);
  1149. // ---------------------------
  1150. tinyxml2::XMLElement* techniqueNode = doc->NewElement("technique");
  1151. profileNode->LinkEndChild(techniqueNode);
  1152. techniqueNode->SetAttribute("sid", "common");
  1153. tinyxml2::XMLElement* blinnNode = doc->NewElement("blinn");
  1154. techniqueNode->LinkEndChild(blinnNode);
  1155. // ---------------------------
  1156. tinyxml2::XMLElement* emissionNode = doc->NewElement("emission");
  1157. blinnNode->LinkEndChild(emissionNode);
  1158. tinyxml2::XMLElement* colorEmissionNode = doc->NewElement("color");
  1159. emissionNode->LinkEndChild(colorEmissionNode);
  1160. colorEmissionNode->SetAttribute("sid", "emission");
  1161. tinyxml2::XMLText* colorEmissionNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  1162. colorEmissionNode->LinkEndChild(colorEmissionNodeText);
  1163. // ---------------------------
  1164. tinyxml2::XMLElement* ambientNode = doc->NewElement("ambient");
  1165. blinnNode->LinkEndChild(ambientNode);
  1166. tinyxml2::XMLElement* colorAmbientNode = doc->NewElement("color");
  1167. ambientNode->LinkEndChild(colorAmbientNode);
  1168. colorAmbientNode->SetAttribute("sid", "ambient");
  1169. tinyxml2::XMLText* colorAmbientNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  1170. colorAmbientNode->LinkEndChild(colorAmbientNodeText);
  1171. // ---------------------------
  1172. tinyxml2::XMLElement* diffuseNode = doc->NewElement("diffuse");
  1173. blinnNode->LinkEndChild(diffuseNode);
  1174. tinyxml2::XMLElement* textureDiffuseNode = doc->NewElement("texture");
  1175. diffuseNode->LinkEndChild(textureDiffuseNode);
  1176. textureDiffuseNode->SetAttribute("texture", avar("%s-sampler", matNames[i].c_str()));
  1177. textureDiffuseNode->SetAttribute("texcoord", "UVMap");
  1178. // Extra info useful for getting the texture to show up correctly in MAYA and 3DS Max
  1179. tinyxml2::XMLElement* extraNode = doc->NewElement("extra");
  1180. textureDiffuseNode->LinkEndChild(extraNode);
  1181. tinyxml2::XMLElement* extraTechNode = doc->NewElement("technique");
  1182. extraNode->LinkEndChild(extraTechNode);
  1183. extraTechNode->SetAttribute("profile", "MAYA");
  1184. tinyxml2::XMLElement* extraWrapUNode = doc->NewElement("wrapU");
  1185. extraTechNode->LinkEndChild(extraWrapUNode);
  1186. extraWrapUNode->SetAttribute("sid", "wrapU0");
  1187. tinyxml2::XMLText* extraWrapUText = doc->NewText("TRUE");
  1188. extraWrapUNode->LinkEndChild(extraWrapUText);
  1189. tinyxml2::XMLElement* extraWrapVNode = doc->NewElement("wrapV");
  1190. extraTechNode->LinkEndChild(extraWrapVNode);
  1191. extraWrapVNode->SetAttribute("sid", "wrapV0");
  1192. tinyxml2::XMLText* extraWrapVText = doc->NewText("TRUE");
  1193. extraWrapVNode->LinkEndChild(extraWrapVText);
  1194. tinyxml2::XMLElement* extraBlendNode = doc->NewElement("blend_mode");
  1195. extraTechNode->LinkEndChild(extraBlendNode);
  1196. tinyxml2::XMLText* extraBlendText = doc->NewText("ADD");
  1197. extraBlendNode->LinkEndChild(extraBlendText);
  1198. // ---------------------------
  1199. tinyxml2::XMLElement* specularNode = doc->NewElement("specular");
  1200. blinnNode->LinkEndChild(specularNode);
  1201. tinyxml2::XMLElement* colorSpecularNode = doc->NewElement("color");
  1202. specularNode->LinkEndChild(colorSpecularNode);
  1203. colorSpecularNode->SetAttribute("sid", "specular");
  1204. tinyxml2::XMLText* colorSpecularNodeText = doc->NewText("0.5 0.5 0.5 1.0");
  1205. colorSpecularNode->LinkEndChild(colorSpecularNodeText);
  1206. // ---------------------------
  1207. tinyxml2::XMLElement* shininessNode = doc->NewElement("shininess");
  1208. blinnNode->LinkEndChild(shininessNode);
  1209. tinyxml2::XMLElement* colorShininessNode = doc->NewElement("float");
  1210. shininessNode->LinkEndChild(colorShininessNode);
  1211. colorShininessNode->SetAttribute("sid", "shininess");
  1212. tinyxml2::XMLText* colorShininessNodeText = doc->NewText("1.0");
  1213. colorShininessNode->LinkEndChild(colorShininessNodeText);
  1214. // ---------------------------
  1215. tinyxml2::XMLElement* reflectiveNode = doc->NewElement("reflective");
  1216. blinnNode->LinkEndChild(reflectiveNode);
  1217. tinyxml2::XMLElement* colorReflectiveNode = doc->NewElement("color");
  1218. reflectiveNode->LinkEndChild(colorReflectiveNode);
  1219. colorReflectiveNode->SetAttribute("sid", "reflective");
  1220. tinyxml2::XMLText* colorReflectiveNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  1221. colorReflectiveNode->LinkEndChild(colorReflectiveNodeText);
  1222. // ---------------------------
  1223. tinyxml2::XMLElement* reflectivityNode = doc->NewElement("reflectivity");
  1224. blinnNode->LinkEndChild(reflectivityNode);
  1225. tinyxml2::XMLElement* floatReflectivityNode = doc->NewElement("float");
  1226. reflectivityNode->LinkEndChild(floatReflectivityNode);
  1227. floatReflectivityNode->SetAttribute("sid", "reflectivity");
  1228. tinyxml2::XMLText* floatReflectivityText = doc->NewText("0.5");
  1229. floatReflectivityNode->LinkEndChild(floatReflectivityText);
  1230. // ---------------------------
  1231. tinyxml2::XMLElement* transparentNode = doc->NewElement("transparent");
  1232. blinnNode->LinkEndChild(transparentNode);
  1233. transparentNode->SetAttribute("opaque", "RGB_ZERO");
  1234. tinyxml2::XMLElement* colorTransparentNode = doc->NewElement("color");
  1235. transparentNode->LinkEndChild(colorTransparentNode);
  1236. colorTransparentNode->SetAttribute("sid", "transparent");
  1237. tinyxml2::XMLText* colorTransparentNodeText = doc->NewText("0.0 0.0 0.0 1.0");
  1238. colorTransparentNode->LinkEndChild(colorTransparentNodeText);
  1239. // ---------------------------
  1240. tinyxml2::XMLElement* transparencyNode = doc->NewElement("transparency");
  1241. blinnNode->LinkEndChild(transparencyNode);
  1242. tinyxml2::XMLElement* floatTransparencyNode = doc->NewElement("float");
  1243. transparencyNode->LinkEndChild(floatTransparencyNode);
  1244. floatTransparencyNode->SetAttribute("sid", "transparency");
  1245. tinyxml2::XMLText* floatTransparencyText = doc->NewText("0.0");
  1246. floatTransparencyNode->LinkEndChild(floatTransparencyText);
  1247. // ---------------------------
  1248. tinyxml2::XMLElement* refractionNode = doc->NewElement("index_of_refraction");
  1249. blinnNode->LinkEndChild(refractionNode);
  1250. tinyxml2::XMLElement* colorRefractionNode = doc->NewElement("float");
  1251. refractionNode->LinkEndChild(colorRefractionNode);
  1252. colorRefractionNode->SetAttribute("sid", "index_of_refraction");
  1253. tinyxml2::XMLText* colorRefractionNodeText = doc->NewText("1");
  1254. colorRefractionNode->LinkEndChild(colorRefractionNodeText);
  1255. }
  1256. // Finally the material library
  1257. tinyxml2::XMLElement* matLibNode = doc->NewElement("library_materials");
  1258. rootNode->LinkEndChild(matLibNode);
  1259. for (U32 i = 0; i < exportData.materials.size(); i++)
  1260. {
  1261. BaseMatInstance* baseInst = exportData.materials[i];
  1262. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  1263. if (!mat)
  1264. continue;
  1265. tinyxml2::XMLElement* materialNode = doc->NewElement("material");
  1266. matLibNode->LinkEndChild(materialNode);
  1267. materialNode->SetAttribute("id", avar("%s-material", matNames[i].c_str()));
  1268. materialNode->SetAttribute("name", matNames[i].c_str());
  1269. tinyxml2::XMLElement* instEffectNode = doc->NewElement("instance_effect");
  1270. materialNode->LinkEndChild(instEffectNode);
  1271. instEffectNode->SetAttribute("url", avar("#%s-effect", matNames[i].c_str()));
  1272. }
  1273. }
  1274. void ColladaUtils::exportColladaTriangles(tinyxml2::XMLElement* meshNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames)
  1275. {
  1276. tinyxml2::XMLDocument* doc = meshNode->GetDocument();
  1277. // Start at -1 so we will export polygons that do not have a material.
  1278. for (S32 i = -1; i < matNames.size(); i++)
  1279. {
  1280. // Calculate the number of triangles that uses this Material
  1281. U32 triangleCount = 0;
  1282. for (U32 j = 0; j < mesh.mPolyList.size(); j++)
  1283. {
  1284. const OptimizedPolyList::Poly& poly = mesh.mPolyList[j];
  1285. if (poly.material != i)
  1286. continue;
  1287. if (poly.vertexCount < 3)
  1288. continue;
  1289. if (poly.type == OptimizedPolyList::TriangleList ||
  1290. poly.type == OptimizedPolyList::TriangleFan ||
  1291. poly.type == OptimizedPolyList::TriangleStrip)
  1292. {
  1293. triangleCount += poly.vertexCount - 2;
  1294. }
  1295. else
  1296. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  1297. }
  1298. // Make sure that we are actually using this Material
  1299. if (triangleCount == 0)
  1300. continue;
  1301. tinyxml2::XMLElement* trianglesNode = doc->NewElement("triangles");
  1302. meshNode->LinkEndChild(trianglesNode);
  1303. trianglesNode->SetAttribute("material", ( i > -1 ) ? avar("%s-material", matNames[i].c_str()) : "" );
  1304. trianglesNode->SetAttribute("count", avar("%d", triangleCount));
  1305. tinyxml2::XMLElement* trianglesVertInputNode = doc->NewElement("input");
  1306. trianglesNode->LinkEndChild(trianglesVertInputNode);
  1307. trianglesVertInputNode->SetAttribute("semantic", "VERTEX");
  1308. trianglesVertInputNode->SetAttribute("source", avar("#%s-mesh-vertices", meshName.c_str()));
  1309. trianglesVertInputNode->SetAttribute("offset", "0");
  1310. tinyxml2::XMLElement* trianglesNormalInputNode = doc->NewElement("input");
  1311. trianglesNode->LinkEndChild(trianglesNormalInputNode);
  1312. trianglesNormalInputNode->SetAttribute("semantic", "NORMAL");
  1313. trianglesNormalInputNode->SetAttribute("source", avar("#%s-mesh-normals", meshName.c_str()));
  1314. trianglesNormalInputNode->SetAttribute("offset", "1");
  1315. tinyxml2::XMLElement* trianglesUV0InputNode = doc->NewElement("input");
  1316. trianglesNode->LinkEndChild(trianglesUV0InputNode);
  1317. trianglesUV0InputNode->SetAttribute("semantic", "TEXCOORD");
  1318. trianglesUV0InputNode->SetAttribute("source", avar("#%s-mesh-map-0", meshName.c_str()));
  1319. trianglesUV0InputNode->SetAttribute("offset", "2");
  1320. trianglesUV0InputNode->SetAttribute("set", "0");
  1321. tinyxml2::XMLElement* polyNode = doc->NewElement("p");
  1322. trianglesNode->LinkEndChild(polyNode);
  1323. Vector<U32> tempIndices;
  1324. tempIndices.reserve(4);
  1325. for (U32 j = 0; j < mesh.mPolyList.size(); j++)
  1326. {
  1327. const OptimizedPolyList::Poly& poly = mesh.mPolyList[j];
  1328. if (poly.vertexCount < 3)
  1329. continue;
  1330. if (poly.material != i)
  1331. continue;
  1332. tempIndices.setSize(poly.vertexCount);
  1333. dMemset(tempIndices.address(), 0, poly.vertexCount);
  1334. if (poly.type == OptimizedPolyList::TriangleStrip)
  1335. {
  1336. tempIndices[0] = 0;
  1337. U32 idx = 1;
  1338. for (U32 k = 1; k < poly.vertexCount; k += 2)
  1339. tempIndices[idx++] = k;
  1340. for (U32 k = ((poly.vertexCount - 1) & (~0x1)); k > 0; k -= 2)
  1341. tempIndices[idx++] = k;
  1342. }
  1343. else if (poly.type == OptimizedPolyList::TriangleList ||
  1344. poly.type == OptimizedPolyList::TriangleFan)
  1345. {
  1346. for (U32 k = 0; k < poly.vertexCount; k++)
  1347. tempIndices[k] = k;
  1348. }
  1349. else
  1350. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  1351. const U32& firstIdx = mesh.mIndexList[poly.vertexStart];
  1352. const OptimizedPolyList::VertIndex& firstVertIdx = mesh.mVertexList[firstIdx];
  1353. for (U32 k = 1; k < poly.vertexCount - 1; k++)
  1354. {
  1355. const U32& secondIdx = mesh.mIndexList[poly.vertexStart + tempIndices[k]];
  1356. const U32& thirdIdx = mesh.mIndexList[poly.vertexStart + tempIndices[k + 1]];
  1357. const OptimizedPolyList::VertIndex& secondVertIdx = mesh.mVertexList[secondIdx];
  1358. const OptimizedPolyList::VertIndex& thirdVertIdx = mesh.mVertexList[thirdIdx];
  1359. // Note the reversed winding on the triangles
  1360. const char* tri = avar("%d %d %d %d %d %d %d %d %d ",
  1361. thirdVertIdx.vertIdx, thirdVertIdx.normalIdx, thirdVertIdx.uv0Idx,
  1362. secondVertIdx.vertIdx, secondVertIdx.normalIdx, secondVertIdx.uv0Idx,
  1363. firstVertIdx.vertIdx, firstVertIdx.normalIdx, firstVertIdx.uv0Idx);
  1364. tinyxml2::XMLText* triangleText = doc->NewText(tri);
  1365. polyNode->LinkEndChild(triangleText);
  1366. }
  1367. }
  1368. }
  1369. }
  1370. void ColladaUtils::exportColladaTriangles(tinyxml2::XMLElement* meshNode, const ExportData& exportData, const U32 detailLevel, const String& meshName)
  1371. {
  1372. tinyxml2::XMLDocument* doc = meshNode->GetDocument();
  1373. // Calculate the number of triangles that uses this Material
  1374. U32 triangleCount = 0;
  1375. const ExportData::detailLevel* dl = &exportData.detailLevels[detailLevel];
  1376. for (S32 i = 0; i < dl->materialRefList.size(); i++)
  1377. {
  1378. int matIdx;
  1379. dl->materialRefList.tryGetValue(i, matIdx);
  1380. BaseMatInstance* baseInst = exportData.materials[matIdx];
  1381. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  1382. if (!mat)
  1383. continue;
  1384. String matName;
  1385. if (mat->getName() && mat->getName()[0])
  1386. matName = mat->mMapTo;
  1387. for (U32 j = 0; j < dl->mesh.mPolyList.size(); j++)
  1388. {
  1389. const OptimizedPolyList::Poly& poly = dl->mesh.mPolyList[j];
  1390. if (poly.material != i)
  1391. continue;
  1392. if (poly.vertexCount < 3)
  1393. continue;
  1394. if (poly.type == OptimizedPolyList::TriangleList ||
  1395. poly.type == OptimizedPolyList::TriangleFan ||
  1396. poly.type == OptimizedPolyList::TriangleStrip)
  1397. {
  1398. triangleCount += poly.vertexCount - 2;
  1399. }
  1400. else
  1401. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  1402. }
  1403. // Make sure that we are actually using this Material
  1404. if (triangleCount == 0)
  1405. continue;
  1406. tinyxml2::XMLElement* trianglesNode = doc->NewElement("triangles");
  1407. meshNode->LinkEndChild(trianglesNode);
  1408. trianglesNode->SetAttribute("material", (i > -1) ? avar("%s-material", matName.c_str()) : "");
  1409. trianglesNode->SetAttribute("count", avar("%d", triangleCount));
  1410. tinyxml2::XMLElement* trianglesVertInputNode = doc->NewElement("input");
  1411. trianglesNode->LinkEndChild(trianglesVertInputNode);
  1412. trianglesVertInputNode->SetAttribute("semantic", "VERTEX");
  1413. trianglesVertInputNode->SetAttribute("source", avar("#%s-mesh-vertices", meshName.c_str()));
  1414. trianglesVertInputNode->SetAttribute("offset", "0");
  1415. tinyxml2::XMLElement* trianglesNormalInputNode = doc->NewElement("input");
  1416. trianglesNode->LinkEndChild(trianglesNormalInputNode);
  1417. trianglesNormalInputNode->SetAttribute("semantic", "NORMAL");
  1418. trianglesNormalInputNode->SetAttribute("source", avar("#%s-mesh-normals", meshName.c_str()));
  1419. trianglesNormalInputNode->SetAttribute("offset", "1");
  1420. tinyxml2::XMLElement* trianglesUV0InputNode = doc->NewElement("input");
  1421. trianglesNode->LinkEndChild(trianglesUV0InputNode);
  1422. trianglesUV0InputNode->SetAttribute("semantic", "TEXCOORD");
  1423. trianglesUV0InputNode->SetAttribute("source", avar("#%s-mesh-map-0", meshName.c_str()));
  1424. trianglesUV0InputNode->SetAttribute("offset", "2");
  1425. trianglesUV0InputNode->SetAttribute("set", "0");
  1426. tinyxml2::XMLElement* polyNode = doc->NewElement("p");
  1427. trianglesNode->LinkEndChild(polyNode);
  1428. Vector<U32> tempIndices;
  1429. tempIndices.reserve(4);
  1430. for (U32 j = 0; j < dl->mesh.mPolyList.size(); j++)
  1431. {
  1432. const OptimizedPolyList::Poly& poly = dl->mesh.mPolyList[j];
  1433. if (poly.vertexCount < 3)
  1434. continue;
  1435. if (poly.material != i)
  1436. continue;
  1437. tempIndices.setSize(poly.vertexCount);
  1438. dMemset(tempIndices.address(), 0, poly.vertexCount);
  1439. if (poly.type == OptimizedPolyList::TriangleStrip)
  1440. {
  1441. tempIndices[0] = 0;
  1442. U32 idx = 1;
  1443. for (U32 k = 1; k < poly.vertexCount; k += 2)
  1444. tempIndices[idx++] = k;
  1445. for (U32 k = ((poly.vertexCount - 1) & (~0x1)); k > 0; k -= 2)
  1446. tempIndices[idx++] = k;
  1447. }
  1448. else if (poly.type == OptimizedPolyList::TriangleList ||
  1449. poly.type == OptimizedPolyList::TriangleFan)
  1450. {
  1451. for (U32 k = 0; k < poly.vertexCount; k++)
  1452. tempIndices[k] = k;
  1453. }
  1454. else
  1455. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  1456. const U32& firstIdx = dl->mesh.mIndexList[poly.vertexStart];
  1457. const OptimizedPolyList::VertIndex& firstVertIdx = dl->mesh.mVertexList[firstIdx];
  1458. for (U32 k = 1; k < poly.vertexCount - 1; k++)
  1459. {
  1460. const U32& secondIdx = dl->mesh.mIndexList[poly.vertexStart + tempIndices[k]];
  1461. const U32& thirdIdx = dl->mesh.mIndexList[poly.vertexStart + tempIndices[k + 1]];
  1462. const OptimizedPolyList::VertIndex& secondVertIdx = dl->mesh.mVertexList[secondIdx];
  1463. const OptimizedPolyList::VertIndex& thirdVertIdx = dl->mesh.mVertexList[thirdIdx];
  1464. // Note the reversed winding on the triangles
  1465. const char* tri = avar("%d %d %d %d %d %d %d %d %d ",
  1466. thirdVertIdx.vertIdx, thirdVertIdx.normalIdx, thirdVertIdx.uv0Idx,
  1467. secondVertIdx.vertIdx, secondVertIdx.normalIdx, secondVertIdx.uv0Idx,
  1468. firstVertIdx.vertIdx, firstVertIdx.normalIdx, firstVertIdx.uv0Idx);
  1469. tinyxml2::XMLText* triangleText = doc->NewText(tri);
  1470. polyNode->LinkEndChild(triangleText);
  1471. }
  1472. }
  1473. }
  1474. }
  1475. void ColladaUtils::exportColladaCollisionTriangles(tinyxml2::XMLElement* meshNode, const ExportData& exportData, const U32 collisionIdx)
  1476. {
  1477. tinyxml2::XMLDocument* doc = meshNode->GetDocument();
  1478. // Calculate the number of triangles that uses this Material
  1479. U32 triangleCount = 0;
  1480. const ExportData::colMesh* col = &exportData.colMeshes[collisionIdx];
  1481. String meshName = col->colMeshName;
  1482. for (U32 j = 0; j < col->mesh.mPolyList.size(); j++)
  1483. {
  1484. const OptimizedPolyList::Poly& poly = col->mesh.mPolyList[j];
  1485. if (poly.vertexCount < 3)
  1486. continue;
  1487. if (poly.type == OptimizedPolyList::TriangleList ||
  1488. poly.type == OptimizedPolyList::TriangleFan ||
  1489. poly.type == OptimizedPolyList::TriangleStrip)
  1490. {
  1491. triangleCount += poly.vertexCount - 2;
  1492. }
  1493. else
  1494. AssertISV(false, "ColladaUtils::exportColladaCollisionTriangles(): Unknown Poly type!");
  1495. }
  1496. // Make sure that we are actually using this Material
  1497. if (triangleCount == 0)
  1498. return;
  1499. tinyxml2::XMLElement* trianglesNode = doc->NewElement("triangles");
  1500. meshNode->LinkEndChild(trianglesNode);
  1501. trianglesNode->SetAttribute("material", "");
  1502. trianglesNode->SetAttribute("count", avar("%d", triangleCount));
  1503. tinyxml2::XMLElement* trianglesVertInputNode = doc->NewElement("input");
  1504. trianglesNode->LinkEndChild(trianglesVertInputNode);
  1505. trianglesVertInputNode->SetAttribute("semantic", "VERTEX");
  1506. trianglesVertInputNode->SetAttribute("source", avar("#%s-mesh-vertices", meshName.c_str()));
  1507. trianglesVertInputNode->SetAttribute("offset", "0");
  1508. tinyxml2::XMLElement* trianglesNormalInputNode = doc->NewElement("input");
  1509. trianglesNode->LinkEndChild(trianglesNormalInputNode);
  1510. trianglesNormalInputNode->SetAttribute("semantic", "NORMAL");
  1511. trianglesNormalInputNode->SetAttribute("source", avar("#%s-mesh-normals", meshName.c_str()));
  1512. trianglesNormalInputNode->SetAttribute("offset", "1");
  1513. tinyxml2::XMLElement* trianglesUV0InputNode = doc->NewElement("input");
  1514. trianglesNode->LinkEndChild(trianglesUV0InputNode);
  1515. trianglesUV0InputNode->SetAttribute("semantic", "TEXCOORD");
  1516. trianglesUV0InputNode->SetAttribute("source", avar("#%s-mesh-map-0", meshName.c_str()));
  1517. trianglesUV0InputNode->SetAttribute("offset", "2");
  1518. trianglesUV0InputNode->SetAttribute("set", "0");
  1519. tinyxml2::XMLElement* polyNode = doc->NewElement("p");
  1520. trianglesNode->LinkEndChild(polyNode);
  1521. Vector<U32> tempIndices;
  1522. tempIndices.reserve(4);
  1523. for (U32 j = 0; j < col->mesh.mPolyList.size(); j++)
  1524. {
  1525. const OptimizedPolyList::Poly& poly = col->mesh.mPolyList[j];
  1526. if (poly.vertexCount < 3)
  1527. continue;
  1528. tempIndices.setSize(poly.vertexCount);
  1529. dMemset(tempIndices.address(), 0, poly.vertexCount);
  1530. if (poly.type == OptimizedPolyList::TriangleStrip)
  1531. {
  1532. tempIndices[0] = 0;
  1533. U32 idx = 1;
  1534. for (U32 k = 1; k < poly.vertexCount; k += 2)
  1535. tempIndices[idx++] = k;
  1536. for (U32 k = ((poly.vertexCount - 1) & (~0x1)); k > 0; k -= 2)
  1537. tempIndices[idx++] = k;
  1538. }
  1539. else if (poly.type == OptimizedPolyList::TriangleList ||
  1540. poly.type == OptimizedPolyList::TriangleFan)
  1541. {
  1542. for (U32 k = 0; k < poly.vertexCount; k++)
  1543. tempIndices[k] = k;
  1544. }
  1545. else
  1546. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  1547. const U32& firstIdx = col->mesh.mIndexList[poly.vertexStart];
  1548. const OptimizedPolyList::VertIndex& firstVertIdx = col->mesh.mVertexList[firstIdx];
  1549. for (U32 k = 1; k < poly.vertexCount - 1; k++)
  1550. {
  1551. const U32& secondIdx = col->mesh.mIndexList[poly.vertexStart + tempIndices[k]];
  1552. const U32& thirdIdx = col->mesh.mIndexList[poly.vertexStart + tempIndices[k + 1]];
  1553. const OptimizedPolyList::VertIndex& secondVertIdx = col->mesh.mVertexList[secondIdx];
  1554. const OptimizedPolyList::VertIndex& thirdVertIdx = col->mesh.mVertexList[thirdIdx];
  1555. // Note the reversed winding on the triangles
  1556. const char* tri = avar("%d %d %d %d %d %d %d %d %d ",
  1557. thirdVertIdx.vertIdx, thirdVertIdx.normalIdx, thirdVertIdx.uv0Idx,
  1558. secondVertIdx.vertIdx, secondVertIdx.normalIdx, secondVertIdx.uv0Idx,
  1559. firstVertIdx.vertIdx, firstVertIdx.normalIdx, firstVertIdx.uv0Idx);
  1560. tinyxml2::XMLText* triangleText = doc->NewText(tri);
  1561. polyNode->LinkEndChild(triangleText);
  1562. }
  1563. }
  1564. }
  1565. void ColladaUtils::exportColladaMesh(tinyxml2::XMLElement* rootNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames)
  1566. {
  1567. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  1568. tinyxml2::XMLElement* libGeomsNode = doc->NewElement("library_geometries");
  1569. rootNode->LinkEndChild(libGeomsNode);
  1570. tinyxml2::XMLElement* geometryNode = doc->NewElement("geometry");
  1571. libGeomsNode->LinkEndChild(geometryNode);
  1572. geometryNode->SetAttribute("id", avar("%s-mesh", meshName.c_str()));
  1573. geometryNode->SetAttribute("name", avar("%s", meshName.c_str()));
  1574. tinyxml2::XMLElement* meshNode = doc->NewElement("mesh");
  1575. geometryNode->LinkEndChild(meshNode);
  1576. // Save out the vertices
  1577. tinyxml2::XMLElement* vertsSourceNode = doc->NewElement("source");
  1578. meshNode->LinkEndChild(vertsSourceNode);
  1579. vertsSourceNode->SetAttribute("id", avar("%s-mesh-positions", meshName.c_str()));
  1580. tinyxml2::XMLElement* vertsNode = doc->NewElement("float_array");
  1581. vertsSourceNode->LinkEndChild(vertsNode);
  1582. vertsNode->SetAttribute("id", avar("%s-mesh-positions-array", meshName.c_str()));
  1583. vertsNode->SetAttribute("count", avar("%d", mesh.mPoints.size() * 3));
  1584. for (U32 i = 0; i < mesh.mPoints.size(); i++)
  1585. {
  1586. const Point3F& vert = mesh.mPoints[i];
  1587. tinyxml2::XMLText* vertText = doc->NewText(avar("%.4f %.4f %.4f ", vert.x, vert.y, vert.z));
  1588. vertsNode->LinkEndChild(vertText);
  1589. }
  1590. // Save the vertex accessor
  1591. tinyxml2::XMLElement* vertsTechNode = doc->NewElement("technique_common");
  1592. vertsSourceNode->LinkEndChild(vertsTechNode);
  1593. tinyxml2::XMLElement* vertsAccNode = doc->NewElement("accessor");
  1594. vertsTechNode->LinkEndChild(vertsAccNode);
  1595. vertsAccNode->SetAttribute("source", avar("#%s-mesh-positions-array", meshName.c_str()));
  1596. vertsAccNode->SetAttribute("count", avar("%d", mesh.mPoints.size()));
  1597. vertsAccNode->SetAttribute("stride", "3");
  1598. tinyxml2::XMLElement* vertsAccXNode = doc->NewElement("param");
  1599. vertsAccNode->LinkEndChild(vertsAccXNode);
  1600. vertsAccXNode->SetAttribute("name", "X");
  1601. vertsAccXNode->SetAttribute("type", "float");
  1602. tinyxml2::XMLElement* vertsAccYNode = doc->NewElement("param");
  1603. vertsAccNode->LinkEndChild(vertsAccYNode);
  1604. vertsAccYNode->SetAttribute("name", "Y");
  1605. vertsAccYNode->SetAttribute("type", "float");
  1606. tinyxml2::XMLElement* vertsAccZNode = doc->NewElement("param");
  1607. vertsAccNode->LinkEndChild(vertsAccZNode);
  1608. vertsAccZNode->SetAttribute("name", "Z");
  1609. vertsAccZNode->SetAttribute("type", "float");
  1610. // Save out the normals
  1611. tinyxml2::XMLElement* normalsSourceNode = doc->NewElement("source");
  1612. meshNode->LinkEndChild(normalsSourceNode);
  1613. normalsSourceNode->SetAttribute("id", avar("%s-mesh-normals", meshName.c_str()));
  1614. tinyxml2::XMLElement* normalsNode = doc->NewElement("float_array");
  1615. normalsSourceNode->LinkEndChild(normalsNode);
  1616. normalsNode->SetAttribute("id", avar("%s-mesh-normals-array", meshName.c_str()));
  1617. normalsNode->SetAttribute("count", avar("%d", mesh.mNormals.size() * 3));
  1618. for (U32 i = 0; i < mesh.mNormals.size(); i++)
  1619. {
  1620. const Point3F& normal = mesh.mNormals[i];
  1621. tinyxml2::XMLText* normalText = doc->NewText(avar("%.4f %.4f %.4f ", normal.x, normal.y, normal.z));
  1622. normalsNode->LinkEndChild(normalText);
  1623. }
  1624. // Save the normals accessor
  1625. tinyxml2::XMLElement* normalsTechNode = doc->NewElement("technique_common");
  1626. normalsSourceNode->LinkEndChild(normalsTechNode);
  1627. tinyxml2::XMLElement* normalsAccNode = doc->NewElement("accessor");
  1628. normalsTechNode->LinkEndChild(normalsAccNode);
  1629. normalsAccNode->SetAttribute("source", avar("#%s-mesh-normals-array", meshName.c_str()));
  1630. normalsAccNode->SetAttribute("count", avar("%d", mesh.mNormals.size()));
  1631. normalsAccNode->SetAttribute("stride", "3");
  1632. tinyxml2::XMLElement* normalsAccXNode = doc->NewElement("param");
  1633. normalsAccNode->LinkEndChild(normalsAccXNode);
  1634. normalsAccXNode->SetAttribute("name", "X");
  1635. normalsAccXNode->SetAttribute("type", "float");
  1636. tinyxml2::XMLElement* normalsAccYNode = doc->NewElement("param");
  1637. normalsAccNode->LinkEndChild(normalsAccYNode);
  1638. normalsAccYNode->SetAttribute("name", "Y");
  1639. normalsAccYNode->SetAttribute("type", "float");
  1640. tinyxml2::XMLElement* normalsAccZNode = doc->NewElement("param");
  1641. normalsAccNode->LinkEndChild(normalsAccZNode);
  1642. normalsAccZNode->SetAttribute("name", "Z");
  1643. normalsAccZNode->SetAttribute("type", "float");
  1644. // Save out the uvs
  1645. tinyxml2::XMLElement* uv0SourceNode = doc->NewElement("source");
  1646. meshNode->LinkEndChild(uv0SourceNode);
  1647. uv0SourceNode->SetAttribute("id", avar("%s-mesh-map-0", meshName.c_str()));
  1648. tinyxml2::XMLElement* uv0Node = doc->NewElement("float_array");
  1649. uv0SourceNode->LinkEndChild(uv0Node);
  1650. uv0Node->SetAttribute("id", avar("%s-mesh-map-0-array", meshName.c_str()));
  1651. uv0Node->SetAttribute("count", avar("%d", mesh.mUV0s.size() * 2));
  1652. for (U32 i = 0; i < mesh.mUV0s.size(); i++)
  1653. {
  1654. const Point2F& uv0 = mesh.mUV0s[i];
  1655. tinyxml2::XMLText* uv0Text = doc->NewText(avar("%.4f %.4f ", uv0.x, 1.0f - uv0.y)); // COLLADA uvs are upside down compared to Torque
  1656. uv0Node->LinkEndChild(uv0Text);
  1657. }
  1658. // Save the uv0 accessor
  1659. tinyxml2::XMLElement* uv0TechNode = doc->NewElement("technique_common");
  1660. uv0SourceNode->LinkEndChild(uv0TechNode);
  1661. tinyxml2::XMLElement* uv0AccNode = doc->NewElement("accessor");
  1662. uv0TechNode->LinkEndChild(uv0AccNode);
  1663. uv0AccNode->SetAttribute("source", avar("#%s-mesh-map-0-array", meshName.c_str()));
  1664. uv0AccNode->SetAttribute("count", avar("%d", mesh.mUV0s.size()));
  1665. uv0AccNode->SetAttribute("stride", "2");
  1666. tinyxml2::XMLElement* uv0AccSNode = doc->NewElement("param");
  1667. uv0AccNode->LinkEndChild(uv0AccSNode);
  1668. uv0AccSNode->SetAttribute("name", "S");
  1669. uv0AccSNode->SetAttribute("type", "float");
  1670. tinyxml2::XMLElement* uv0AccTNode = doc->NewElement("param");
  1671. uv0AccNode->LinkEndChild(uv0AccTNode);
  1672. uv0AccTNode->SetAttribute("name", "T");
  1673. uv0AccTNode->SetAttribute("type", "float");
  1674. // Define the vertices position array
  1675. tinyxml2::XMLElement* verticesNode = doc->NewElement("vertices");
  1676. meshNode->LinkEndChild(verticesNode);
  1677. verticesNode->SetAttribute("id", avar("%s-mesh-vertices", meshName.c_str()));
  1678. tinyxml2::XMLElement* verticesInputNode = doc->NewElement("input");
  1679. verticesNode->LinkEndChild(verticesInputNode);
  1680. verticesInputNode->SetAttribute("semantic", "POSITION");
  1681. verticesInputNode->SetAttribute("source", avar("#%s-mesh-positions", meshName.c_str()));
  1682. exportColladaTriangles(meshNode, mesh, meshName, matNames);
  1683. // Extra info useful for COLLADAMaya importer (OpenCOLLADA)
  1684. tinyxml2::XMLElement* extraGeoNode = doc->NewElement("extra");
  1685. libGeomsNode->LinkEndChild(extraGeoNode);
  1686. tinyxml2::XMLElement* extraGeoNodeTech = doc->NewElement("technique");
  1687. extraGeoNode->LinkEndChild(extraGeoNodeTech);
  1688. extraGeoNodeTech->SetAttribute("profile", "OpenCOLLADAMaya");
  1689. tinyxml2::XMLElement* mayaNode2Id = doc->NewElement("originalMayaNodeId");
  1690. extraGeoNodeTech->LinkEndChild(mayaNode2Id);
  1691. mayaNode2Id->SetAttribute("sid", "originalMayaNodeId");
  1692. tinyxml2::XMLText* mayaIdMesh = doc->NewText(avar("%s", meshName.c_str()));
  1693. mayaNode2Id->LinkEndChild(mayaIdMesh);
  1694. tinyxml2::XMLElement* doubleSidedId = doc->NewElement("double_sided");
  1695. extraGeoNodeTech->LinkEndChild(doubleSidedId);
  1696. doubleSidedId->SetAttribute("sid", "double_sided");
  1697. tinyxml2::XMLText* doubleSideIdText = doc->NewText("1");
  1698. doubleSidedId->LinkEndChild(doubleSideIdText);
  1699. tinyxml2::XMLElement* paramExtraNode = doc->NewElement("param");
  1700. extraGeoNodeTech->LinkEndChild(paramExtraNode);
  1701. paramExtraNode->SetAttribute("sid", "colladaId");
  1702. paramExtraNode->SetAttribute("type", "string");
  1703. tinyxml2::XMLText* mayaParamMesh = doc->NewText(avar("%s-mesh", meshName.c_str()));
  1704. paramExtraNode->LinkEndChild(mayaParamMesh);
  1705. }
  1706. void ColladaUtils::exportColladaMesh(tinyxml2::XMLElement* rootNode, const ExportData& exportData, const String& meshName)
  1707. {
  1708. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  1709. tinyxml2::XMLElement* libGeomsNode = doc->NewElement("library_geometries");
  1710. rootNode->LinkEndChild(libGeomsNode);
  1711. for (U32 d = 0; d < exportData.detailLevels.size(); d++)
  1712. {
  1713. char lodMeshName[256];
  1714. dSprintf(lodMeshName, 256, "%s%d", meshName.c_str(), exportData.detailLevels[d].size);
  1715. char lodMeshID[256];
  1716. dSprintf(lodMeshID, 256, "%s-mesh", lodMeshName);
  1717. tinyxml2::XMLElement* geometryNode = doc->NewElement("geometry");
  1718. libGeomsNode->LinkEndChild(geometryNode);
  1719. geometryNode->SetAttribute("id", lodMeshID);
  1720. geometryNode->SetAttribute("name", lodMeshName);
  1721. tinyxml2::XMLElement* meshNode = doc->NewElement("mesh");
  1722. geometryNode->LinkEndChild(meshNode);
  1723. // Save out the vertices
  1724. tinyxml2::XMLElement* vertsSourceNode = doc->NewElement("source");
  1725. meshNode->LinkEndChild(vertsSourceNode);
  1726. vertsSourceNode->SetAttribute("id", avar("%s-mesh-positions", lodMeshName));
  1727. tinyxml2::XMLElement* vertsNode = doc->NewElement("float_array");
  1728. vertsSourceNode->LinkEndChild(vertsNode);
  1729. vertsNode->SetAttribute("id", avar("%s-mesh-positions-array", lodMeshName));
  1730. vertsNode->SetAttribute("count", avar("%d", exportData.detailLevels[d].mesh.mPoints.size() * 3));
  1731. for (U32 i = 0; i < exportData.detailLevels[d].mesh.mPoints.size(); i++)
  1732. {
  1733. const Point3F& vert = exportData.detailLevels[d].mesh.mPoints[i];
  1734. tinyxml2::XMLText* vertText = doc->NewText(avar("%.4f %.4f %.4f ", vert.x, vert.y, vert.z));
  1735. vertsNode->LinkEndChild(vertText);
  1736. }
  1737. // Save the vertex accessor
  1738. tinyxml2::XMLElement* vertsTechNode = doc->NewElement("technique_common");
  1739. vertsSourceNode->LinkEndChild(vertsTechNode);
  1740. tinyxml2::XMLElement* vertsAccNode = doc->NewElement("accessor");
  1741. vertsTechNode->LinkEndChild(vertsAccNode);
  1742. vertsAccNode->SetAttribute("source", avar("#%s-mesh-positions-array", lodMeshName));
  1743. vertsAccNode->SetAttribute("count", avar("%d", exportData.detailLevels[d].mesh.mPoints.size()));
  1744. vertsAccNode->SetAttribute("stride", "3");
  1745. tinyxml2::XMLElement* vertsAccXNode = doc->NewElement("param");
  1746. vertsAccNode->LinkEndChild(vertsAccXNode);
  1747. vertsAccXNode->SetAttribute("name", "X");
  1748. vertsAccXNode->SetAttribute("type", "float");
  1749. tinyxml2::XMLElement* vertsAccYNode = doc->NewElement("param");
  1750. vertsAccNode->LinkEndChild(vertsAccYNode);
  1751. vertsAccYNode->SetAttribute("name", "Y");
  1752. vertsAccYNode->SetAttribute("type", "float");
  1753. tinyxml2::XMLElement* vertsAccZNode = doc->NewElement("param");
  1754. vertsAccNode->LinkEndChild(vertsAccZNode);
  1755. vertsAccZNode->SetAttribute("name", "Z");
  1756. vertsAccZNode->SetAttribute("type", "float");
  1757. // Save out the normals
  1758. tinyxml2::XMLElement* normalsSourceNode = doc->NewElement("source");
  1759. meshNode->LinkEndChild(normalsSourceNode);
  1760. normalsSourceNode->SetAttribute("id", avar("%s-mesh-normals", lodMeshName));
  1761. tinyxml2::XMLElement* normalsNode = doc->NewElement("float_array");
  1762. normalsSourceNode->LinkEndChild(normalsNode);
  1763. normalsNode->SetAttribute("id", avar("%s-mesh-normals-array", lodMeshName));
  1764. normalsNode->SetAttribute("count", avar("%d", exportData.detailLevels[d].mesh.mNormals.size() * 3));
  1765. for (U32 i = 0; i < exportData.detailLevels[d].mesh.mNormals.size(); i++)
  1766. {
  1767. const Point3F& normal = exportData.detailLevels[d].mesh.mNormals[i];
  1768. tinyxml2::XMLText* normalText = doc->NewText(avar("%.4f %.4f %.4f ", normal.x, normal.y, normal.z));
  1769. normalsNode->LinkEndChild(normalText);
  1770. }
  1771. // Save the normals accessor
  1772. tinyxml2::XMLElement* normalsTechNode = doc->NewElement("technique_common");
  1773. normalsSourceNode->LinkEndChild(normalsTechNode);
  1774. tinyxml2::XMLElement* normalsAccNode = doc->NewElement("accessor");
  1775. normalsTechNode->LinkEndChild(normalsAccNode);
  1776. normalsAccNode->SetAttribute("source", avar("#%s-mesh-normals-array", lodMeshName));
  1777. normalsAccNode->SetAttribute("count", avar("%d", exportData.detailLevels[d].mesh.mNormals.size()));
  1778. normalsAccNode->SetAttribute("stride", "3");
  1779. tinyxml2::XMLElement* normalsAccXNode = doc->NewElement("param");
  1780. normalsAccNode->LinkEndChild(normalsAccXNode);
  1781. normalsAccXNode->SetAttribute("name", "X");
  1782. normalsAccXNode->SetAttribute("type", "float");
  1783. tinyxml2::XMLElement* normalsAccYNode = doc->NewElement("param");
  1784. normalsAccNode->LinkEndChild(normalsAccYNode);
  1785. normalsAccYNode->SetAttribute("name", "Y");
  1786. normalsAccYNode->SetAttribute("type", "float");
  1787. tinyxml2::XMLElement* normalsAccZNode = doc->NewElement("param");
  1788. normalsAccNode->LinkEndChild(normalsAccZNode);
  1789. normalsAccZNode->SetAttribute("name", "Z");
  1790. normalsAccZNode->SetAttribute("type", "float");
  1791. // Save out the uvs
  1792. tinyxml2::XMLElement* uv0SourceNode = doc->NewElement("source");
  1793. meshNode->LinkEndChild(uv0SourceNode);
  1794. uv0SourceNode->SetAttribute("id", avar("%s-mesh-map-0", lodMeshName));
  1795. tinyxml2::XMLElement* uv0Node = doc->NewElement("float_array");
  1796. uv0SourceNode->LinkEndChild(uv0Node);
  1797. uv0Node->SetAttribute("id", avar("%s-mesh-map-0-array", lodMeshName));
  1798. uv0Node->SetAttribute("count", avar("%d", exportData.detailLevels[d].mesh.mUV0s.size() * 2));
  1799. for (U32 i = 0; i < exportData.detailLevels[d].mesh.mUV0s.size(); i++)
  1800. {
  1801. const Point2F& uv0 = exportData.detailLevels[d].mesh.mUV0s[i];
  1802. tinyxml2::XMLText* uv0Text = doc->NewText(avar("%.4f %.4f ", uv0.x, 1.0f - uv0.y)); // COLLADA uvs are upside down compared to Torque
  1803. uv0Node->LinkEndChild(uv0Text);
  1804. }
  1805. // Save the uv0 accessor
  1806. tinyxml2::XMLElement* uv0TechNode = doc->NewElement("technique_common");
  1807. uv0SourceNode->LinkEndChild(uv0TechNode);
  1808. tinyxml2::XMLElement* uv0AccNode = doc->NewElement("accessor");
  1809. uv0TechNode->LinkEndChild(uv0AccNode);
  1810. uv0AccNode->SetAttribute("source", avar("#%s-mesh-map-0-array", lodMeshName));
  1811. uv0AccNode->SetAttribute("count", avar("%d", exportData.detailLevels[d].mesh.mUV0s.size()));
  1812. uv0AccNode->SetAttribute("stride", "2");
  1813. tinyxml2::XMLElement* uv0AccSNode = doc->NewElement("param");
  1814. uv0AccNode->LinkEndChild(uv0AccSNode);
  1815. uv0AccSNode->SetAttribute("name", "S");
  1816. uv0AccSNode->SetAttribute("type", "float");
  1817. tinyxml2::XMLElement* uv0AccTNode = doc->NewElement("param");
  1818. uv0AccNode->LinkEndChild(uv0AccTNode);
  1819. uv0AccTNode->SetAttribute("name", "T");
  1820. uv0AccTNode->SetAttribute("type", "float");
  1821. // Define the vertices position array
  1822. tinyxml2::XMLElement* verticesNode = doc->NewElement("vertices");
  1823. meshNode->LinkEndChild(verticesNode);
  1824. verticesNode->SetAttribute("id", avar("%s-mesh-vertices", lodMeshName));
  1825. tinyxml2::XMLElement* verticesInputNode = doc->NewElement("input");
  1826. verticesNode->LinkEndChild(verticesInputNode);
  1827. verticesInputNode->SetAttribute("semantic", "POSITION");
  1828. verticesInputNode->SetAttribute("source", avar("#%s-mesh-positions", lodMeshName));
  1829. Vector<String> mapNames;
  1830. //exportColladaTriangles(meshNode, exportData.detailLevels[d].mesh, lodMeshName, mapNames);
  1831. exportColladaTriangles(meshNode, exportData, d, lodMeshName);
  1832. // Extra info useful for COLLADAMaya importer (OpenCOLLADA)
  1833. tinyxml2::XMLElement* extraGeoNode = doc->NewElement("extra");
  1834. libGeomsNode->LinkEndChild(extraGeoNode);
  1835. tinyxml2::XMLElement* extraGeoNodeTech = doc->NewElement("technique");
  1836. extraGeoNode->LinkEndChild(extraGeoNodeTech);
  1837. extraGeoNodeTech->SetAttribute("profile", "OpenCOLLADAMaya");
  1838. tinyxml2::XMLElement* mayaNode2Id = doc->NewElement("originalMayaNodeId");
  1839. extraGeoNodeTech->LinkEndChild(mayaNode2Id);
  1840. mayaNode2Id->SetAttribute("sid", "originalMayaNodeId");
  1841. tinyxml2::XMLText* mayaIdMesh = doc->NewText(avar("%s", lodMeshName));
  1842. mayaNode2Id->LinkEndChild(mayaIdMesh);
  1843. tinyxml2::XMLElement* doubleSidedId = doc->NewElement("double_sided");
  1844. extraGeoNodeTech->LinkEndChild(doubleSidedId);
  1845. doubleSidedId->SetAttribute("sid", "double_sided");
  1846. tinyxml2::XMLText* doubleSideIdText = doc->NewText("1");
  1847. doubleSidedId->LinkEndChild(doubleSideIdText);
  1848. tinyxml2::XMLElement* paramExtraNode = doc->NewElement("param");
  1849. extraGeoNodeTech->LinkEndChild(paramExtraNode);
  1850. paramExtraNode->SetAttribute("sid", "colladaId");
  1851. paramExtraNode->SetAttribute("type", "string");
  1852. tinyxml2::XMLText* mayaParamMesh = doc->NewText(avar("%s-mesh", lodMeshName));
  1853. paramExtraNode->LinkEndChild(mayaParamMesh);
  1854. }
  1855. //And now collisions
  1856. for (U32 d = 0; d < exportData.colMeshes.size(); d++)
  1857. {
  1858. const char* colMeshName = exportData.colMeshes[d].colMeshName;
  1859. char colMeshId[256];
  1860. dSprintf(colMeshId, 256, "%s-mesh", colMeshName);
  1861. tinyxml2::XMLElement* geometryNode = doc->NewElement("geometry");
  1862. libGeomsNode->LinkEndChild(geometryNode);
  1863. geometryNode->SetAttribute("id", colMeshId);
  1864. geometryNode->SetAttribute("name", colMeshName);
  1865. tinyxml2::XMLElement* meshNode = doc->NewElement("mesh");
  1866. geometryNode->LinkEndChild(meshNode);
  1867. // Save out the vertices
  1868. tinyxml2::XMLElement* vertsSourceNode = doc->NewElement("source");
  1869. meshNode->LinkEndChild(vertsSourceNode);
  1870. vertsSourceNode->SetAttribute("id", avar("%s-mesh-positions", colMeshName));
  1871. tinyxml2::XMLElement* vertsNode = doc->NewElement("float_array");
  1872. vertsSourceNode->LinkEndChild(vertsNode);
  1873. vertsNode->SetAttribute("id", avar("%s-mesh-positions-array", colMeshName));
  1874. vertsNode->SetAttribute("count", avar("%d", exportData.colMeshes[d].mesh.mPoints.size() * 3));
  1875. for (U32 i = 0; i < exportData.colMeshes[d].mesh.mPoints.size(); i++)
  1876. {
  1877. const Point3F& vert = exportData.colMeshes[d].mesh.mPoints[i];
  1878. tinyxml2::XMLText* vertText = doc->NewText(avar("%.4f %.4f %.4f ", vert.x, vert.y, vert.z));
  1879. vertsNode->LinkEndChild(vertText);
  1880. }
  1881. // Save the vertex accessor
  1882. tinyxml2::XMLElement* vertsTechNode = doc->NewElement("technique_common");
  1883. vertsSourceNode->LinkEndChild(vertsTechNode);
  1884. tinyxml2::XMLElement* vertsAccNode = doc->NewElement("accessor");
  1885. vertsTechNode->LinkEndChild(vertsAccNode);
  1886. vertsAccNode->SetAttribute("source", avar("#%s-mesh-positions-array", colMeshName));
  1887. vertsAccNode->SetAttribute("count", avar("%d", exportData.colMeshes[d].mesh.mPoints.size()));
  1888. vertsAccNode->SetAttribute("stride", "3");
  1889. tinyxml2::XMLElement* vertsAccXNode = doc->NewElement("param");
  1890. vertsAccNode->LinkEndChild(vertsAccXNode);
  1891. vertsAccXNode->SetAttribute("name", "X");
  1892. vertsAccXNode->SetAttribute("type", "float");
  1893. tinyxml2::XMLElement* vertsAccYNode = doc->NewElement("param");
  1894. vertsAccNode->LinkEndChild(vertsAccYNode);
  1895. vertsAccYNode->SetAttribute("name", "Y");
  1896. vertsAccYNode->SetAttribute("type", "float");
  1897. tinyxml2::XMLElement* vertsAccZNode = doc->NewElement("param");
  1898. vertsAccNode->LinkEndChild(vertsAccZNode);
  1899. vertsAccZNode->SetAttribute("name", "Z");
  1900. vertsAccZNode->SetAttribute("type", "float");
  1901. // Save out the normals
  1902. tinyxml2::XMLElement* normalsSourceNode = doc->NewElement("source");
  1903. meshNode->LinkEndChild(normalsSourceNode);
  1904. normalsSourceNode->SetAttribute("id", avar("%s-mesh-normals", colMeshName));
  1905. tinyxml2::XMLElement* normalsNode = doc->NewElement("float_array");
  1906. normalsSourceNode->LinkEndChild(normalsNode);
  1907. normalsNode->SetAttribute("id", avar("%s-mesh-normals-array", colMeshName));
  1908. normalsNode->SetAttribute("count", avar("%d", exportData.colMeshes[d].mesh.mNormals.size() * 3));
  1909. for (U32 i = 0; i < exportData.colMeshes[d].mesh.mNormals.size(); i++)
  1910. {
  1911. const Point3F& normal = exportData.colMeshes[d].mesh.mNormals[i];
  1912. tinyxml2::XMLText* normalText = doc->NewText(avar("%.4f %.4f %.4f ", normal.x, normal.y, normal.z));
  1913. normalsNode->LinkEndChild(normalText);
  1914. }
  1915. // Save the normals accessor
  1916. tinyxml2::XMLElement* normalsTechNode = doc->NewElement("technique_common");
  1917. normalsSourceNode->LinkEndChild(normalsTechNode);
  1918. tinyxml2::XMLElement* normalsAccNode = doc->NewElement("accessor");
  1919. normalsTechNode->LinkEndChild(normalsAccNode);
  1920. normalsAccNode->SetAttribute("source", avar("#%s-mesh-normals-array", colMeshName));
  1921. normalsAccNode->SetAttribute("count", avar("%d", exportData.colMeshes[d].mesh.mNormals.size()));
  1922. normalsAccNode->SetAttribute("stride", "3");
  1923. tinyxml2::XMLElement* normalsAccXNode = doc->NewElement("param");
  1924. normalsAccNode->LinkEndChild(normalsAccXNode);
  1925. normalsAccXNode->SetAttribute("name", "X");
  1926. normalsAccXNode->SetAttribute("type", "float");
  1927. tinyxml2::XMLElement* normalsAccYNode = doc->NewElement("param");
  1928. normalsAccNode->LinkEndChild(normalsAccYNode);
  1929. normalsAccYNode->SetAttribute("name", "Y");
  1930. normalsAccYNode->SetAttribute("type", "float");
  1931. tinyxml2::XMLElement* normalsAccZNode = doc->NewElement("param");
  1932. normalsAccNode->LinkEndChild(normalsAccZNode);
  1933. normalsAccZNode->SetAttribute("name", "Z");
  1934. normalsAccZNode->SetAttribute("type", "float");
  1935. // Save out the uvs
  1936. tinyxml2::XMLElement* uv0SourceNode = doc->NewElement("source");
  1937. meshNode->LinkEndChild(uv0SourceNode);
  1938. uv0SourceNode->SetAttribute("id", avar("%s-mesh-map-0", colMeshName));
  1939. tinyxml2::XMLElement* uv0Node = doc->NewElement("float_array");
  1940. uv0SourceNode->LinkEndChild(uv0Node);
  1941. uv0Node->SetAttribute("id", avar("%s-mesh-map-0-array", colMeshName));
  1942. uv0Node->SetAttribute("count", avar("%d", exportData.colMeshes[d].mesh.mUV0s.size() * 2));
  1943. for (U32 i = 0; i < exportData.colMeshes[d].mesh.mUV0s.size(); i++)
  1944. {
  1945. const Point2F& uv0 = exportData.colMeshes[d].mesh.mUV0s[i];
  1946. tinyxml2::XMLText* uv0Text = doc->NewText(avar("%.4f %.4f ", uv0.x, 1.0f - uv0.y)); // COLLADA uvs are upside down compared to Torque
  1947. uv0Node->LinkEndChild(uv0Text);
  1948. }
  1949. // Save the uv0 accessor
  1950. tinyxml2::XMLElement* uv0TechNode = doc->NewElement("technique_common");
  1951. uv0SourceNode->LinkEndChild(uv0TechNode);
  1952. tinyxml2::XMLElement* uv0AccNode = doc->NewElement("accessor");
  1953. uv0TechNode->LinkEndChild(uv0AccNode);
  1954. uv0AccNode->SetAttribute("source", avar("#%s-mesh-map-0-array", colMeshName));
  1955. uv0AccNode->SetAttribute("count", avar("%d", exportData.colMeshes[d].mesh.mUV0s.size()));
  1956. uv0AccNode->SetAttribute("stride", "2");
  1957. tinyxml2::XMLElement* uv0AccSNode = doc->NewElement("param");
  1958. uv0AccNode->LinkEndChild(uv0AccSNode);
  1959. uv0AccSNode->SetAttribute("name", "S");
  1960. uv0AccSNode->SetAttribute("type", "float");
  1961. tinyxml2::XMLElement* uv0AccTNode = doc->NewElement("param");
  1962. uv0AccNode->LinkEndChild(uv0AccTNode);
  1963. uv0AccTNode->SetAttribute("name", "T");
  1964. uv0AccTNode->SetAttribute("type", "float");
  1965. // Define the vertices position array
  1966. tinyxml2::XMLElement* verticesNode = doc->NewElement("vertices");
  1967. meshNode->LinkEndChild(verticesNode);
  1968. verticesNode->SetAttribute("id", avar("%s-mesh-vertices", colMeshName));
  1969. tinyxml2::XMLElement* verticesInputNode = doc->NewElement("input");
  1970. verticesNode->LinkEndChild(verticesInputNode);
  1971. verticesInputNode->SetAttribute("semantic", "POSITION");
  1972. verticesInputNode->SetAttribute("source", avar("#%s-mesh-positions", colMeshName));
  1973. Vector<String> mapNames;
  1974. //exportColladaTriangles(meshNode, exportData.detailLevels[d].mesh, lodMeshName, mapNames);
  1975. exportColladaCollisionTriangles(meshNode, exportData, d);
  1976. // Extra info useful for COLLADAMaya importer (OpenCOLLADA)
  1977. tinyxml2::XMLElement* extraGeoNode = doc->NewElement("extra");
  1978. libGeomsNode->LinkEndChild(extraGeoNode);
  1979. tinyxml2::XMLElement* extraGeoNodeTech = doc->NewElement("technique");
  1980. extraGeoNode->LinkEndChild(extraGeoNodeTech);
  1981. extraGeoNodeTech->SetAttribute("profile", "OpenCOLLADAMaya");
  1982. tinyxml2::XMLElement* mayaNode2Id = doc->NewElement("originalMayaNodeId");
  1983. extraGeoNodeTech->LinkEndChild(mayaNode2Id);
  1984. mayaNode2Id->SetAttribute("sid", "originalMayaNodeId");
  1985. tinyxml2::XMLText* mayaIdMesh = doc->NewText(avar("%s", colMeshName));
  1986. mayaNode2Id->LinkEndChild(mayaIdMesh);
  1987. tinyxml2::XMLElement* doubleSidedId = doc->NewElement("double_sided");
  1988. extraGeoNodeTech->LinkEndChild(doubleSidedId);
  1989. doubleSidedId->SetAttribute("sid", "double_sided");
  1990. tinyxml2::XMLText* doubleSideIdText = doc->NewText("1");
  1991. doubleSidedId->LinkEndChild(doubleSideIdText);
  1992. tinyxml2::XMLElement* paramExtraNode = doc->NewElement("param");
  1993. extraGeoNodeTech->LinkEndChild(paramExtraNode);
  1994. paramExtraNode->SetAttribute("sid", "colladaId");
  1995. paramExtraNode->SetAttribute("type", "string");
  1996. tinyxml2::XMLText* mayaParamMesh = doc->NewText(avar("%s-mesh", colMeshName));
  1997. paramExtraNode->LinkEndChild(mayaParamMesh);
  1998. }
  1999. }
  2000. void ColladaUtils::exportColladaScene(tinyxml2::XMLElement* rootNode, const String& meshName, const Vector<String>& matNames)
  2001. {
  2002. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  2003. tinyxml2::XMLElement* libSceneNode = doc->NewElement("library_visual_scenes");
  2004. rootNode->LinkEndChild(libSceneNode);
  2005. tinyxml2::XMLElement* visSceneNode = doc->NewElement("visual_scene");
  2006. libSceneNode->LinkEndChild(visSceneNode);
  2007. visSceneNode->SetAttribute("id", "RootNode");
  2008. visSceneNode->SetAttribute("name", "RootNode");
  2009. tinyxml2::XMLElement* nodeNode = doc->NewElement("node");
  2010. visSceneNode->LinkEndChild(nodeNode);
  2011. nodeNode->SetAttribute("id", avar("%s", meshName.c_str()));
  2012. nodeNode->SetAttribute("name", avar("%s", meshName.c_str()));
  2013. nodeNode->SetAttribute("type", "NODE");
  2014. tinyxml2::XMLElement* instanceGeomNode = doc->NewElement("instance_geometry");
  2015. nodeNode->LinkEndChild(instanceGeomNode);
  2016. instanceGeomNode->SetAttribute("url", avar("#%s-mesh", meshName.c_str()));
  2017. instanceGeomNode->SetAttribute("name", avar("%s", meshName.c_str()));
  2018. tinyxml2::XMLElement* bindMatNode = doc->NewElement("bind_material");
  2019. instanceGeomNode->LinkEndChild(bindMatNode);
  2020. tinyxml2::XMLElement* techniqueNode = doc->NewElement("technique_common");
  2021. bindMatNode->LinkEndChild(techniqueNode);
  2022. // Bind the materials
  2023. for (U32 i = 0; i < matNames.size(); i++)
  2024. {
  2025. tinyxml2::XMLElement* instMatNode = doc->NewElement("instance_material");
  2026. techniqueNode->LinkEndChild(instMatNode);
  2027. instMatNode->SetAttribute("symbol", avar("%s-material", matNames[i].c_str()));
  2028. instMatNode->SetAttribute("target", avar("#%s-material", matNames[i].c_str()));
  2029. tinyxml2::XMLElement* bindVertexNode = doc->NewElement("bind_vertex_input");
  2030. instMatNode->LinkEndChild(bindVertexNode);
  2031. //bindVertexNode->SetAttribute("semantic", avar("%s-mesh-map-0", meshName.c_str()));
  2032. bindVertexNode->SetAttribute("semantic", "UVMap");
  2033. bindVertexNode->SetAttribute("input_semantic", "TEXCOORD");
  2034. bindVertexNode->SetAttribute("input_set", "0");
  2035. }
  2036. // Extra info useful for COLLADAMax importer (OpenCOLLADA)
  2037. tinyxml2::XMLElement* extraInsGeoNode = doc->NewElement("extra");
  2038. nodeNode->LinkEndChild(extraInsGeoNode);
  2039. tinyxml2::XMLElement* extraInsGeoTechNode = doc->NewElement("technique");
  2040. extraInsGeoNode->LinkEndChild(extraInsGeoTechNode);
  2041. extraInsGeoTechNode->SetAttribute("profile", "OpenCOLLADA");
  2042. tinyxml2::XMLElement* castShadowsNode = doc->NewElement("cast_shadows");
  2043. extraInsGeoTechNode->LinkEndChild(castShadowsNode);
  2044. castShadowsNode->SetAttribute("sid", "cast_shadows");
  2045. castShadowsNode->SetAttribute("type", "bool");
  2046. tinyxml2::XMLText* castShadowsText = doc->NewText("1");
  2047. castShadowsNode->LinkEndChild(castShadowsText);
  2048. //-----------------------------
  2049. tinyxml2::XMLElement* receiveShadowsNode = doc->NewElement("receive_shadows");
  2050. extraInsGeoTechNode->LinkEndChild(receiveShadowsNode);
  2051. receiveShadowsNode->SetAttribute("sid", "receive_shadows");
  2052. receiveShadowsNode->SetAttribute("type", "bool");
  2053. tinyxml2::XMLText* receiveShadowsText = doc->NewText("1");
  2054. receiveShadowsNode->LinkEndChild(receiveShadowsText);
  2055. //-----------------------------
  2056. tinyxml2::XMLElement* primaryVisibiltyNode = doc->NewElement("primary_visibility");
  2057. extraInsGeoTechNode->LinkEndChild(primaryVisibiltyNode);
  2058. primaryVisibiltyNode->SetAttribute("sid", "primary_visibility");
  2059. primaryVisibiltyNode->SetAttribute("type", "int");
  2060. tinyxml2::XMLText* primaryVisibiltyText = doc->NewText("1");
  2061. primaryVisibiltyNode->LinkEndChild(primaryVisibiltyText);
  2062. //-----------------------------
  2063. tinyxml2::XMLElement* secondaryVisibilityNode = doc->NewElement("secondary_visibility");
  2064. extraInsGeoTechNode->LinkEndChild(secondaryVisibilityNode);
  2065. secondaryVisibilityNode->SetAttribute("sid", "secondary_visibility");
  2066. secondaryVisibilityNode->SetAttribute("type", "int");
  2067. tinyxml2::XMLText* secondaryVisibilityText = doc->NewText("1");
  2068. secondaryVisibilityNode->LinkEndChild(secondaryVisibilityText);
  2069. // Extra info useful for COLLADAMaya importer (OpenCOLLADA)
  2070. tinyxml2::XMLElement* extra2InsGeoNode = doc->NewElement("extra");
  2071. nodeNode->LinkEndChild(extra2InsGeoNode);
  2072. tinyxml2::XMLElement* extra2InsGeoTechNode = doc->NewElement("technique");
  2073. extra2InsGeoNode->LinkEndChild(extra2InsGeoTechNode);
  2074. extra2InsGeoTechNode->SetAttribute("profile", "OpenCOLLADAMaya");
  2075. tinyxml2::XMLElement* mayaNodeId = doc->NewElement("originalMayaNodeId");
  2076. extra2InsGeoTechNode->LinkEndChild(mayaNodeId);
  2077. mayaNodeId->SetAttribute("sid", "originalMayaNodeId");
  2078. mayaNodeId->SetAttribute("type", "string");
  2079. tinyxml2::XMLText* mayaNodeIdMesh = doc->NewText(avar("%s", meshName.c_str()));
  2080. mayaNodeId->LinkEndChild(mayaNodeIdMesh);
  2081. tinyxml2::XMLElement* paramExtraNode = doc->NewElement("param");
  2082. extra2InsGeoTechNode->LinkEndChild(paramExtraNode);
  2083. paramExtraNode->SetAttribute("sid", "colladaId");
  2084. paramExtraNode->SetAttribute("type", "string");
  2085. tinyxml2::XMLText* mayaParamMesh = doc->NewText(avar("%s", meshName.c_str()));
  2086. paramExtraNode->LinkEndChild(mayaParamMesh);
  2087. //-----------------------------
  2088. tinyxml2::XMLElement* sceneNode = doc->NewElement("scene");
  2089. rootNode->LinkEndChild(sceneNode);
  2090. tinyxml2::XMLElement* instVisSceneNode = doc->NewElement("instance_visual_scene");
  2091. sceneNode->LinkEndChild(instVisSceneNode);
  2092. instVisSceneNode->SetAttribute("url", "#RootNode");
  2093. }
  2094. void ColladaUtils::exportColladaScene(tinyxml2::XMLElement* rootNode, const ExportData& exportData, const String& meshName)
  2095. {
  2096. tinyxml2::XMLDocument* doc = rootNode->GetDocument();
  2097. tinyxml2::XMLElement* libSceneNode = doc->NewElement("library_visual_scenes");
  2098. rootNode->LinkEndChild(libSceneNode);
  2099. tinyxml2::XMLElement* visSceneNode = doc->NewElement("visual_scene");
  2100. libSceneNode->LinkEndChild(visSceneNode);
  2101. visSceneNode->SetAttribute("id", "RootNode");
  2102. visSceneNode->SetAttribute("name", "RootNode");
  2103. for (U32 d = 0; d < exportData.detailLevels.size(); d++)
  2104. {
  2105. char lodMeshName[256];
  2106. dSprintf(lodMeshName, 256, "%s%d", meshName.c_str(), exportData.detailLevels[d].size);
  2107. tinyxml2::XMLElement* nodeNode = doc->NewElement("node");
  2108. visSceneNode->LinkEndChild(nodeNode);
  2109. nodeNode->SetAttribute("id", lodMeshName);
  2110. nodeNode->SetAttribute("name", lodMeshName);
  2111. nodeNode->SetAttribute("type", "NODE");
  2112. tinyxml2::XMLElement* instanceGeomNode = doc->NewElement("instance_geometry");
  2113. nodeNode->LinkEndChild(instanceGeomNode);
  2114. instanceGeomNode->SetAttribute("url", avar("#%s%d-mesh", meshName.c_str(), exportData.detailLevels[d].size));
  2115. instanceGeomNode->SetAttribute("name", lodMeshName);
  2116. tinyxml2::XMLElement* bindMatNode = doc->NewElement("bind_material");
  2117. instanceGeomNode->LinkEndChild(bindMatNode);
  2118. tinyxml2::XMLElement* techniqueNode = doc->NewElement("technique_common");
  2119. bindMatNode->LinkEndChild(techniqueNode);
  2120. // Bind the materials
  2121. for (U32 i = 0; i < exportData.detailLevels[d].materialRefList.size(); i++)
  2122. {
  2123. int matIdx;
  2124. exportData.detailLevels[d].materialRefList.tryGetValue(i, matIdx);
  2125. BaseMatInstance* baseInst = exportData.materials[matIdx];
  2126. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  2127. if (!mat)
  2128. continue;
  2129. String matName;
  2130. if (mat->getName() && mat->getName()[0])
  2131. matName = mat->mMapTo;
  2132. tinyxml2::XMLElement* instMatNode = doc->NewElement("instance_material");
  2133. techniqueNode->LinkEndChild(instMatNode);
  2134. instMatNode->SetAttribute("symbol", avar("%s-material", matName.c_str()));
  2135. instMatNode->SetAttribute("target", avar("#%s-material", matName.c_str()));
  2136. tinyxml2::XMLElement* bindVertexNode = doc->NewElement("bind_vertex_input");
  2137. instMatNode->LinkEndChild(bindVertexNode);
  2138. //bindVertexNode->SetAttribute("semantic", avar("%s-mesh-map-0", meshName.c_str()));
  2139. bindVertexNode->SetAttribute("semantic", "UVMap");
  2140. bindVertexNode->SetAttribute("input_semantic", "TEXCOORD");
  2141. bindVertexNode->SetAttribute("input_set", "0");
  2142. }
  2143. // Extra info useful for COLLADAMax importer (OpenCOLLADA)
  2144. tinyxml2::XMLElement* extraInsGeoNode = doc->NewElement("extra");
  2145. nodeNode->LinkEndChild(extraInsGeoNode);
  2146. tinyxml2::XMLElement* extraInsGeoTechNode = doc->NewElement("technique");
  2147. extraInsGeoNode->LinkEndChild(extraInsGeoTechNode);
  2148. extraInsGeoTechNode->SetAttribute("profile", "OpenCOLLADA");
  2149. tinyxml2::XMLElement* castShadowsNode = doc->NewElement("cast_shadows");
  2150. extraInsGeoTechNode->LinkEndChild(castShadowsNode);
  2151. castShadowsNode->SetAttribute("sid", "cast_shadows");
  2152. castShadowsNode->SetAttribute("type", "bool");
  2153. tinyxml2::XMLText* castShadowsText = doc->NewText("1");
  2154. castShadowsNode->LinkEndChild(castShadowsText);
  2155. //-----------------------------
  2156. tinyxml2::XMLElement* receiveShadowsNode = doc->NewElement("receive_shadows");
  2157. extraInsGeoTechNode->LinkEndChild(receiveShadowsNode);
  2158. receiveShadowsNode->SetAttribute("sid", "receive_shadows");
  2159. receiveShadowsNode->SetAttribute("type", "bool");
  2160. tinyxml2::XMLText* receiveShadowsText = doc->NewText("1");
  2161. receiveShadowsNode->LinkEndChild(receiveShadowsText);
  2162. //-----------------------------
  2163. tinyxml2::XMLElement* primaryVisibiltyNode = doc->NewElement("primary_visibility");
  2164. extraInsGeoTechNode->LinkEndChild(primaryVisibiltyNode);
  2165. primaryVisibiltyNode->SetAttribute("sid", "primary_visibility");
  2166. primaryVisibiltyNode->SetAttribute("type", "int");
  2167. tinyxml2::XMLText* primaryVisibiltyText = doc->NewText("1");
  2168. primaryVisibiltyNode->LinkEndChild(primaryVisibiltyText);
  2169. //-----------------------------
  2170. tinyxml2::XMLElement* secondaryVisibilityNode = doc->NewElement("secondary_visibility");
  2171. extraInsGeoTechNode->LinkEndChild(secondaryVisibilityNode);
  2172. secondaryVisibilityNode->SetAttribute("sid", "secondary_visibility");
  2173. secondaryVisibilityNode->SetAttribute("type", "int");
  2174. tinyxml2::XMLText* secondaryVisibilityText = doc->NewText("1");
  2175. secondaryVisibilityNode->LinkEndChild(secondaryVisibilityText);
  2176. // Extra info useful for COLLADAMaya importer (OpenCOLLADA)
  2177. tinyxml2::XMLElement* extra2InsGeoNode = doc->NewElement("extra");
  2178. nodeNode->LinkEndChild(extra2InsGeoNode);
  2179. tinyxml2::XMLElement* extra2InsGeoTechNode = doc->NewElement("technique");
  2180. extra2InsGeoNode->LinkEndChild(extra2InsGeoTechNode);
  2181. extra2InsGeoTechNode->SetAttribute("profile", "OpenCOLLADAMaya");
  2182. tinyxml2::XMLElement* mayaNodeId = doc->NewElement("originalMayaNodeId");
  2183. extra2InsGeoTechNode->LinkEndChild(mayaNodeId);
  2184. mayaNodeId->SetAttribute("sid", "originalMayaNodeId");
  2185. mayaNodeId->SetAttribute("type", "string");
  2186. tinyxml2::XMLText* mayaNodeIdMesh = doc->NewText(lodMeshName);
  2187. mayaNodeId->LinkEndChild(mayaNodeIdMesh);
  2188. tinyxml2::XMLElement* paramExtraNode = doc->NewElement("param");
  2189. extra2InsGeoTechNode->LinkEndChild(paramExtraNode);
  2190. paramExtraNode->SetAttribute("sid", "colladaId");
  2191. paramExtraNode->SetAttribute("type", "string");
  2192. tinyxml2::XMLText* mayaParamMesh = doc->NewText(lodMeshName);
  2193. paramExtraNode->LinkEndChild(mayaParamMesh);
  2194. }
  2195. //Collisions
  2196. for (U32 d = 0; d < exportData.colMeshes.size(); d++)
  2197. {
  2198. const char* colMeshName = exportData.colMeshes[d].colMeshName;
  2199. tinyxml2::XMLElement* nodeNode = doc->NewElement("node");
  2200. visSceneNode->LinkEndChild(nodeNode);
  2201. nodeNode->SetAttribute("id", colMeshName);
  2202. nodeNode->SetAttribute("name", colMeshName);
  2203. nodeNode->SetAttribute("type", "NODE");
  2204. tinyxml2::XMLElement* instanceGeomNode = doc->NewElement("instance_geometry");
  2205. nodeNode->LinkEndChild(instanceGeomNode);
  2206. instanceGeomNode->SetAttribute("url", avar("#%s-mesh", colMeshName));
  2207. instanceGeomNode->SetAttribute("name", colMeshName);
  2208. tinyxml2::XMLElement* bindMatNode = doc->NewElement("bind_material");
  2209. instanceGeomNode->LinkEndChild(bindMatNode);
  2210. tinyxml2::XMLElement* techniqueNode = doc->NewElement("technique_common");
  2211. bindMatNode->LinkEndChild(techniqueNode);
  2212. tinyxml2::XMLElement* instMatNode = doc->NewElement("instance_material");
  2213. techniqueNode->LinkEndChild(instMatNode);
  2214. instMatNode->SetAttribute("symbol", avar("%s-material", colMeshName));
  2215. instMatNode->SetAttribute("target", avar("#%s-material", colMeshName));
  2216. tinyxml2::XMLElement* bindVertexNode = doc->NewElement("bind_vertex_input");
  2217. instMatNode->LinkEndChild(bindVertexNode);
  2218. //bindVertexNode->SetAttribute("semantic", avar("%s-mesh-map-0", meshName.c_str()));
  2219. bindVertexNode->SetAttribute("semantic", "UVMap");
  2220. bindVertexNode->SetAttribute("input_semantic", "TEXCOORD");
  2221. bindVertexNode->SetAttribute("input_set", "0");
  2222. // Extra info useful for COLLADAMax importer (OpenCOLLADA)
  2223. tinyxml2::XMLElement* extraInsGeoNode = doc->NewElement("extra");
  2224. nodeNode->LinkEndChild(extraInsGeoNode);
  2225. tinyxml2::XMLElement* extraInsGeoTechNode = doc->NewElement("technique");
  2226. extraInsGeoNode->LinkEndChild(extraInsGeoTechNode);
  2227. extraInsGeoTechNode->SetAttribute("profile", "OpenCOLLADA");
  2228. tinyxml2::XMLElement* castShadowsNode = doc->NewElement("cast_shadows");
  2229. extraInsGeoTechNode->LinkEndChild(castShadowsNode);
  2230. castShadowsNode->SetAttribute("sid", "cast_shadows");
  2231. castShadowsNode->SetAttribute("type", "bool");
  2232. tinyxml2::XMLText* castShadowsText = doc->NewText("1");
  2233. castShadowsNode->LinkEndChild(castShadowsText);
  2234. //-----------------------------
  2235. tinyxml2::XMLElement* receiveShadowsNode = doc->NewElement("receive_shadows");
  2236. extraInsGeoTechNode->LinkEndChild(receiveShadowsNode);
  2237. receiveShadowsNode->SetAttribute("sid", "receive_shadows");
  2238. receiveShadowsNode->SetAttribute("type", "bool");
  2239. tinyxml2::XMLText* receiveShadowsText = doc->NewText("1");
  2240. receiveShadowsNode->LinkEndChild(receiveShadowsText);
  2241. //-----------------------------
  2242. tinyxml2::XMLElement* primaryVisibiltyNode = doc->NewElement("primary_visibility");
  2243. extraInsGeoTechNode->LinkEndChild(primaryVisibiltyNode);
  2244. primaryVisibiltyNode->SetAttribute("sid", "primary_visibility");
  2245. primaryVisibiltyNode->SetAttribute("type", "int");
  2246. tinyxml2::XMLText* primaryVisibiltyText = doc->NewText("1");
  2247. primaryVisibiltyNode->LinkEndChild(primaryVisibiltyText);
  2248. //-----------------------------
  2249. tinyxml2::XMLElement* secondaryVisibilityNode = doc->NewElement("secondary_visibility");
  2250. extraInsGeoTechNode->LinkEndChild(secondaryVisibilityNode);
  2251. secondaryVisibilityNode->SetAttribute("sid", "secondary_visibility");
  2252. secondaryVisibilityNode->SetAttribute("type", "int");
  2253. tinyxml2::XMLText* secondaryVisibilityText = doc->NewText("1");
  2254. secondaryVisibilityNode->LinkEndChild(secondaryVisibilityText);
  2255. // Extra info useful for COLLADAMaya importer (OpenCOLLADA)
  2256. tinyxml2::XMLElement* extra2InsGeoNode = doc->NewElement("extra");
  2257. nodeNode->LinkEndChild(extra2InsGeoNode);
  2258. tinyxml2::XMLElement* extra2InsGeoTechNode = doc->NewElement("technique");
  2259. extra2InsGeoNode->LinkEndChild(extra2InsGeoTechNode);
  2260. extra2InsGeoTechNode->SetAttribute("profile", "OpenCOLLADAMaya");
  2261. tinyxml2::XMLElement* mayaNodeId = doc->NewElement("originalMayaNodeId");
  2262. extra2InsGeoTechNode->LinkEndChild(mayaNodeId);
  2263. mayaNodeId->SetAttribute("sid", "originalMayaNodeId");
  2264. mayaNodeId->SetAttribute("type", "string");
  2265. tinyxml2::XMLText* mayaNodeIdMesh = doc->NewText(colMeshName);
  2266. mayaNodeId->LinkEndChild(mayaNodeIdMesh);
  2267. tinyxml2::XMLElement* paramExtraNode = doc->NewElement("param");
  2268. extra2InsGeoTechNode->LinkEndChild(paramExtraNode);
  2269. paramExtraNode->SetAttribute("sid", "colladaId");
  2270. paramExtraNode->SetAttribute("type", "string");
  2271. tinyxml2::XMLText* mayaParamMesh = doc->NewText(colMeshName);
  2272. paramExtraNode->LinkEndChild(mayaParamMesh);
  2273. }
  2274. //-----------------------------
  2275. tinyxml2::XMLElement* sceneNode = doc->NewElement("scene");
  2276. rootNode->LinkEndChild(sceneNode);
  2277. tinyxml2::XMLElement* instVisSceneNode = doc->NewElement("instance_visual_scene");
  2278. sceneNode->LinkEndChild(instVisSceneNode);
  2279. instVisSceneNode->SetAttribute("url", "#RootNode");
  2280. }
  2281. void ColladaUtils::exportToCollada(const Torque::Path& colladaFile, const OptimizedPolyList& mesh, const String& meshName)
  2282. {
  2283. // Get the mesh name
  2284. String outMeshName = meshName;
  2285. if (outMeshName.isEmpty())
  2286. outMeshName = colladaFile.getFileName();
  2287. // The XML document that will hold all of our data
  2288. VfsXMLDocument doc;
  2289. // Add a standard XML declaration to the top
  2290. tinyxml2::XMLDeclaration* xmlDecl = doc.NewDeclaration();
  2291. doc.LinkEndChild(xmlDecl);
  2292. // Create our Collada root node and populate a couple standard attributes
  2293. tinyxml2::XMLElement* rootNode = doc.NewElement("COLLADA");
  2294. rootNode->SetAttribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema");
  2295. rootNode->SetAttribute("version", "1.4.1");
  2296. //rootNode->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); //T3D Collada loader complaint about this.
  2297. // Add the root node to the document
  2298. doc.LinkEndChild(rootNode);
  2299. // Save out our header info
  2300. exportColladaHeader(rootNode);
  2301. // Save out the materials
  2302. Vector<String> mapNames;
  2303. exportColladaMaterials(rootNode, mesh, mapNames, colladaFile);
  2304. S32 suffix;
  2305. String baseMeshName = String::GetTrailingNumber(outMeshName, suffix);
  2306. // Save out our geometry
  2307. exportColladaMesh(rootNode, mesh, baseMeshName, mapNames);
  2308. // Save out our scene nodes
  2309. exportColladaScene(rootNode, baseMeshName, mapNames);
  2310. // Write out the actual Collada file
  2311. char fullPath[MAX_PATH_LENGTH];
  2312. Platform::makeFullPathName(colladaFile.getFullPath(), fullPath, MAX_PATH_LENGTH);
  2313. if (!doc.SaveFile(fullPath))
  2314. Con::errorf("ColladaUtils::exportToCollada(): Unable to export to %s", fullPath);
  2315. }
  2316. void ColladaUtils::exportToCollada(const Torque::Path& colladaFile, const ExportData& exportData)
  2317. {
  2318. // Get the mesh name
  2319. String outMeshName = colladaFile.getFileName();
  2320. // The XML document that will hold all of our data
  2321. VfsXMLDocument doc;
  2322. // Add a standard XML declaration to the top
  2323. tinyxml2::XMLDeclaration* xmlDecl = doc.NewDeclaration();
  2324. doc.LinkEndChild(xmlDecl);
  2325. // Create our Collada root node and populate a couple standard attributes
  2326. tinyxml2::XMLElement* rootNode = doc.NewElement("COLLADA");
  2327. rootNode->SetAttribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema");
  2328. rootNode->SetAttribute("version", "1.4.1");
  2329. //rootNode->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); //T3D Collada loader complaint about this.
  2330. // Add the root node to the document
  2331. doc.LinkEndChild(rootNode);
  2332. // Save out our header info
  2333. exportColladaHeader(rootNode);
  2334. // Save out the materials
  2335. Vector<String> mapNames;
  2336. exportColladaMaterials(rootNode, exportData, colladaFile);
  2337. S32 suffix;
  2338. String baseMeshName = String::GetTrailingNumber(outMeshName, suffix);
  2339. // Save out our geometry
  2340. exportColladaMesh(rootNode, exportData, baseMeshName);
  2341. // Save out our scene nodes
  2342. exportColladaScene(rootNode, exportData, baseMeshName);
  2343. // Write out the actual Collada file
  2344. char fullPath[MAX_PATH_LENGTH];
  2345. Platform::makeFullPathName(colladaFile.getFullPath(), fullPath, MAX_PATH_LENGTH);
  2346. if (!doc.SaveFile(fullPath))
  2347. Con::errorf("ColladaUtils::exportToCollada(): Unable to export to %s", fullPath);
  2348. }
  2349. void ColladaUtils::ExportData::processData()
  2350. {
  2351. //This pref dictates if we 'backfill' lower LODs with higher ones if any given mesh being exported lacks that level.
  2352. //For example, if there are 2 meshes, and one has 500, 200, 100 and the other has 500 and 200 - if this setting is on, the second mesh
  2353. //will backfill the 200 to the 100 so it has all levels filled. If it's off, the second mesh will not render at the 100 level
  2354. bool fillLowDetailLevels = dAtob(Con::getVariable("$exportMesh::fillLowDetailLevels", "1"));
  2355. S32 numDetailLevels = numberOfDetailLevels();
  2356. detailLevels.clear();
  2357. detailLevels.setSize(numDetailLevels);
  2358. for (U32 meshNum = 0; meshNum < meshData.size(); ++meshNum)
  2359. {
  2360. for (U32 i = 0; i < numDetailLevels; ++i)
  2361. {
  2362. //Get our target size
  2363. S32 targetDetailLevelSize = getDetailLevelSize(i);
  2364. //alright, step through each meshdata and propagate the polyList info 'up' to fill
  2365. detailLevel* curDetail = &detailLevels[i];
  2366. curDetail->size = targetDetailLevelSize;
  2367. //Do we have a detail level for this?
  2368. S32 detailLevelIdx = -1;
  2369. for (S32 mdl = i; mdl >= 0; mdl--)
  2370. {
  2371. //walk backwards as needed to find our first valid detail level for this mesh. if we find none, just move on
  2372. S32 testDetailLevelSize = getDetailLevelSize(mdl);
  2373. detailLevelIdx = meshData[meshNum].hasDetailLevel(testDetailLevelSize);
  2374. if (detailLevelIdx != -1)
  2375. break;
  2376. }
  2377. if (detailLevelIdx == -1)
  2378. {
  2379. //found nothing backwards, so lets check if we're configured to back-fill the first detail levels
  2380. if (fillLowDetailLevels)
  2381. {
  2382. //if so, search forward, find the first valid detail and fill it in
  2383. for (S32 mdl = 0; mdl < numDetailLevels; mdl++)
  2384. {
  2385. //walk backwards as needed to find our first valid detail level for this mesh. if we find none, just move on
  2386. S32 testDetailLevelSize = getDetailLevelSize(mdl);
  2387. detailLevelIdx = meshData[meshNum].hasDetailLevel(testDetailLevelSize);
  2388. if (detailLevelIdx != -1)
  2389. break;
  2390. }
  2391. }
  2392. }
  2393. //If we found the detail level index, go ahead and build out the data for it
  2394. if (detailLevelIdx != -1)
  2395. {
  2396. curDetail->mesh.setTransform(&meshData[meshNum].meshTransform, meshData[meshNum].scale);
  2397. curDetail->mesh.setObject(meshData[meshNum].originatingObject);
  2398. if (meshData[meshNum].shapeInst != nullptr)
  2399. {
  2400. if (!meshData[meshNum].shapeInst->buildPolyList(&curDetail->mesh, detailLevelIdx))
  2401. {
  2402. Con::errorf("TSStatic::buildExportPolyList - failed to build polylist for LOD %i", i);
  2403. continue;
  2404. }
  2405. }
  2406. else
  2407. {
  2408. //special handling classes
  2409. ConvexShape* convexShp = dynamic_cast<ConvexShape*>(meshData[meshNum].originatingObject);
  2410. if (convexShp != nullptr)
  2411. {
  2412. if (!convexShp->buildPolyList(PLC_Export, &curDetail->mesh, meshData[meshNum].originatingObject->getWorldBox(), meshData[meshNum].originatingObject->getWorldSphere()))
  2413. {
  2414. Con::errorf("TSStatic::buildExportPolyList - failed to build ConvexShape polylist for LOD %i", i);
  2415. continue;
  2416. }
  2417. }
  2418. }
  2419. //lastly, get material
  2420. for (U32 matNum = 0; matNum < curDetail->mesh.mMaterialList.size(); matNum++)
  2421. {
  2422. S32 matIdx = hasMaterialInstance(curDetail->mesh.mMaterialList[matNum]);
  2423. if (matIdx == -1)
  2424. {
  2425. //cool, haven't already got this material, so lets store it out
  2426. materials.push_back(curDetail->mesh.mMaterialList[matNum]);
  2427. curDetail->materialRefList.insert(matNum, materials.size() - 1);
  2428. }
  2429. else
  2430. {
  2431. curDetail->materialRefList.insert(matNum, matIdx);
  2432. }
  2433. }
  2434. }
  2435. }
  2436. }
  2437. }