tsShapeLoader.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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 "platform/platform.h"
  23. #include "console/engineAPI.h"
  24. #include "ts/loader/tsShapeLoader.h"
  25. #include "core/volume.h"
  26. #include "materials/materialList.h"
  27. #include "materials/matInstance.h"
  28. #include "materials/materialManager.h"
  29. #include "ts/tsShapeInstance.h"
  30. #include "ts/tsMaterialList.h"
  31. MODULE_BEGIN( ShapeLoader )
  32. MODULE_INIT_AFTER( GFX )
  33. MODULE_INIT
  34. {
  35. TSShapeLoader::addFormat("Torque DTS", "dts");
  36. TSShapeLoader::addFormat("Torque DSQ", "dsq");
  37. }
  38. MODULE_END;
  39. const F32 TSShapeLoader::DefaultTime = -1.0f;
  40. const double TSShapeLoader::MinFrameRate = 15.0f;
  41. const double TSShapeLoader::MaxFrameRate = 60.0f;
  42. const double TSShapeLoader::AppGroundFrameRate = 10.0f;
  43. Torque::Path TSShapeLoader::shapePath;
  44. Vector<TSShapeLoader::ShapeFormat> TSShapeLoader::smFormats;
  45. //------------------------------------------------------------------------------
  46. // Utility functions
  47. void TSShapeLoader::zapScale(MatrixF& mat)
  48. {
  49. Point3F invScale = mat.getScale();
  50. invScale.x = invScale.x ? (1.0f / invScale.x) : 0;
  51. invScale.y = invScale.y ? (1.0f / invScale.y) : 0;
  52. invScale.z = invScale.z ? (1.0f / invScale.z) : 0;
  53. mat.scale(invScale);
  54. }
  55. //------------------------------------------------------------------------------
  56. // Shape utility functions
  57. MatrixF TSShapeLoader::getLocalNodeMatrix(AppNode* node, F32 t)
  58. {
  59. MatrixF m1 = node->getNodeTransform(t);
  60. // multiply by inverse scale at t=0
  61. MatrixF m10 = node->getNodeTransform(DefaultTime);
  62. m1.scale(Point3F(1.0f/m10.getScale().x, 1.0f/m10.getScale().y, 1.0f/m10.getScale().z));
  63. if (node->mParentIndex >= 0)
  64. {
  65. AppNode *parent = appNodes[node->mParentIndex];
  66. MatrixF m2 = parent->getNodeTransform(t);
  67. // multiply by inverse scale at t=0
  68. MatrixF m20 = parent->getNodeTransform(DefaultTime);
  69. m2.scale(Point3F(1.0f/m20.getScale().x, 1.0f/m20.getScale().y, 1.0f/m20.getScale().z));
  70. // get local transform by pre-multiplying by inverted parent transform
  71. m1 = m2.inverse() * m1;
  72. }
  73. else if (boundsNode && node != boundsNode)
  74. {
  75. // make transform relative to bounds node transform at time=t
  76. MatrixF mb = boundsNode->getNodeTransform(t);
  77. zapScale(mb);
  78. m1 = mb.inverse() * m1;
  79. }
  80. return m1;
  81. }
  82. void TSShapeLoader::generateNodeTransform(AppNode* node, F32 t, bool blend, F32 referenceTime,
  83. QuatF& rot, Point3F& trans, QuatF& srot, Point3F& scale)
  84. {
  85. MatrixF m1 = getLocalNodeMatrix(node, t);
  86. if (blend)
  87. {
  88. MatrixF m0 = getLocalNodeMatrix(node, referenceTime);
  89. m1 = m0.inverse() * m1;
  90. }
  91. rot.set(m1);
  92. trans = m1.getPosition();
  93. srot.identity(); //@todo: srot not supported yet
  94. scale = m1.getScale();
  95. }
  96. //-----------------------------------------------------------------------------
  97. void TSShapeLoader::updateProgress(int major, const char* msg, int numMinor, int minor)
  98. {
  99. // Calculate progress value
  100. F32 progress = (F32)major / NumLoadPhases;
  101. const char *progressMsg = msg;
  102. if (numMinor)
  103. {
  104. progress += (minor * (1.0f / NumLoadPhases) / numMinor);
  105. progressMsg = avar("%s (%d of %d)", msg, minor + 1, numMinor);
  106. }
  107. Con::executef("updateTSShapeLoadProgress", Con::getFloatArg(progress), progressMsg);
  108. }
  109. //-----------------------------------------------------------------------------
  110. // Shape creation entry point
  111. TSShape* TSShapeLoader::generateShape(const Torque::Path& path)
  112. {
  113. shapePath = path;
  114. shape = new TSShape();
  115. shape->mExporterVersion = 124;
  116. shape->mSmallestVisibleSize = 999999;
  117. shape->mSmallestVisibleDL = 0;
  118. shape->mReadVersion = 24;
  119. shape->mFlags = 0;
  120. shape->mSequencesConstructed = 0;
  121. // Get all nodes, objects and sequences in the shape
  122. updateProgress(Load_EnumerateScene, "Enumerating scene...");
  123. enumerateScene();
  124. if (!subshapes.size())
  125. {
  126. delete shape;
  127. Con::errorf("Failed to load shape \"%s\", no subshapes found", path.getFullPath().c_str());
  128. return NULL;
  129. }
  130. // Create the TSShape::Node hierarchy
  131. generateSubshapes();
  132. // Create objects (meshes and details)
  133. generateObjects();
  134. // Generate initial object states and node transforms
  135. generateDefaultStates();
  136. // Generate skins
  137. generateSkins();
  138. // Generate material list
  139. generateMaterialList();
  140. // Generate animation sequences
  141. generateSequences();
  142. // Sort detail levels and meshes
  143. updateProgress(Load_InitShape, "Initialising shape...");
  144. sortDetails();
  145. // Install the TS memory helper into a TSShape object.
  146. install();
  147. return shape;
  148. }
  149. bool TSShapeLoader::processNode(AppNode* node)
  150. {
  151. // Detect bounds node
  152. if ( node->isBounds() )
  153. {
  154. if ( boundsNode )
  155. {
  156. Con::warnf( "More than one bounds node found" );
  157. return false;
  158. }
  159. boundsNode = node;
  160. // Process bounds geometry
  161. MatrixF boundsMat(boundsNode->getNodeTransform(DefaultTime));
  162. boundsMat.inverse();
  163. zapScale(boundsMat);
  164. for (S32 iMesh = 0; iMesh < boundsNode->getNumMesh(); iMesh++)
  165. {
  166. AppMesh* mesh = boundsNode->getMesh(iMesh);
  167. MatrixF transform = mesh->getMeshTransform(DefaultTime);
  168. transform.mulL(boundsMat);
  169. mesh->lockMesh(DefaultTime, transform);
  170. }
  171. return true;
  172. }
  173. // Detect sequence markers
  174. if ( node->isSequence() )
  175. {
  176. //appSequences.push_back(new AppSequence(node));
  177. return false;
  178. }
  179. // Add this node to the subshape (create one if needed)
  180. if ( subshapes.size() == 0 )
  181. subshapes.push_back( new TSShapeLoader::Subshape );
  182. subshapes.last()->branches.push_back( node );
  183. return true;
  184. }
  185. //-----------------------------------------------------------------------------
  186. // Nodes, meshes and skins
  187. typedef bool (*NameCmpFunc)(const String&, const Vector<String>&, void*, void*);
  188. bool cmpShapeName(const String& key, const Vector<String>& names, void* arg1, void* arg2)
  189. {
  190. for (S32 i = 0; i < names.size(); i++)
  191. {
  192. if (names[i].compare(key, 0, String::NoCase) == 0)
  193. return false;
  194. }
  195. return true;
  196. }
  197. String getUniqueName(const char* name, NameCmpFunc isNameUnique, const Vector<String>& names, void* arg1=0, void* arg2=0)
  198. {
  199. const int MAX_ITERATIONS = 0x10000; // maximum of 4 characters (A-P) will be appended
  200. String suffix;
  201. for (S32 i = 0; i < MAX_ITERATIONS; i++)
  202. {
  203. // Generate a suffix using the first 16 characters of the alphabet
  204. suffix.clear();
  205. for (S32 value = i; value != 0; value >>= 4)
  206. suffix = suffix + (char)('A' + (value & 0xF));
  207. String uname = name + suffix;
  208. if (isNameUnique(uname, names, arg1, arg2))
  209. return uname;
  210. }
  211. return name;
  212. }
  213. void TSShapeLoader::recurseSubshape(AppNode* appNode, S32 parentIndex, bool recurseChildren)
  214. {
  215. // Ignore local bounds nodes
  216. if (appNode->isBounds())
  217. return;
  218. S32 subShapeNum = shape->subShapeFirstNode.size()-1;
  219. Subshape* subshape = subshapes[subShapeNum];
  220. // Check if we should collapse this node
  221. S32 myIndex;
  222. if (ignoreNode(appNode->getName()))
  223. {
  224. myIndex = parentIndex;
  225. }
  226. else
  227. {
  228. // Check that adding this node will not exceed the maximum node count
  229. if (shape->nodes.size() >= MAX_TS_SET_SIZE)
  230. return;
  231. myIndex = shape->nodes.size();
  232. String nodeName = getUniqueName(appNode->getName(), cmpShapeName, shape->names);
  233. // Create the 3space node
  234. shape->nodes.increment();
  235. shape->nodes.last().nameIndex = shape->addName(nodeName);
  236. shape->nodes.last().parentIndex = parentIndex;
  237. shape->nodes.last().firstObject = -1;
  238. shape->nodes.last().firstChild = -1;
  239. shape->nodes.last().nextSibling = -1;
  240. // Add the AppNode to a matching list (so AppNodes can be accessed using 3space
  241. // node indices)
  242. appNodes.push_back(appNode);
  243. appNodes.last()->mParentIndex = parentIndex;
  244. // Check for NULL detail or AutoBillboard nodes (no children or geometry)
  245. if ((appNode->getNumChildNodes() == 0) &&
  246. (appNode->getNumMesh() == 0))
  247. {
  248. S32 size = 0x7FFFFFFF;
  249. String dname(String::GetTrailingNumber(appNode->getName(), size));
  250. if (dStrEqual(dname, "nulldetail") && (size != 0x7FFFFFFF))
  251. {
  252. shape->addDetail("detail", size, subShapeNum);
  253. }
  254. else if (appNode->isBillboard() && (size != 0x7FFFFFFF))
  255. {
  256. // AutoBillboard detail
  257. S32 numEquatorSteps = 4;
  258. S32 numPolarSteps = 0;
  259. F32 polarAngle = 0.0f;
  260. S32 dl = 0;
  261. S32 dim = 64;
  262. bool includePoles = true;
  263. appNode->getInt("BB::EQUATOR_STEPS", numEquatorSteps);
  264. appNode->getInt("BB::POLAR_STEPS", numPolarSteps);
  265. appNode->getFloat("BB::POLAR_ANGLE", polarAngle);
  266. appNode->getInt("BB::DL", dl);
  267. appNode->getInt("BB::DIM", dim);
  268. appNode->getBool("BB::INCLUDE_POLES", includePoles);
  269. S32 detIndex = shape->addDetail( "bbDetail", size, -1 );
  270. shape->details[detIndex].bbEquatorSteps = numEquatorSteps;
  271. shape->details[detIndex].bbPolarSteps = numPolarSteps;
  272. shape->details[detIndex].bbDetailLevel = dl;
  273. shape->details[detIndex].bbDimension = dim;
  274. shape->details[detIndex].bbIncludePoles = includePoles;
  275. shape->details[detIndex].bbPolarAngle = polarAngle;
  276. }
  277. }
  278. }
  279. // Collect geometry
  280. for (U32 iMesh = 0; iMesh < appNode->getNumMesh(); iMesh++)
  281. {
  282. AppMesh* mesh = appNode->getMesh(iMesh);
  283. if (!ignoreMesh(mesh->getName()))
  284. {
  285. subshape->objMeshes.push_back(mesh);
  286. subshape->objNodes.push_back(mesh->isSkin() ? -1 : myIndex);
  287. }
  288. }
  289. // Create children
  290. if (recurseChildren)
  291. {
  292. for (int iChild = 0; iChild < appNode->getNumChildNodes(); iChild++)
  293. recurseSubshape(appNode->getChildNode(iChild), myIndex, true);
  294. }
  295. }
  296. void TSShapeLoader::generateSubshapes()
  297. {
  298. for (U32 iSub = 0; iSub < subshapes.size(); iSub++)
  299. {
  300. updateProgress(Load_GenerateSubshapes, "Generating subshapes...", subshapes.size(), iSub);
  301. Subshape* subshape = subshapes[iSub];
  302. // Recurse through the node hierarchy, adding 3space nodes and
  303. // collecting geometry
  304. S32 firstNode = shape->nodes.size();
  305. shape->subShapeFirstNode.push_back(firstNode);
  306. for (U32 iBranch = 0; iBranch < subshape->branches.size(); iBranch++)
  307. recurseSubshape(subshape->branches[iBranch], -1, true);
  308. shape->subShapeNumNodes.push_back(shape->nodes.size() - firstNode);
  309. if (shape->nodes.size() >= MAX_TS_SET_SIZE)
  310. {
  311. Con::warnf("Shape exceeds the maximum node count (%d). Ignoring additional nodes.",
  312. MAX_TS_SET_SIZE);
  313. }
  314. }
  315. }
  316. // Custom name comparison function to compare mesh name and detail size
  317. bool cmpMeshNameAndSize(const String& key, const Vector<String>& names, void* arg1, void* arg2)
  318. {
  319. const Vector<AppMesh*>& meshes = *(Vector<AppMesh*>*)arg1;
  320. S32 meshSize = (S32)arg2;
  321. for (S32 i = 0; i < names.size(); i++)
  322. {
  323. if (names[i].compare(key, 0, String::NoCase) == 0)
  324. {
  325. if (meshes[i]->detailSize == meshSize)
  326. return false;
  327. }
  328. }
  329. return true;
  330. }
  331. void TSShapeLoader::generateObjects()
  332. {
  333. for (S32 iSub = 0; iSub < subshapes.size(); iSub++)
  334. {
  335. Subshape* subshape = subshapes[iSub];
  336. shape->subShapeFirstObject.push_back(shape->objects.size());
  337. // Get the names and sizes of the meshes for this subshape
  338. Vector<String> meshNames;
  339. for (S32 iMesh = 0; iMesh < subshape->objMeshes.size(); iMesh++)
  340. {
  341. AppMesh* mesh = subshape->objMeshes[iMesh];
  342. mesh->detailSize = 2;
  343. String name = String::GetTrailingNumber( mesh->getName(), mesh->detailSize );
  344. name = getUniqueName( name, cmpMeshNameAndSize, meshNames, &(subshape->objMeshes), (void*)mesh->detailSize );
  345. meshNames.push_back( name );
  346. // Fix up any collision details that don't have a negative detail level.
  347. if ( dStrStartsWith(meshNames[iMesh], "Collision") ||
  348. dStrStartsWith(meshNames[iMesh], "LOSCol") )
  349. {
  350. if (mesh->detailSize > 0)
  351. mesh->detailSize = -mesh->detailSize;
  352. }
  353. }
  354. // An 'object' is a collection of meshes with the same base name and
  355. // different detail sizes. The object is attached to the node of the
  356. // highest detail mesh.
  357. // Sort the 3 arrays (objMeshes, objNodes, meshNames) by name and size
  358. for (S32 i = 0; i < subshape->objMeshes.size()-1; i++)
  359. {
  360. for (S32 j = i+1; j < subshape->objMeshes.size(); j++)
  361. {
  362. if ((meshNames[i].compare(meshNames[j]) < 0) ||
  363. ((meshNames[i].compare(meshNames[j]) == 0) &&
  364. (subshape->objMeshes[i]->detailSize < subshape->objMeshes[j]->detailSize)))
  365. {
  366. {
  367. AppMesh* tmp = subshape->objMeshes[i];
  368. subshape->objMeshes[i] = subshape->objMeshes[j];
  369. subshape->objMeshes[j] = tmp;
  370. }
  371. {
  372. S32 tmp = subshape->objNodes[i];
  373. subshape->objNodes[i] = subshape->objNodes[j];
  374. subshape->objNodes[j] = tmp;
  375. }
  376. {
  377. String tmp = meshNames[i];
  378. meshNames[i] = meshNames[j];
  379. meshNames[j] = tmp;
  380. }
  381. }
  382. }
  383. }
  384. // Now create objects
  385. const String* lastName = 0;
  386. for (S32 iMesh = 0; iMesh < subshape->objMeshes.size(); iMesh++)
  387. {
  388. AppMesh* mesh = subshape->objMeshes[iMesh];
  389. if (!lastName || (meshNames[iMesh] != *lastName))
  390. {
  391. shape->objects.increment();
  392. shape->objects.last().nameIndex = shape->addName(meshNames[iMesh]);
  393. shape->objects.last().nodeIndex = subshape->objNodes[iMesh];
  394. shape->objects.last().startMeshIndex = appMeshes.size();
  395. shape->objects.last().numMeshes = 0;
  396. lastName = &meshNames[iMesh];
  397. }
  398. // Add this mesh to the object
  399. appMeshes.push_back(mesh);
  400. shape->objects.last().numMeshes++;
  401. // Set mesh flags
  402. mesh->flags = 0;
  403. if (mesh->isBillboard())
  404. {
  405. mesh->flags |= TSMesh::Billboard;
  406. if (mesh->isBillboardZAxis())
  407. mesh->flags |= TSMesh::BillboardZAxis;
  408. }
  409. // Set the detail name... do fixups for collision details.
  410. const char* detailName = "detail";
  411. if ( mesh->detailSize < 0 )
  412. {
  413. if ( dStrStartsWith(meshNames[iMesh], "Collision") ||
  414. dStrStartsWith(meshNames[iMesh], "Col") )
  415. detailName = "Collision";
  416. else if (dStrStartsWith(meshNames[iMesh], "LOSCol"))
  417. detailName = "LOS";
  418. }
  419. // Attempt to add the detail (will fail if it already exists)
  420. S32 oldNumDetails = shape->details.size();
  421. shape->addDetail(detailName, mesh->detailSize, iSub);
  422. if (shape->details.size() > oldNumDetails)
  423. {
  424. Con::warnf("Object mesh \"%s\" has no matching detail (\"%s%d\" has"
  425. " been added automatically)", mesh->getName(false), detailName, mesh->detailSize);
  426. }
  427. }
  428. // Get object count for this subshape
  429. shape->subShapeNumObjects.push_back(shape->objects.size() - shape->subShapeFirstObject.last());
  430. }
  431. }
  432. void TSShapeLoader::generateSkins()
  433. {
  434. Vector<AppMesh*> skins;
  435. for (int iObject = 0; iObject < shape->objects.size(); iObject++)
  436. {
  437. for (int iMesh = 0; iMesh < shape->objects[iObject].numMeshes; iMesh++)
  438. {
  439. AppMesh* mesh = appMeshes[shape->objects[iObject].startMeshIndex + iMesh];
  440. if (mesh->isSkin())
  441. skins.push_back(mesh);
  442. }
  443. }
  444. for (int iSkin = 0; iSkin < skins.size(); iSkin++)
  445. {
  446. updateProgress(Load_GenerateSkins, "Generating skins...", skins.size(), iSkin);
  447. // Get skin data (bones, vertex weights etc)
  448. AppMesh* skin = skins[iSkin];
  449. skin->lookupSkinData();
  450. // Just copy initial verts and norms for now
  451. skin->initialVerts.set(skin->points.address(), skin->vertsPerFrame);
  452. skin->initialNorms.set(skin->normals.address(), skin->vertsPerFrame);
  453. // Map bones to nodes
  454. skin->nodeIndex.setSize(skin->bones.size());
  455. for (int iBone = 0; iBone < skin->bones.size(); iBone++)
  456. {
  457. // Find the node that matches this bone
  458. skin->nodeIndex[iBone] = -1;
  459. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  460. {
  461. if (appNodes[iNode]->isEqual(skin->bones[iBone]))
  462. {
  463. delete skin->bones[iBone];
  464. skin->bones[iBone] = appNodes[iNode];
  465. skin->nodeIndex[iBone] = iNode;
  466. break;
  467. }
  468. }
  469. if (skin->nodeIndex[iBone] == -1)
  470. {
  471. Con::warnf("Could not find bone %d. Defaulting to first node", iBone);
  472. skin->nodeIndex[iBone] = 0;
  473. }
  474. }
  475. }
  476. }
  477. void TSShapeLoader::generateDefaultStates()
  478. {
  479. // Generate default object states (includes initial geometry)
  480. for (int iObject = 0; iObject < shape->objects.size(); iObject++)
  481. {
  482. updateProgress(Load_GenerateDefaultStates, "Generating initial mesh and node states...",
  483. shape->objects.size(), iObject);
  484. TSShape::Object& obj = shape->objects[iObject];
  485. // Calculate the objectOffset for each mesh at T=0
  486. for (int iMesh = 0; iMesh < obj.numMeshes; iMesh++)
  487. {
  488. AppMesh* appMesh = appMeshes[obj.startMeshIndex + iMesh];
  489. AppNode* appNode = obj.nodeIndex >= 0 ? appNodes[obj.nodeIndex] : boundsNode;
  490. MatrixF meshMat(appMesh->getMeshTransform(DefaultTime));
  491. MatrixF nodeMat(appMesh->isSkin() ? meshMat : appNode->getNodeTransform(DefaultTime));
  492. zapScale(nodeMat);
  493. appMesh->objectOffset = nodeMat.inverse() * meshMat;
  494. }
  495. generateObjectState(shape->objects[iObject], DefaultTime, true, true);
  496. }
  497. // Generate default node transforms
  498. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  499. {
  500. // Determine the default translation and rotation for the node
  501. QuatF rot, srot;
  502. Point3F trans, scale;
  503. generateNodeTransform(appNodes[iNode], DefaultTime, false, 0, rot, trans, srot, scale);
  504. // Add default node translation and rotation
  505. addNodeRotation(rot, true);
  506. addNodeTranslation(trans, true);
  507. }
  508. }
  509. void TSShapeLoader::generateObjectState(TSShape::Object& obj, F32 t, bool addFrame, bool addMatFrame)
  510. {
  511. shape->objectStates.increment();
  512. TSShape::ObjectState& state = shape->objectStates.last();
  513. state.frameIndex = 0;
  514. state.matFrameIndex = 0;
  515. state.vis = mClampF(appMeshes[obj.startMeshIndex]->getVisValue(t), 0.0f, 1.0f);
  516. if (addFrame || addMatFrame)
  517. {
  518. generateFrame(obj, t, addFrame, addMatFrame);
  519. // set the frame number for the object state
  520. state.frameIndex = appMeshes[obj.startMeshIndex]->numFrames - 1;
  521. state.matFrameIndex = appMeshes[obj.startMeshIndex]->numMatFrames - 1;
  522. }
  523. }
  524. void TSShapeLoader::generateFrame(TSShape::Object& obj, F32 t, bool addFrame, bool addMatFrame)
  525. {
  526. for (int iMesh = 0; iMesh < obj.numMeshes; iMesh++)
  527. {
  528. AppMesh* appMesh = appMeshes[obj.startMeshIndex + iMesh];
  529. U32 oldNumPoints = appMesh->points.size();
  530. U32 oldNumUvs = appMesh->uvs.size();
  531. // Get the mesh geometry at time, 't'
  532. // Geometry verts, normals and tverts can be animated (different set for
  533. // each frame), but the TSDrawPrimitives stay the same, so the way lockMesh
  534. // works is that it will only generate the primitives once, then after that
  535. // will just append verts, normals and tverts each time it is called.
  536. appMesh->lockMesh(t, appMesh->objectOffset);
  537. // Calculate vertex normals if required
  538. if (appMesh->normals.size() != appMesh->points.size())
  539. appMesh->computeNormals();
  540. // If this is the first call, set the number of points per frame
  541. if (appMesh->numFrames == 0)
  542. {
  543. appMesh->vertsPerFrame = appMesh->points.size();
  544. }
  545. else
  546. {
  547. // Check frame topology => ie. that the right number of points, normals
  548. // and tverts was added
  549. if ((appMesh->points.size() - oldNumPoints) != appMesh->vertsPerFrame)
  550. {
  551. Con::warnf("Wrong number of points (%d) added at time=%f (expected %d)",
  552. appMesh->points.size() - oldNumPoints, t, appMesh->vertsPerFrame);
  553. addFrame = false;
  554. }
  555. if ((appMesh->normals.size() - oldNumPoints) != appMesh->vertsPerFrame)
  556. {
  557. Con::warnf("Wrong number of normals (%d) added at time=%f (expected %d)",
  558. appMesh->normals.size() - oldNumPoints, t, appMesh->vertsPerFrame);
  559. addFrame = false;
  560. }
  561. if ((appMesh->uvs.size() - oldNumUvs) != appMesh->vertsPerFrame)
  562. {
  563. Con::warnf("Wrong number of tverts (%d) added at time=%f (expected %d)",
  564. appMesh->uvs.size() - oldNumUvs, t, appMesh->vertsPerFrame);
  565. addMatFrame = false;
  566. }
  567. }
  568. // Because lockMesh adds points, normals AND tverts each call, if we didn't
  569. // actually want another frame or matFrame, we need to remove them afterwards.
  570. // In the common case (we DO want the frame), we can do nothing => the
  571. // points/normals/tverts are already in place!
  572. if (addFrame)
  573. {
  574. appMesh->numFrames++;
  575. }
  576. else
  577. {
  578. appMesh->points.setSize(oldNumPoints);
  579. appMesh->normals.setSize(oldNumPoints);
  580. }
  581. if (addMatFrame)
  582. {
  583. appMesh->numMatFrames++;
  584. }
  585. else
  586. {
  587. appMesh->uvs.setSize(oldNumPoints);
  588. }
  589. }
  590. }
  591. //-----------------------------------------------------------------------------
  592. // Materials
  593. /// Convert all Collada materials into a single TSMaterialList
  594. void TSShapeLoader::generateMaterialList()
  595. {
  596. // Install the materials into the material list
  597. shape->materialList = new TSMaterialList;
  598. for (int iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++)
  599. {
  600. updateProgress(Load_GenerateMaterials, "Generating materials...", AppMesh::appMaterials.size(), iMat);
  601. AppMaterial* appMat = AppMesh::appMaterials[iMat];
  602. shape->materialList->push_back(appMat->getName(), appMat->getFlags(), U32(-1), U32(-1), U32(-1), 1.0f, appMat->getReflectance());
  603. }
  604. }
  605. //-----------------------------------------------------------------------------
  606. // Animation Sequences
  607. void TSShapeLoader::generateSequences()
  608. {
  609. for (int iSeq = 0; iSeq < appSequences.size(); iSeq++)
  610. {
  611. updateProgress(Load_GenerateSequences, "Generating sequences...", appSequences.size(), iSeq);
  612. // Initialize the sequence
  613. appSequences[iSeq]->setActive(true);
  614. shape->sequences.increment();
  615. TSShape::Sequence& seq = shape->sequences.last();
  616. seq.nameIndex = shape->addName(appSequences[iSeq]->getName());
  617. seq.toolBegin = appSequences[iSeq]->getStart();
  618. seq.priority = appSequences[iSeq]->getPriority();
  619. seq.flags = appSequences[iSeq]->getFlags();
  620. // Compute duration and number of keyframes (then adjust time between frames to match)
  621. seq.duration = appSequences[iSeq]->getEnd() - appSequences[iSeq]->getStart();
  622. seq.numKeyframes = (S32)(seq.duration * appSequences[iSeq]->fps + 0.5f) + 1;
  623. seq.sourceData.start = 0;
  624. seq.sourceData.end = seq.numKeyframes-1;
  625. seq.sourceData.total = seq.numKeyframes;
  626. // Set membership arrays (ie. which nodes and objects are affected by this sequence)
  627. setNodeMembership(seq, appSequences[iSeq]);
  628. setObjectMembership(seq, appSequences[iSeq]);
  629. // Generate keyframes
  630. generateNodeAnimation(seq);
  631. generateObjectAnimation(seq, appSequences[iSeq]);
  632. generateGroundAnimation(seq, appSequences[iSeq]);
  633. generateFrameTriggers(seq, appSequences[iSeq]);
  634. // Set sequence flags
  635. seq.dirtyFlags = 0;
  636. if (seq.rotationMatters.testAll() || seq.translationMatters.testAll() || seq.scaleMatters.testAll())
  637. seq.dirtyFlags |= TSShapeInstance::TransformDirty;
  638. if (seq.visMatters.testAll())
  639. seq.dirtyFlags |= TSShapeInstance::VisDirty;
  640. if (seq.frameMatters.testAll())
  641. seq.dirtyFlags |= TSShapeInstance::FrameDirty;
  642. if (seq.matFrameMatters.testAll())
  643. seq.dirtyFlags |= TSShapeInstance::MatFrameDirty;
  644. // Set shape flags (only the most significant scale type)
  645. U32 curVal = shape->mFlags & TSShape::AnyScale;
  646. shape->mFlags &= ~(TSShape::AnyScale);
  647. shape->mFlags |= getMax(curVal, seq.flags & TSShape::AnyScale); // take the larger value (can only convert upwards)
  648. appSequences[iSeq]->setActive(false);
  649. }
  650. }
  651. void TSShapeLoader::setNodeMembership(TSShape::Sequence& seq, const AppSequence* appSeq)
  652. {
  653. seq.rotationMatters.clearAll(); // node rotation (size = nodes.size())
  654. seq.translationMatters.clearAll(); // node translation (size = nodes.size())
  655. seq.scaleMatters.clearAll(); // node scale (size = nodes.size())
  656. // This shouldn't be allowed, but check anyway...
  657. if (seq.numKeyframes < 2)
  658. return;
  659. // Note: this fills the cache with current sequence data. Methods that get
  660. // called later (e.g. generateNodeAnimation) use this info (and assume it's set).
  661. fillNodeTransformCache(seq, appSeq);
  662. // Test to see if the transform changes over the interval in order to decide
  663. // whether to animate the transform in 3space. We don't use app's mechanism
  664. // for doing this because it functions different in different apps and we do
  665. // some special stuff with scale.
  666. setRotationMembership(seq);
  667. setTranslationMembership(seq);
  668. setScaleMembership(seq);
  669. }
  670. void TSShapeLoader::setRotationMembership(TSShape::Sequence& seq)
  671. {
  672. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  673. {
  674. // Check if any of the node rotations are different to
  675. // the default rotation
  676. QuatF defaultRot;
  677. shape->defaultRotations[iNode].getQuatF(&defaultRot);
  678. for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  679. {
  680. if (nodeRotCache[iNode][iFrame] != defaultRot)
  681. {
  682. seq.rotationMatters.set(iNode);
  683. break;
  684. }
  685. }
  686. }
  687. }
  688. void TSShapeLoader::setTranslationMembership(TSShape::Sequence& seq)
  689. {
  690. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  691. {
  692. // Check if any of the node translations are different to
  693. // the default translation
  694. Point3F& defaultTrans = shape->defaultTranslations[iNode];
  695. for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  696. {
  697. if (!nodeTransCache[iNode][iFrame].equal(defaultTrans))
  698. {
  699. seq.translationMatters.set(iNode);
  700. break;
  701. }
  702. }
  703. }
  704. }
  705. void TSShapeLoader::setScaleMembership(TSShape::Sequence& seq)
  706. {
  707. Point3F unitScale(1,1,1);
  708. U32 arbitraryScaleCount = 0;
  709. U32 alignedScaleCount = 0;
  710. U32 uniformScaleCount = 0;
  711. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  712. {
  713. // Check if any of the node scales are not the unit scale
  714. for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  715. {
  716. Point3F& scale = nodeScaleCache[iNode][iFrame];
  717. if (!unitScale.equal(scale))
  718. {
  719. // Determine what type of scale this is
  720. if (!nodeScaleRotCache[iNode][iFrame].isIdentity())
  721. arbitraryScaleCount++;
  722. else if (scale.x != scale.y || scale.y != scale.z)
  723. alignedScaleCount++;
  724. else
  725. uniformScaleCount++;
  726. seq.scaleMatters.set(iNode);
  727. break;
  728. }
  729. }
  730. }
  731. // Only one type of scale is animated
  732. if (arbitraryScaleCount)
  733. seq.flags |= TSShape::ArbitraryScale;
  734. else if (alignedScaleCount)
  735. seq.flags |= TSShape::AlignedScale;
  736. else if (uniformScaleCount)
  737. seq.flags |= TSShape::UniformScale;
  738. }
  739. void TSShapeLoader::setObjectMembership(TSShape::Sequence& seq, const AppSequence* appSeq)
  740. {
  741. seq.visMatters.clearAll(); // object visibility (size = objects.size())
  742. seq.frameMatters.clearAll(); // vert animation (morph) (size = objects.size())
  743. seq.matFrameMatters.clearAll(); // UV animation (size = objects.size())
  744. for (int iObject = 0; iObject < shape->objects.size(); iObject++)
  745. {
  746. if (!appMeshes[shape->objects[iObject].startMeshIndex])
  747. continue;
  748. if (appMeshes[shape->objects[iObject].startMeshIndex]->animatesVis(appSeq))
  749. seq.visMatters.set(iObject);
  750. // Morph and UV animation has been deprecated
  751. //if (appMeshes[shape->objects[iObject].startMeshIndex]->animatesFrame(appSeq))
  752. //seq.frameMatters.set(iObject);
  753. //if (appMeshes[shape->objects[iObject].startMeshIndex]->animatesMatFrame(appSeq))
  754. //seq.matFrameMatters.set(iObject);
  755. }
  756. }
  757. void TSShapeLoader::clearNodeTransformCache()
  758. {
  759. // clear out the transform caches
  760. for (int i = 0; i < nodeRotCache.size(); i++)
  761. delete [] nodeRotCache[i];
  762. nodeRotCache.clear();
  763. for (int i = 0; i < nodeTransCache.size(); i++)
  764. delete [] nodeTransCache[i];
  765. nodeTransCache.clear();
  766. for (int i = 0; i < nodeScaleRotCache.size(); i++)
  767. delete [] nodeScaleRotCache[i];
  768. nodeScaleRotCache.clear();
  769. for (int i = 0; i < nodeScaleCache.size(); i++)
  770. delete [] nodeScaleCache[i];
  771. nodeScaleCache.clear();
  772. }
  773. void TSShapeLoader::fillNodeTransformCache(TSShape::Sequence& seq, const AppSequence* appSeq)
  774. {
  775. // clear out the transform caches and set it up for this sequence
  776. clearNodeTransformCache();
  777. nodeRotCache.setSize(appNodes.size());
  778. for (int i = 0; i < nodeRotCache.size(); i++)
  779. nodeRotCache[i] = new QuatF[seq.numKeyframes];
  780. nodeTransCache.setSize(appNodes.size());
  781. for (int i = 0; i < nodeTransCache.size(); i++)
  782. nodeTransCache[i] = new Point3F[seq.numKeyframes];
  783. nodeScaleRotCache.setSize(appNodes.size());
  784. for (int i = 0; i < nodeScaleRotCache.size(); i++)
  785. nodeScaleRotCache[i] = new QuatF[seq.numKeyframes];
  786. nodeScaleCache.setSize(appNodes.size());
  787. for (int i = 0; i < nodeScaleCache.size(); i++)
  788. nodeScaleCache[i] = new Point3F[seq.numKeyframes];
  789. // get the node transforms for every frame
  790. for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  791. {
  792. F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numKeyframes - 1);
  793. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  794. {
  795. generateNodeTransform(appNodes[iNode], time, seq.isBlend(), appSeq->getBlendRefTime(),
  796. nodeRotCache[iNode][iFrame], nodeTransCache[iNode][iFrame],
  797. nodeScaleRotCache[iNode][iFrame], nodeScaleCache[iNode][iFrame]);
  798. }
  799. }
  800. }
  801. void TSShapeLoader::addNodeRotation(QuatF& rot, bool defaultVal)
  802. {
  803. Quat16 rot16;
  804. rot16.set(rot);
  805. if (!defaultVal)
  806. shape->nodeRotations.push_back(rot16);
  807. else
  808. shape->defaultRotations.push_back(rot16);
  809. }
  810. void TSShapeLoader::addNodeTranslation(Point3F& trans, bool defaultVal)
  811. {
  812. if (!defaultVal)
  813. shape->nodeTranslations.push_back(trans);
  814. else
  815. shape->defaultTranslations.push_back(trans);
  816. }
  817. void TSShapeLoader::addNodeUniformScale(F32 scale)
  818. {
  819. shape->nodeUniformScales.push_back(scale);
  820. }
  821. void TSShapeLoader::addNodeAlignedScale(Point3F& scale)
  822. {
  823. shape->nodeAlignedScales.push_back(scale);
  824. }
  825. void TSShapeLoader::addNodeArbitraryScale(QuatF& qrot, Point3F& scale)
  826. {
  827. Quat16 rot16;
  828. rot16.set(qrot);
  829. shape->nodeArbitraryScaleRots.push_back(rot16);
  830. shape->nodeArbitraryScaleFactors.push_back(scale);
  831. }
  832. void TSShapeLoader::generateNodeAnimation(TSShape::Sequence& seq)
  833. {
  834. seq.baseRotation = shape->nodeRotations.size();
  835. seq.baseTranslation = shape->nodeTranslations.size();
  836. seq.baseScale = (seq.flags & TSShape::ArbitraryScale) ? shape->nodeArbitraryScaleRots.size() :
  837. (seq.flags & TSShape::AlignedScale) ? shape->nodeAlignedScales.size() :
  838. shape->nodeUniformScales.size();
  839. for (int iNode = 0; iNode < appNodes.size(); iNode++)
  840. {
  841. for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  842. {
  843. if (seq.rotationMatters.test(iNode))
  844. addNodeRotation(nodeRotCache[iNode][iFrame], false);
  845. if (seq.translationMatters.test(iNode))
  846. addNodeTranslation(nodeTransCache[iNode][iFrame], false);
  847. if (seq.scaleMatters.test(iNode))
  848. {
  849. QuatF& rot = nodeScaleRotCache[iNode][iFrame];
  850. Point3F scale = nodeScaleCache[iNode][iFrame];
  851. if (seq.flags & TSShape::ArbitraryScale)
  852. addNodeArbitraryScale(rot, scale);
  853. else if (seq.flags & TSShape::AlignedScale)
  854. addNodeAlignedScale(scale);
  855. else if (seq.flags & TSShape::UniformScale)
  856. addNodeUniformScale((scale.x+scale.y+scale.z)/3.0f);
  857. }
  858. }
  859. }
  860. }
  861. void TSShapeLoader::generateObjectAnimation(TSShape::Sequence& seq, const AppSequence* appSeq)
  862. {
  863. seq.baseObjectState = shape->objectStates.size();
  864. for (int iObject = 0; iObject < shape->objects.size(); iObject++)
  865. {
  866. bool visMatters = seq.visMatters.test(iObject);
  867. bool frameMatters = seq.frameMatters.test(iObject);
  868. bool matFrameMatters = seq.matFrameMatters.test(iObject);
  869. if (visMatters || frameMatters || matFrameMatters)
  870. {
  871. for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  872. {
  873. F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numKeyframes - 1);
  874. generateObjectState(shape->objects[iObject], time, frameMatters, matFrameMatters);
  875. }
  876. }
  877. }
  878. }
  879. void TSShapeLoader::generateGroundAnimation(TSShape::Sequence& seq, const AppSequence* appSeq)
  880. {
  881. seq.firstGroundFrame = shape->groundTranslations.size();
  882. seq.numGroundFrames = 0;
  883. if (!boundsNode)
  884. return;
  885. // Check if the bounds node is animated by this sequence
  886. seq.numGroundFrames = (S32)((seq.duration + 0.25f/AppGroundFrameRate) * AppGroundFrameRate);
  887. seq.flags |= TSShape::MakePath;
  888. // Get ground transform at the start of the sequence
  889. MatrixF invStartMat = boundsNode->getNodeTransform(appSeq->getStart());
  890. zapScale(invStartMat);
  891. invStartMat.inverse();
  892. for (int iFrame = 0; iFrame < seq.numGroundFrames; iFrame++)
  893. {
  894. F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numGroundFrames - 1);
  895. // Determine delta bounds node transform at 't'
  896. MatrixF mat = boundsNode->getNodeTransform(time);
  897. zapScale(mat);
  898. mat = invStartMat * mat;
  899. // Add ground transform
  900. Quat16 rotation;
  901. rotation.set(QuatF(mat));
  902. shape->groundTranslations.push_back(mat.getPosition());
  903. shape->groundRotations.push_back(rotation);
  904. }
  905. }
  906. void TSShapeLoader::generateFrameTriggers(TSShape::Sequence& seq, const AppSequence* appSeq)
  907. {
  908. // Initialize triggers
  909. seq.firstTrigger = shape->triggers.size();
  910. seq.numTriggers = appSeq->getNumTriggers();
  911. if (!seq.numTriggers)
  912. return;
  913. seq.flags |= TSShape::MakePath;
  914. // Add triggers
  915. for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++)
  916. {
  917. shape->triggers.increment();
  918. appSeq->getTrigger(iTrigger, shape->triggers.last());
  919. }
  920. // Track the triggers that get turned off by this shape...normally, triggers
  921. // aren't turned on/off, just on...if we are a trigger that does both then we
  922. // need to mark ourselves as such so that on/off can become off/on when sequence
  923. // is played in reverse...
  924. U32 offTriggers = 0;
  925. for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++)
  926. {
  927. U32 state = shape->triggers[seq.firstTrigger+iTrigger].state;
  928. if ((state & TSShape::Trigger::StateOn) == 0)
  929. offTriggers |= (state & TSShape::Trigger::StateMask);
  930. }
  931. // We now know which states are turned off, set invert on all those (including when turned on)
  932. for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++)
  933. {
  934. if (shape->triggers[seq.firstTrigger + iTrigger].state & offTriggers)
  935. shape->triggers[seq.firstTrigger + iTrigger].state |= TSShape::Trigger::InvertOnReverse;
  936. }
  937. }
  938. //-----------------------------------------------------------------------------
  939. void TSShapeLoader::sortDetails()
  940. {
  941. // Sort objects by: transparency, material index and node index
  942. // Insert NULL meshes where required
  943. for (int iSub = 0; iSub < subshapes.size(); iSub++)
  944. {
  945. Vector<S32> validDetails;
  946. shape->getSubShapeDetails(iSub, validDetails);
  947. for (int iDet = 0; iDet < validDetails.size(); iDet++)
  948. {
  949. TSShape::Detail &detail = shape->details[validDetails[iDet]];
  950. if (detail.subShapeNum >= 0)
  951. detail.objectDetailNum = iDet;
  952. for (int iObj = shape->subShapeFirstObject[iSub];
  953. iObj < (shape->subShapeFirstObject[iSub] + shape->subShapeNumObjects[iSub]);
  954. iObj++)
  955. {
  956. TSShape::Object &object = shape->objects[iObj];
  957. // Insert a NULL mesh for this detail level if required (ie. if the
  958. // object does not already have a mesh with an equal or higher detail)
  959. S32 meshIndex = (iDet < object.numMeshes) ? iDet : object.numMeshes-1;
  960. if (appMeshes[object.startMeshIndex + meshIndex]->detailSize < shape->details[iDet].size)
  961. {
  962. // Add a NULL mesh
  963. appMeshes.insert(object.startMeshIndex + iDet, NULL);
  964. object.numMeshes++;
  965. // Fixup the start index for the other objects
  966. for (int k = iObj+1; k < shape->objects.size(); k++)
  967. shape->objects[k].startMeshIndex++;
  968. }
  969. }
  970. }
  971. }
  972. }
  973. // Install into the TSShape, the shape is expected to be empty.
  974. // Data is not copied, the TSShape is modified to point to memory
  975. // managed by this object. This object is also bound to the TSShape
  976. // object and will be deleted when it's deleted.
  977. void TSShapeLoader::install()
  978. {
  979. // Arrays that are filled in by ts shape init, but need
  980. // to be allocated beforehand.
  981. shape->subShapeFirstTranslucentObject.setSize(shape->subShapeFirstObject.size());
  982. // Construct TS sub-meshes
  983. shape->meshes.setSize(appMeshes.size());
  984. for (U32 m = 0; m < appMeshes.size(); m++)
  985. shape->meshes[m] = appMeshes[m] ? appMeshes[m]->constructTSMesh() : NULL;
  986. // Remove empty meshes and objects
  987. for (S32 iObj = shape->objects.size()-1; iObj >= 0; iObj--)
  988. {
  989. TSShape::Object& obj = shape->objects[iObj];
  990. for (S32 iMesh = obj.numMeshes-1; iMesh >= 0; iMesh--)
  991. {
  992. TSMesh *mesh = shape->meshes[obj.startMeshIndex + iMesh];
  993. if (mesh && !mesh->primitives.size())
  994. {
  995. S32 oldMeshCount = obj.numMeshes;
  996. destructInPlace(mesh);
  997. shape->removeMeshFromObject(iObj, iMesh);
  998. iMesh -= (oldMeshCount - obj.numMeshes - 1); // handle when more than one mesh is removed
  999. }
  1000. }
  1001. if (!obj.numMeshes)
  1002. shape->removeObject(shape->getName(obj.nameIndex));
  1003. }
  1004. // Add a dummy object if needed so the shape loads and renders ok
  1005. if (!shape->details.size())
  1006. {
  1007. shape->addDetail("detail", 2, 0);
  1008. shape->subShapeNumObjects.last() = 1;
  1009. shape->meshes.push_back(NULL);
  1010. shape->objects.increment();
  1011. shape->objects.last().nameIndex = shape->addName("dummy");
  1012. shape->objects.last().nodeIndex = 0;
  1013. shape->objects.last().startMeshIndex = 0;
  1014. shape->objects.last().numMeshes = 1;
  1015. shape->objectStates.increment();
  1016. shape->objectStates.last().frameIndex = 0;
  1017. shape->objectStates.last().matFrameIndex = 0;
  1018. shape->objectStates.last().vis = 1.0f;
  1019. }
  1020. // Update smallest visible detail
  1021. shape->mSmallestVisibleDL = -1;
  1022. shape->mSmallestVisibleSize = 999999;
  1023. for (S32 i = 0; i < shape->details.size(); i++)
  1024. {
  1025. if ((shape->details[i].size >= 0) &&
  1026. (shape->details[i].size < shape->mSmallestVisibleSize))
  1027. {
  1028. shape->mSmallestVisibleDL = i;
  1029. shape->mSmallestVisibleSize = shape->details[i].size;
  1030. }
  1031. }
  1032. computeBounds(shape->bounds);
  1033. if (!shape->bounds.isValidBox())
  1034. shape->bounds = Box3F(1.0f);
  1035. shape->bounds.getCenter(&shape->center);
  1036. shape->radius = (shape->bounds.maxExtents - shape->center).len();
  1037. shape->tubeRadius = shape->radius;
  1038. shape->init();
  1039. }
  1040. void TSShapeLoader::computeBounds(Box3F& bounds)
  1041. {
  1042. // Compute the box that encloses the model geometry
  1043. bounds = Box3F::Invalid;
  1044. // Use bounds node geometry if present
  1045. if ( boundsNode && boundsNode->getNumMesh() )
  1046. {
  1047. for (S32 iMesh = 0; iMesh < boundsNode->getNumMesh(); iMesh++)
  1048. {
  1049. AppMesh* mesh = boundsNode->getMesh( iMesh );
  1050. if ( !mesh )
  1051. continue;
  1052. Box3F meshBounds;
  1053. mesh->computeBounds( meshBounds );
  1054. if ( meshBounds.isValidBox() )
  1055. bounds.intersect( meshBounds );
  1056. }
  1057. }
  1058. else
  1059. {
  1060. // Compute bounds based on all geometry in the model
  1061. for (S32 iMesh = 0; iMesh < appMeshes.size(); iMesh++)
  1062. {
  1063. AppMesh* mesh = appMeshes[iMesh];
  1064. if ( !mesh )
  1065. continue;
  1066. Box3F meshBounds;
  1067. mesh->computeBounds( meshBounds );
  1068. if ( meshBounds.isValidBox() )
  1069. bounds.intersect( meshBounds );
  1070. }
  1071. }
  1072. }
  1073. TSShapeLoader::~TSShapeLoader()
  1074. {
  1075. clearNodeTransformCache();
  1076. // Clear shared AppMaterial list
  1077. for (int iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++)
  1078. delete AppMesh::appMaterials[iMat];
  1079. AppMesh::appMaterials.clear();
  1080. // Delete Subshapes
  1081. delete boundsNode;
  1082. for (int iSub = 0; iSub < subshapes.size(); iSub++)
  1083. delete subshapes[iSub];
  1084. // Delete AppSequences
  1085. for (int iSeq = 0; iSeq < appSequences.size(); iSeq++)
  1086. delete appSequences[iSeq];
  1087. appSequences.clear();
  1088. }
  1089. // Static functions to handle supported formats for shape loader.
  1090. void TSShapeLoader::addFormat(String name, String extension)
  1091. {
  1092. ShapeFormat newFormat;
  1093. newFormat.mName = name;
  1094. newFormat.mExtension = extension;
  1095. smFormats.push_back(newFormat);
  1096. }
  1097. String TSShapeLoader::getFormatExtensions()
  1098. {
  1099. // "*.dsq TAB *.dae TAB
  1100. StringBuilder output;
  1101. for(U32 n = 0; n < smFormats.size(); ++n)
  1102. {
  1103. output.append("*.");
  1104. output.append(smFormats[n].mExtension);
  1105. output.append("\t");
  1106. }
  1107. return output.end();
  1108. }
  1109. String TSShapeLoader::getFormatFilters()
  1110. {
  1111. // "DSQ Files|*.dsq|COLLADA Files|*.dae|"
  1112. StringBuilder output;
  1113. for(U32 n = 0; n < smFormats.size(); ++n)
  1114. {
  1115. output.append(smFormats[n].mName);
  1116. output.append("|*.");
  1117. output.append(smFormats[n].mExtension);
  1118. output.append("|");
  1119. }
  1120. return output.end();
  1121. }
  1122. DefineConsoleFunction( getFormatExtensions, const char*, ( ),,
  1123. "Returns a list of supported shape format extensions separated by tabs."
  1124. "Example output: *.dsq TAB *.dae TAB")
  1125. {
  1126. return Con::getReturnBuffer(TSShapeLoader::getFormatExtensions());
  1127. }
  1128. DefineConsoleFunction( getFormatFilters, const char*, ( ),,
  1129. "Returns a list of supported shape formats in filter form.\n"
  1130. "Example output: DSQ Files|*.dsq|COLLADA Files|*.dae|")
  1131. {
  1132. return Con::getReturnBuffer(TSShapeLoader::getFormatFilters());
  1133. }