tsShapeEdit.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  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/consoleTypes.h"
  24. #include "core/resourceManager.h"
  25. #include "ts/tsShape.h"
  26. #include "ts/tsShapeInstance.h"
  27. #include "ts/tsLastDetail.h"
  28. #include "ts/tsMaterialList.h"
  29. #include "core/stream/fileStream.h"
  30. #include "core/volume.h"
  31. //-----------------------------------------------------------------------------
  32. S32 TSShape::addName(const String& name)
  33. {
  34. // Check for empty names
  35. if (name.isEmpty())
  36. return -1;
  37. // Return the index of the new name (add if it is unique)
  38. S32 index = findName(name);
  39. if (index >= 0)
  40. return index;
  41. names.push_back(StringTable->insert(name));
  42. return names.size()-1;
  43. }
  44. void TSShape::updateSmallestVisibleDL()
  45. {
  46. // Update smallest visible detail
  47. mSmallestVisibleDL = -1;
  48. mSmallestVisibleSize = F32_MAX;
  49. F32 maxSize = 0.0f;
  50. for (S32 i = 0; i < details.size(); i++)
  51. {
  52. maxSize = getMax( maxSize, details[i].size );
  53. if ((details[i].size >= 0) && (details[i].size < mSmallestVisibleSize))
  54. {
  55. mSmallestVisibleDL = i;
  56. mSmallestVisibleSize = details[i].size;
  57. }
  58. }
  59. // Initialize the detail level lod lookup table.
  60. mDetailLevelLookup.setSize( (U32)( maxSize * 2.0f ) + 2 );
  61. for ( U32 l=0; l < mDetailLevelLookup.size(); l++ )
  62. {
  63. F32 pixelSize = (F32)l;
  64. S32 dl = -1;
  65. for ( U32 d=0; d < details.size(); d++ )
  66. {
  67. // Break when we get to hidden detail
  68. // levels like collision shapes.
  69. if ( details[d].size < 0 )
  70. break;
  71. if ( pixelSize > details[d].size )
  72. {
  73. dl = d;
  74. break;
  75. }
  76. if ( d + 1 >= details.size() || details[d+1].size < 0 )
  77. {
  78. // We've run out of details and haven't found anything?
  79. // Let's just grab this one.
  80. dl = d;
  81. break;
  82. }
  83. }
  84. // Calculate the intra detail level.
  85. F32 intraDL = 0;
  86. if ( dl > -1 )
  87. {
  88. F32 curSize = details[dl].size;
  89. F32 nextSize = dl == 0 ? 2.0f * curSize : details[dl - 1].size;
  90. intraDL = mClampF( nextSize - curSize > 0.01f ? (pixelSize - curSize) / (nextSize - curSize) : 1.0f, 0, 1 );
  91. }
  92. mDetailLevelLookup[l].set( dl, intraDL );
  93. }
  94. // Test for using the legacy screen error
  95. // lod method here instead of runtime.
  96. //
  97. // See setDetailFromDistance().
  98. //
  99. mUseDetailFromScreenError = mSmallestVisibleDL >= 0 &&
  100. details.first().maxError >= 0;
  101. }
  102. S32 TSShape::addDetail(const String& dname, S32 size, S32 subShapeNum)
  103. {
  104. S32 nameIndex = addName(avar("%s%d", dname.c_str(), size));
  105. // Check if this detail size has already been added
  106. S32 index;
  107. for (index = 0; index < details.size(); index++)
  108. {
  109. if ((details[index].size == size) &&
  110. (details[index].subShapeNum == subShapeNum) &&
  111. (details[index].nameIndex == nameIndex))
  112. return index;
  113. if (details[index].size < size)
  114. break;
  115. }
  116. // Create a new detail level at the right index, so array
  117. // remains sorted by detail size (from largest to smallest)
  118. details.insert(index);
  119. TSShape::Detail &detail = details[index];
  120. // Clear the detail to ensure no garbage values
  121. // are left in any vars we don't set.
  122. dMemset( &detail, 0, sizeof( Detail ) );
  123. // Setup the detail.
  124. detail.nameIndex = nameIndex;
  125. detail.size = size;
  126. detail.subShapeNum = subShapeNum;
  127. detail.objectDetailNum = 0;
  128. detail.averageError = -1;
  129. detail.maxError = -1;
  130. detail.polyCount = 0;
  131. // Resize alpha vectors
  132. alphaIn.increment();
  133. alphaOut.increment();
  134. // Fixup objectDetailNum in other detail levels
  135. for (S32 i = index+1; i < details.size(); i++)
  136. {
  137. if ((details[i].subShapeNum >= 0) &&
  138. ((subShapeNum == -1) || (details[i].subShapeNum == subShapeNum)))
  139. details[i].objectDetailNum++;
  140. }
  141. // Update smallest visible detail
  142. updateSmallestVisibleDL();
  143. return index;
  144. }
  145. S32 TSShape::addImposter(const String& cachePath, S32 size, S32 numEquatorSteps,
  146. S32 numPolarSteps, S32 dl, S32 dim, bool includePoles, F32 polarAngle)
  147. {
  148. // Check if the desired size is already in use
  149. bool isNewDetail = false;
  150. S32 detIndex = findDetailBySize( size );
  151. if ( detIndex >= 0 )
  152. {
  153. // Size is in use. If the detail is already an imposter, we can just change
  154. // the settings, otherwise quit
  155. if ( details[detIndex].subShapeNum >= 0 )
  156. {
  157. Con::errorf( "TSShape::addImposter: A non-billboard detail already "
  158. "exists at size %d", size );
  159. return -1;
  160. }
  161. }
  162. else
  163. {
  164. // Size is not in use. If an imposter already exists, change its size, otherwise
  165. // create a new detail
  166. for ( detIndex = 0; detIndex < details.size(); ++detIndex )
  167. {
  168. if ( details[detIndex].subShapeNum < 0 )
  169. {
  170. // Change the imposter detail size
  171. setDetailSize( details[detIndex].size, size );
  172. break;
  173. }
  174. }
  175. if ( detIndex == details.size() )
  176. {
  177. isNewDetail = true;
  178. detIndex = addDetail( "bbDetail", size, -1 );
  179. }
  180. }
  181. // Now set the billboard properties.
  182. Detail &detail = details[detIndex];
  183. // In prior to DTS version 26 we would pack the autobillboard
  184. // into this single 32bit value. This was prone to overflows
  185. // of parameters caused random bugs.
  186. //
  187. // Set the old autobillboard properties var to zero.
  188. detail.objectDetailNum = 0;
  189. // We now use the new vars.
  190. detail.bbEquatorSteps = numEquatorSteps;
  191. detail.bbPolarSteps = numPolarSteps;
  192. detail.bbPolarAngle = polarAngle;
  193. detail.bbDetailLevel = dl;
  194. detail.bbDimension = dim;
  195. detail.bbIncludePoles = includePoles;
  196. // Rebuild billboard details or force an update of the modified detail
  197. if ( isNewDetail )
  198. {
  199. // Add NULL meshes for this detail
  200. for ( S32 iObj = 0; iObj < objects.size(); ++iObj )
  201. {
  202. if ( detIndex < objects[iObj].numMeshes )
  203. {
  204. objects[iObj].numMeshes++;
  205. meshes.insert( objects[iObj].startMeshIndex + detIndex, NULL );
  206. for (S32 j = iObj + 1; j < objects.size(); ++j )
  207. objects[j].startMeshIndex++;
  208. }
  209. }
  210. // Could be dedicated server.
  211. if ( GFXDevice::devicePresent() )
  212. setupBillboardDetails( cachePath );
  213. while ( detailCollisionAccelerators.size() < details.size() )
  214. detailCollisionAccelerators.push_back( NULL );
  215. }
  216. else
  217. {
  218. if ( billboardDetails.size() && GFXDevice::devicePresent() )
  219. {
  220. delete billboardDetails[detIndex];
  221. billboardDetails[detIndex] = new TSLastDetail(
  222. this,
  223. cachePath,
  224. detail.bbEquatorSteps,
  225. detail.bbPolarSteps,
  226. detail.bbPolarAngle,
  227. detail.bbIncludePoles,
  228. detail.bbDetailLevel,
  229. detail.bbDimension );
  230. billboardDetails[detIndex]->update( true );
  231. }
  232. }
  233. return detIndex;
  234. }
  235. bool TSShape::removeImposter()
  236. {
  237. // Find the imposter detail level
  238. S32 detIndex;
  239. for ( detIndex = 0; detIndex < details.size(); ++detIndex )
  240. {
  241. if ( details[detIndex].subShapeNum < 0 )
  242. break;
  243. }
  244. if ( detIndex == details.size() )
  245. {
  246. Con::errorf( "TSShape::removeImposter: No imposter detail level found in shape" );
  247. return false;
  248. }
  249. // Remove the detail level
  250. details.erase( detIndex );
  251. if ( detIndex < billboardDetails.size() )
  252. {
  253. // Delete old textures
  254. TSLastDetail* bb = billboardDetails[detIndex];
  255. bb->deleteImposterCacheTextures();
  256. delete billboardDetails[detIndex];
  257. }
  258. billboardDetails.clear();
  259. detailCollisionAccelerators.erase( detIndex );
  260. // Remove the (NULL) meshes from each object
  261. for ( S32 iObj = 0; iObj < objects.size(); ++iObj )
  262. {
  263. if ( detIndex < objects[iObj].numMeshes )
  264. {
  265. objects[iObj].numMeshes--;
  266. meshes.erase( objects[iObj].startMeshIndex + detIndex );
  267. for (S32 j = iObj + 1; j < objects.size(); ++j )
  268. objects[j].startMeshIndex--;
  269. }
  270. }
  271. // Update smallest visible size
  272. updateSmallestVisibleDL();
  273. return true;
  274. }
  275. //-----------------------------------------------------------------------------
  276. /// Get the index of the element in the group with a given name
  277. template<class T> S32 findByName(Vector<T>& group, S32 nameIndex)
  278. {
  279. for (S32 i = 0; i < group.size(); i++)
  280. if (group[i].nameIndex == nameIndex)
  281. return i;
  282. return -1;
  283. }
  284. /// Adjust the nameIndex for elements in the group
  285. template<class T> void adjustForNameRemoval(Vector<T>& group, S32 nameIndex)
  286. {
  287. for (S32 i = 0; i < group.size(); i++)
  288. if (group[i].nameIndex > nameIndex)
  289. group[i].nameIndex--;
  290. }
  291. bool TSShape::removeName(const String& name)
  292. {
  293. // Check if the name is still in use
  294. S32 nameIndex = findName(name);
  295. if ((findByName(nodes, nameIndex) >= 0) ||
  296. (findByName(objects, nameIndex) >= 0) ||
  297. (findByName(sequences, nameIndex) >= 0) ||
  298. (findByName(details, nameIndex) >= 0))
  299. return false;
  300. // Remove the name, then update nameIndex for affected elements
  301. names.erase(nameIndex);
  302. adjustForNameRemoval(nodes, nameIndex);
  303. adjustForNameRemoval(objects, nameIndex);
  304. adjustForNameRemoval(sequences, nameIndex);
  305. adjustForNameRemoval(details, nameIndex);
  306. return true;
  307. }
  308. //-----------------------------------------------------------------------------
  309. template<class T> bool doRename(TSShape* shape, Vector<T>& group, const String& oldName, const String& newName)
  310. {
  311. // Find the element in the group with the oldName
  312. S32 index = findByName(group, shape->findName(oldName));
  313. if (index < 0)
  314. {
  315. Con::errorf("TSShape::rename: Could not find '%s'", oldName.c_str());
  316. return false;
  317. }
  318. // Ignore trivial renames
  319. if (oldName.equal(newName, String::NoCase))
  320. return true;
  321. // Check that this name is not already in use
  322. if (findByName(group, shape->findName(newName)) >= 0)
  323. {
  324. Con::errorf("TSShape::rename: '%s' is already in use", newName.c_str());
  325. return false;
  326. }
  327. // Do the rename (the old name will be removed if it is no longer in use)
  328. group[index].nameIndex = shape->addName(newName);
  329. shape->removeName(oldName);
  330. return true;
  331. }
  332. bool TSShape::renameNode(const String& oldName, const String& newName)
  333. {
  334. return doRename(this, nodes, oldName, newName);
  335. }
  336. bool TSShape::renameObject(const String& oldName, const String& newName)
  337. {
  338. return doRename(this, objects, oldName, newName);
  339. }
  340. bool TSShape::renameDetail(const String& oldName, const String& newName)
  341. {
  342. return doRename(this, details, oldName, newName);
  343. }
  344. bool TSShape::renameSequence(const String& oldName, const String& newName)
  345. {
  346. return doRename(this, sequences, oldName, newName);
  347. }
  348. //-----------------------------------------------------------------------------
  349. bool TSShape::addNode(const String& name, const String& parentName, const Point3F& pos, const QuatF& rot)
  350. {
  351. // Check that adding this node would not exceed the maximum count
  352. if (nodes.size() >= MAX_TS_SET_SIZE)
  353. {
  354. Con::errorf("TSShape::addNode: Cannot add node, shape already has maximum (%d) nodes", MAX_TS_SET_SIZE);
  355. return false;
  356. }
  357. // Check that there is not already a node with this name
  358. if (findNode(name) >= 0)
  359. {
  360. Con::errorf("TSShape::addNode: %s already exists!", name.c_str());
  361. return false;
  362. }
  363. // Find the parent node (OK for name to be empty => node is at root level)
  364. S32 parentIndex = -1;
  365. if (String::compare(parentName, ""))
  366. {
  367. parentIndex = findNode(parentName);
  368. if (parentIndex < 0)
  369. {
  370. Con::errorf("TSShape::addNode: Could not find parent node '%s'", parentName.c_str());
  371. return false;
  372. }
  373. }
  374. // Need to make everything editable since node indexes etc will change
  375. makeEditable();
  376. // Insert node at the end of the subshape
  377. S32 subShapeIndex = (parentIndex >= 0) ? getSubShapeForNode(parentIndex) : 0;
  378. S32 nodeIndex = subShapeNumNodes[subShapeIndex];
  379. // Adjust subshape node indices
  380. subShapeNumNodes[subShapeIndex]++;
  381. for (S32 i = subShapeIndex + 1; i < subShapeFirstNode.size(); i++)
  382. subShapeFirstNode[i]++;
  383. // Update animation sequences
  384. for (S32 iSeq = 0; iSeq < sequences.size(); iSeq++)
  385. {
  386. // Update animation matters arrays (new node is not animated)
  387. TSShape::Sequence& seq = sequences[iSeq];
  388. seq.translationMatters.insert(nodeIndex, false);
  389. seq.rotationMatters.insert(nodeIndex, false);
  390. seq.scaleMatters.insert(nodeIndex, false);
  391. }
  392. // Insert the new node
  393. TSShape::Node node;
  394. node.nameIndex = addName(name);
  395. node.parentIndex = parentIndex;
  396. node.firstChild = -1;
  397. node.firstObject = -1;
  398. node.nextSibling = -1;
  399. nodes.insert(nodeIndex, node);
  400. // Insert node default translation and rotation
  401. Quat16 rot16;
  402. rot16.set(rot);
  403. defaultTranslations.insert(nodeIndex, pos);
  404. defaultRotations.insert(nodeIndex, rot16);
  405. // Fixup node indices
  406. for (S32 i = 0; i < nodes.size(); i++)
  407. {
  408. if (nodes[i].parentIndex >= nodeIndex)
  409. nodes[i].parentIndex++;
  410. }
  411. for (S32 i = 0; i < objects.size(); i++)
  412. {
  413. if (objects[i].nodeIndex >= nodeIndex)
  414. objects[i].nodeIndex++;
  415. }
  416. for (S32 i = 0; i < meshes.size(); i++)
  417. {
  418. if (meshes[i] && (meshes[i]->getMeshType() == TSMesh::SkinMeshType))
  419. {
  420. TSSkinMesh* skin = dynamic_cast<TSSkinMesh*>(meshes[i]);
  421. for (S32 j = 0; j < skin->batchData.nodeIndex.size(); j++)
  422. {
  423. if (skin->batchData.nodeIndex[j] >= nodeIndex)
  424. skin->batchData.nodeIndex[j]++;
  425. }
  426. }
  427. }
  428. initObjects();
  429. return true;
  430. }
  431. /// Erase animation keyframes (translation, rotation etc)
  432. template<class T> S32 eraseStates(Vector<T>& vec, const TSIntegerSet& matters, S32 base, S32 numKeyframes, S32 index=-1)
  433. {
  434. S32 dest, count;
  435. if (index == -1)
  436. {
  437. // Erase for all nodes/objects
  438. dest = base;
  439. count = numKeyframes * matters.count();
  440. }
  441. else
  442. {
  443. // Erase for the indexed node/object only
  444. dest = base + matters.count(index)*numKeyframes;
  445. count = numKeyframes;
  446. }
  447. // Erase the values
  448. if (count)
  449. {
  450. if ((dest + count) < vec.size())
  451. dCopyArray(&vec[dest], &vec[dest + count], vec.size() - (dest + count));
  452. vec.decrement(count);
  453. }
  454. return count;
  455. }
  456. bool TSShape::removeNode(const String& name)
  457. {
  458. // Find the node to be removed
  459. S32 nodeIndex = findNode(name);
  460. if (nodeIndex < 0)
  461. {
  462. Con::errorf("TSShape::removeNode: Could not find node '%s'", name.c_str());
  463. return false;
  464. }
  465. S32 nodeParentIndex = nodes[nodeIndex].parentIndex;
  466. // Warn if there are objects attached to this node
  467. Vector<S32> nodeObjects;
  468. getNodeObjects(nodeIndex, nodeObjects);
  469. if (nodeObjects.size())
  470. {
  471. Con::warnf("TSShape::removeNode: Node '%s' has %d objects attached, these "
  472. "will be reassigned to the node's parent ('%s')", name.c_str(), nodeObjects.size(),
  473. ((nodeParentIndex >= 0) ? getName(nodes[nodeParentIndex].nameIndex).c_str() : "null"));
  474. }
  475. // Need to make everything editable since node indexes etc will change
  476. makeEditable();
  477. // Update animation sequences
  478. for (S32 iSeq = 0; iSeq < sequences.size(); iSeq++)
  479. {
  480. TSShape::Sequence& seq = sequences[iSeq];
  481. // Remove animated node transforms
  482. if (seq.translationMatters.test(nodeIndex))
  483. eraseStates(nodeTranslations, seq.translationMatters, seq.baseTranslation, seq.numKeyframes, nodeIndex);
  484. if (seq.rotationMatters.test(nodeIndex))
  485. eraseStates(nodeRotations, seq.rotationMatters, seq.baseRotation, seq.numKeyframes, nodeIndex);
  486. if (seq.scaleMatters.test(nodeIndex))
  487. {
  488. if (seq.flags & TSShape::ArbitraryScale)
  489. {
  490. eraseStates(nodeArbitraryScaleRots, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  491. eraseStates(nodeArbitraryScaleFactors, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  492. }
  493. else if (seq.flags & TSShape::AlignedScale)
  494. eraseStates(nodeAlignedScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  495. else
  496. eraseStates(nodeUniformScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  497. }
  498. seq.translationMatters.erase(nodeIndex);
  499. seq.rotationMatters.erase(nodeIndex);
  500. seq.scaleMatters.erase(nodeIndex);
  501. }
  502. // Remove the node
  503. nodes.erase(nodeIndex);
  504. defaultTranslations.erase(nodeIndex);
  505. defaultRotations.erase(nodeIndex);
  506. // Adjust subshape node indices
  507. S32 subShapeIndex = getSubShapeForNode(nodeIndex);
  508. subShapeNumNodes[subShapeIndex]--;
  509. for (S32 i = subShapeIndex + 1; i < subShapeFirstNode.size(); i++)
  510. subShapeFirstNode[i]--;
  511. // Fixup node parent indices
  512. for (S32 i = 0; i < nodes.size(); i++)
  513. {
  514. if (nodes[i].parentIndex == nodeIndex)
  515. nodes[i].parentIndex = -1;
  516. else if (nodes[i].parentIndex > nodeIndex)
  517. nodes[i].parentIndex--;
  518. }
  519. if (nodeParentIndex > nodeIndex)
  520. nodeParentIndex--;
  521. // Fixup object node indices, and re-assign attached objects to node's parent
  522. for (S32 i = 0; i < objects.size(); i++)
  523. {
  524. if (objects[i].nodeIndex == nodeIndex)
  525. objects[i].nodeIndex = nodeParentIndex;
  526. if (objects[i].nodeIndex > nodeIndex)
  527. objects[i].nodeIndex--;
  528. }
  529. // Fixup skin weight node indices, and re-assign weights for deleted node to its parent
  530. for (S32 i = 0; i < meshes.size(); i++)
  531. {
  532. if (meshes[i] && (meshes[i]->getMeshType() == TSMesh::SkinMeshType))
  533. {
  534. TSSkinMesh* skin = dynamic_cast<TSSkinMesh*>(meshes[i]);
  535. for (S32 j = 0; j < skin->batchData.nodeIndex.size(); j++)
  536. {
  537. if (skin->batchData.nodeIndex[j] == nodeIndex)
  538. skin->batchData.nodeIndex[j] = nodeParentIndex;
  539. if (skin->batchData.nodeIndex[j] > nodeIndex)
  540. skin->batchData.nodeIndex[j]--;
  541. }
  542. }
  543. }
  544. // Remove the sequence name if it is no longer in use
  545. removeName(name);
  546. initObjects();
  547. return true;
  548. }
  549. //-----------------------------------------------------------------------------
  550. bool TSShape::setNodeTransform(const String& name, const Point3F& pos, const QuatF& rot)
  551. {
  552. // Find the node to be transformed
  553. S32 nodeIndex = findNode(name);
  554. if (nodeIndex < 0)
  555. {
  556. Con::errorf("TSShape::setNodeTransform: Could not find node '%s'", name.c_str());
  557. return false;
  558. }
  559. // Update initial node position and rotation
  560. defaultTranslations[nodeIndex] = pos;
  561. defaultRotations[nodeIndex].set(rot);
  562. return true;
  563. }
  564. //-----------------------------------------------------------------------------
  565. S32 TSShape::addObject(const String& objName, S32 subShapeIndex)
  566. {
  567. S32 objIndex = subShapeNumObjects[subShapeIndex];
  568. // Add object to subshape
  569. subShapeNumObjects[subShapeIndex]++;
  570. for (S32 i = subShapeIndex + 1; i < subShapeFirstObject.size(); i++)
  571. subShapeFirstObject[i]++;
  572. TSShape::Object obj;
  573. obj.nameIndex = addName(objName);
  574. obj.nodeIndex = 0;
  575. obj.numMeshes = 0;
  576. obj.startMeshIndex = (objIndex == 0) ? 0 : objects[objIndex-1].startMeshIndex + objects[objIndex-1].numMeshes;
  577. obj.firstDecal = 0;
  578. obj.nextSibling = 0;
  579. objects.insert(objIndex, obj);
  580. // Add default object state
  581. TSShape::ObjectState state;
  582. state.frameIndex = 0;
  583. state.matFrameIndex = 0;
  584. state.vis = 1.0f;
  585. objectStates.insert(objIndex, state);
  586. // Fixup sequences
  587. for (S32 i = 0; i < sequences.size(); i++)
  588. sequences[i].baseObjectState++;
  589. return objIndex;
  590. }
  591. void TSShape::addMeshToObject(S32 objIndex, S32 meshIndex, TSMesh* mesh)
  592. {
  593. TSShape::Object& obj = objects[objIndex];
  594. // Pad with NULLs if required
  595. S32 oldNumMeshes = obj.numMeshes;
  596. if (mesh)
  597. {
  598. for (S32 i = obj.numMeshes; i < meshIndex; i++)
  599. {
  600. meshes.insert(obj.startMeshIndex + i, NULL);
  601. obj.numMeshes++;
  602. }
  603. }
  604. // Insert the new mesh
  605. meshes.insert(obj.startMeshIndex + meshIndex, mesh);
  606. obj.numMeshes++;
  607. // Skinned meshes are not attached to any node
  608. if (mesh && (mesh->getMeshType() == TSMesh::SkinMeshType))
  609. obj.nodeIndex = -1;
  610. // Fixup mesh indices for other objects
  611. for (S32 i = 0; i < objects.size(); i++)
  612. {
  613. if ((i != objIndex) && (objects[i].startMeshIndex >= obj.startMeshIndex))
  614. objects[i].startMeshIndex += (obj.numMeshes - oldNumMeshes);
  615. }
  616. }
  617. void TSShape::removeMeshFromObject(S32 objIndex, S32 meshIndex)
  618. {
  619. TSShape::Object& obj = objects[objIndex];
  620. // Remove the mesh, but do not destroy it (this must be done by the caller)
  621. meshes[obj.startMeshIndex + meshIndex] = NULL;
  622. // Check if there are any objects remaining that have a valid mesh at this
  623. // detail size
  624. bool removeDetail = true;
  625. for (S32 i = 0; i < objects.size(); i++)
  626. {
  627. if ((meshIndex < objects[i].numMeshes) && meshes[objects[i].startMeshIndex + meshIndex])
  628. {
  629. removeDetail = false;
  630. break;
  631. }
  632. }
  633. // Remove detail level if possible
  634. if (removeDetail)
  635. {
  636. for (S32 i = 0; i < objects.size(); i++)
  637. {
  638. if (meshIndex < objects[i].numMeshes)
  639. {
  640. U32 idxToRemove = objects[i].startMeshIndex + meshIndex;
  641. meshes.erase(idxToRemove);
  642. objects[i].numMeshes--;
  643. // Clear invalid parent
  644. for (U32 k = 0; k < meshes.size(); k++)
  645. {
  646. if (meshes[k] == NULL)
  647. continue;
  648. if (meshes[k]->mParentMesh == idxToRemove)
  649. {
  650. meshes[k]->mParentMesh = -1;
  651. }
  652. else if (meshes[k]->mParentMesh > idxToRemove)
  653. {
  654. meshes[k]->mParentMesh--;
  655. }
  656. }
  657. for (S32 j = 0; j < objects.size(); j++)
  658. {
  659. if (objects[j].startMeshIndex > objects[i].startMeshIndex)
  660. objects[j].startMeshIndex--;
  661. }
  662. }
  663. }
  664. Vector<S32> validDetails;
  665. getSubShapeDetails(getSubShapeForObject(objIndex), validDetails);
  666. for (S32 i = 0; i < validDetails.size(); i++)
  667. {
  668. TSShape::Detail& detail = details[validDetails[i]];
  669. if (detail.objectDetailNum > meshIndex)
  670. detail.objectDetailNum--;
  671. }
  672. details.erase(validDetails[meshIndex]);
  673. }
  674. // Remove trailing NULL meshes from the object
  675. S32 oldNumMeshes = obj.numMeshes;
  676. while (obj.numMeshes && !meshes[obj.startMeshIndex + obj.numMeshes - 1])
  677. {
  678. U32 idxToRemove = obj.startMeshIndex + obj.numMeshes - 1;
  679. meshes.erase(idxToRemove);
  680. // Clear invalid parent
  681. for (U32 k = 0; k < meshes.size(); k++)
  682. {
  683. if (meshes[k] == NULL)
  684. continue;
  685. if (meshes[k]->mParentMesh == idxToRemove)
  686. {
  687. meshes[k]->mParentMesh = -1;
  688. }
  689. else if (meshes[k]->mParentMesh > idxToRemove)
  690. {
  691. meshes[k]->mParentMesh--;
  692. }
  693. }
  694. obj.numMeshes--;
  695. }
  696. // Fixup mesh indices for other objects
  697. for (S32 i = 0; i < objects.size(); i++)
  698. {
  699. if (objects[i].startMeshIndex > obj.startMeshIndex)
  700. objects[i].startMeshIndex -= (oldNumMeshes - obj.numMeshes);
  701. }
  702. }
  703. bool TSShape::setObjectNode(const String& objName, const String& nodeName)
  704. {
  705. // Find the object and node
  706. S32 objIndex = findObject(objName);
  707. if (objIndex < 0)
  708. {
  709. Con::errorf("TSShape::setObjectNode: Could not find object '%s'", objName.c_str());
  710. return false;
  711. }
  712. S32 nodeIndex;
  713. if (nodeName.isEmpty())
  714. nodeIndex = -1;
  715. else
  716. {
  717. nodeIndex = findNode(nodeName);
  718. if (nodeIndex < 0)
  719. {
  720. Con::errorf("TSShape::setObjectNode: Could not find node '%s'", nodeName.c_str());
  721. return false;
  722. }
  723. }
  724. objects[objIndex].nodeIndex = nodeIndex;
  725. return true;
  726. }
  727. bool TSShape::removeObject(const String& name)
  728. {
  729. // Find the object
  730. S32 objIndex = findObject(name);
  731. if (objIndex < 0)
  732. {
  733. Con::errorf("TSShape::removeObject: Could not find object '%s'", name.c_str());
  734. return false;
  735. }
  736. // Need to make everything editable since node indexes etc will change
  737. makeEditable();
  738. // Destroy all meshes in the object
  739. TSShape::Object& obj = objects[objIndex];
  740. while ( obj.numMeshes )
  741. {
  742. destructInPlace(meshes[obj.startMeshIndex + obj.numMeshes - 1]);
  743. removeMeshFromObject(objIndex, obj.numMeshes - 1);
  744. }
  745. // Remove the object from the shape
  746. objects.erase(objIndex);
  747. S32 subShapeIndex = getSubShapeForObject(objIndex);
  748. subShapeNumObjects[subShapeIndex]--;
  749. for (S32 i = subShapeIndex + 1; i < subShapeFirstObject.size(); i++)
  750. subShapeFirstObject[i]--;
  751. // Remove the object from all sequences
  752. for (S32 i = 0; i < sequences.size(); i++)
  753. {
  754. TSShape::Sequence& seq = sequences[i];
  755. TSIntegerSet objMatters(seq.frameMatters);
  756. objMatters.overlap(seq.matFrameMatters);
  757. objMatters.overlap(seq.visMatters);
  758. if (objMatters.test(objIndex))
  759. eraseStates(objectStates, objMatters, seq.baseObjectState, seq.numKeyframes, objIndex);
  760. seq.frameMatters.erase(objIndex);
  761. seq.matFrameMatters.erase(objIndex);
  762. seq.visMatters.erase(objIndex);
  763. }
  764. // Remove the object name if it is no longer in use
  765. removeName(name);
  766. // Update smallest visible detail
  767. updateSmallestVisibleDL();
  768. initObjects();
  769. return true;
  770. }
  771. //-----------------------------------------------------------------------------
  772. // Helper to copy a TSMesh ready for adding to this TSShape (with the right vertex format etc)
  773. TSMesh* TSShape::copyMesh( const TSMesh* srcMesh ) const
  774. {
  775. TSMesh * mesh = 0;
  776. if ( srcMesh && ( srcMesh->getMeshType() == TSMesh::SkinMeshType ) )
  777. {
  778. TSSkinMesh* skin = new TSSkinMesh;
  779. // Copy skin elements
  780. const TSSkinMesh *srcSkin = dynamic_cast<const TSSkinMesh*>(srcMesh);
  781. skin->weight = srcSkin->weight;
  782. skin->vertexIndex = srcSkin->vertexIndex;
  783. skin->boneIndex = srcSkin->boneIndex;
  784. skin->batchData.nodeIndex = srcSkin->batchData.nodeIndex;
  785. skin->batchData.initialTransforms = srcSkin->batchData.initialTransforms;
  786. skin->batchData.initialVerts = srcSkin->batchData.initialVerts;
  787. skin->batchData.initialNorms = srcSkin->batchData.initialNorms;
  788. mesh = static_cast<TSMesh*>(skin);
  789. }
  790. else
  791. {
  792. mesh = new TSMesh;
  793. }
  794. if ( !srcMesh )
  795. return mesh; // return an empty mesh
  796. // Copy mesh elements
  797. mesh->mIndices = srcMesh->mIndices;
  798. mesh->mPrimitives = srcMesh->mPrimitives;
  799. mesh->numFrames = srcMesh->numFrames;
  800. mesh->numMatFrames = srcMesh->numMatFrames;
  801. mesh->vertsPerFrame = srcMesh->vertsPerFrame;
  802. mesh->setFlags(srcMesh->getFlags());
  803. mesh->mNumVerts = srcMesh->mNumVerts;
  804. // Copy vertex data in an *unpacked* form
  805. mesh->copySourceVertexDataFrom(srcMesh);
  806. mesh->createTangents(mesh->mVerts, mesh->mNorms);
  807. mesh->mEncodedNorms.set(NULL, 0);
  808. mesh->computeBounds();
  809. return mesh;
  810. }
  811. bool TSShape::addMesh(TSMesh* mesh, const String& meshName)
  812. {
  813. // Ensure mesh is in editable state
  814. mesh->makeEditable();
  815. // Need to make everything editable since node indexes etc will change
  816. makeEditable();
  817. // Determine the object name and detail size from the mesh name
  818. S32 detailSize = 999;
  819. String objName(String::GetTrailingNumber(meshName, detailSize));
  820. // Find the destination object (create one if it does not exist)
  821. S32 objIndex = findObject(objName);
  822. if (objIndex < 0)
  823. objIndex = addObject(objName, 0);
  824. AssertFatal(objIndex >= 0 && objIndex < objects.size(), "Invalid object index!");
  825. // Determine the subshape this object belongs to
  826. S32 subShapeIndex = getSubShapeForObject(objIndex);
  827. AssertFatal(subShapeIndex < subShapeFirstObject.size(), "Could not find subshape for object!");
  828. // Get the existing detail levels for the subshape
  829. Vector<S32> validDetails;
  830. getSubShapeDetails(subShapeIndex, validDetails);
  831. // Determine where to add the new mesh, and whether this is a new detail
  832. S32 detIndex;
  833. bool newDetail = true;
  834. for (detIndex = 0; detIndex < validDetails.size(); detIndex++)
  835. {
  836. const TSShape::Detail& det = details[validDetails[detIndex]];
  837. if (detailSize >= det.size)
  838. {
  839. newDetail = (det.size != detailSize);
  840. break;
  841. }
  842. }
  843. // Insert the new detail level if required
  844. if (newDetail)
  845. {
  846. // Determine a name for the detail level
  847. const char* detailName;
  848. if (dStrStartsWith(objName, "Col"))
  849. detailName = "collision";
  850. else if (dStrStartsWith(objName, "loscol"))
  851. detailName = "los";
  852. else
  853. detailName = "detail";
  854. S32 index = addDetail(detailName, detailSize, subShapeIndex);
  855. details[index].objectDetailNum = detIndex;
  856. }
  857. // Adding a new mesh or detail level is a bit tricky, since each
  858. // object potentially stores a different number of meshes, including
  859. // NULL meshes for higher detail levels where required.
  860. // For example, the following table shows 3 objects. Note how NULLs
  861. // must be inserted for detail levels higher than the first valid
  862. // mesh, but details after the the last valid mesh are left empty.
  863. //
  864. // Detail | Object1 | Object2 | Object3
  865. // ---------+-----------+-----------+---------
  866. // 128 | 128 | NULL | NULL
  867. // 64 | | NULL | 64
  868. // 32 | | 32 | NULL
  869. // 2 | | | 2
  870. // Add meshes as required for each object
  871. for (S32 i = 0; i < subShapeNumObjects[subShapeIndex]; i++)
  872. {
  873. S32 index = subShapeFirstObject[subShapeIndex] + i;
  874. const TSShape::Object& obj = objects[index];
  875. if (index == objIndex)
  876. {
  877. // The target object: replace the existing mesh (if any) or add a new one
  878. // if required.
  879. if (!newDetail && (detIndex < obj.numMeshes))
  880. {
  881. if ( meshes[obj.startMeshIndex + detIndex] )
  882. destructInPlace(meshes[obj.startMeshIndex + detIndex]);
  883. meshes[obj.startMeshIndex + detIndex] = mesh;
  884. }
  885. else
  886. addMeshToObject(index, detIndex, mesh);
  887. }
  888. else
  889. {
  890. // Other objects: add a NULL mesh only if inserting before a valid mesh
  891. if (newDetail && (detIndex < obj.numMeshes))
  892. addMeshToObject(index, detIndex, NULL);
  893. }
  894. }
  895. initObjects();
  896. return true;
  897. }
  898. bool TSShape::addMesh(TSShape* srcShape, const String& srcMeshName, const String& meshName)
  899. {
  900. // Find the mesh in the source shape
  901. TSMesh* srcMesh = srcShape->findMesh(srcMeshName);
  902. if (!srcMesh)
  903. {
  904. Con::errorf("TSShape::addMesh: Could not find mesh '%s' in shape", srcMeshName.c_str());
  905. return false;
  906. }
  907. // Copy the source mesh
  908. TSMesh *mesh = copyMesh( srcMesh );
  909. if (srcMesh->getMeshType() == TSMesh::SkinMeshType)
  910. {
  911. TSSkinMesh *srcSkin = dynamic_cast<TSSkinMesh*>(srcMesh);
  912. // Check that the source skin is compatible with our skeleton
  913. Vector<S32> nodeMap(srcShape->nodes.size());
  914. for (S32 i = 0; i < srcShape->nodes.size(); i++)
  915. nodeMap.push_back( findNode( srcShape->getName(srcShape->nodes[i].nameIndex) ) );
  916. for (S32 i = 0; i < srcSkin->boneIndex.size(); i++)
  917. {
  918. S32 srcNode = srcSkin->boneIndex[i];
  919. if (nodeMap[srcNode] == -1)
  920. {
  921. const char* name = srcShape->getName(srcShape->nodes[srcNode].nameIndex).c_str();
  922. Con::errorf("TSShape::addMesh: Skin is weighted to node (%s) that "
  923. "does not exist in this shape", name);
  924. return false;
  925. }
  926. }
  927. TSSkinMesh *skin = dynamic_cast<TSSkinMesh*>(mesh);
  928. // Remap node indices
  929. skin->batchData.nodeIndex = srcSkin->batchData.nodeIndex;
  930. for (S32 i = 0; i < skin->batchData.nodeIndex.size(); i++)
  931. skin->batchData.nodeIndex[i] = nodeMap[skin->batchData.nodeIndex[i]];
  932. }
  933. // Add the copied mesh to the shape
  934. if (!addMesh(mesh, meshName))
  935. {
  936. delete mesh;
  937. return false;
  938. }
  939. // Copy materials used by the source mesh (only if from a different shape)
  940. if (srcShape != this)
  941. {
  942. for (S32 i = 0; i < mesh->mPrimitives.size(); i++)
  943. {
  944. if (!(mesh->mPrimitives[i].matIndex & TSDrawPrimitive::NoMaterial))
  945. {
  946. S32 drawType = (mesh->mPrimitives[i].matIndex & (~TSDrawPrimitive::MaterialMask));
  947. S32 srcMatIndex = mesh->mPrimitives[i].matIndex & TSDrawPrimitive::MaterialMask;
  948. const String& matName = srcShape->materialList->getMaterialName(srcMatIndex);
  949. // Add the material if it does not already exist
  950. S32 destMatIndex = materialList->getMaterialNameList().find_next(matName);
  951. if (destMatIndex < 0)
  952. {
  953. destMatIndex = materialList->size();
  954. materialList->push_back(matName, srcShape->materialList->getFlags(srcMatIndex));
  955. }
  956. mesh->mPrimitives[i].matIndex = drawType | destMatIndex;
  957. }
  958. }
  959. }
  960. return true;
  961. }
  962. bool TSShape::setMeshSize(const String& meshName, S32 size)
  963. {
  964. S32 objIndex, meshIndex;
  965. if (!findMeshIndex(meshName, objIndex, meshIndex) ||
  966. !meshes[objects[objIndex].startMeshIndex + meshIndex])
  967. {
  968. Con::errorf("TSShape::setMeshSize: Could not find mesh '%s'", meshName.c_str());
  969. return false;
  970. }
  971. // Need to make everything editable since node indexes etc will change
  972. makeEditable();
  973. // Remove the mesh from the object, but don't destroy it
  974. TSShape::Object& obj = objects[objIndex];
  975. TSMesh* mesh = meshes[obj.startMeshIndex + meshIndex];
  976. removeMeshFromObject(objIndex, meshIndex);
  977. // Add the mesh back at the new position
  978. addMesh(mesh, avar("%s %d", getName(obj.nameIndex).c_str(), size));
  979. // Update smallest visible detail
  980. updateSmallestVisibleDL();
  981. initObjects();
  982. return true;
  983. }
  984. bool TSShape::removeMesh(const String& meshName)
  985. {
  986. S32 objIndex, meshIndex;
  987. if (!findMeshIndex(meshName, objIndex, meshIndex) ||
  988. !meshes[objects[objIndex].startMeshIndex + meshIndex])
  989. {
  990. Con::errorf("TSShape::removeMesh: Could not find mesh '%s'", meshName.c_str());
  991. return false;
  992. }
  993. // Need to make everything editable since node indexes etc will change
  994. makeEditable();
  995. // Destroy and remove the mesh
  996. TSShape::Object& obj = objects[objIndex];
  997. destructInPlace(meshes[obj.startMeshIndex + meshIndex]);
  998. removeMeshFromObject(objIndex, meshIndex);
  999. // Remove the object if there are no meshes left
  1000. if (!obj.numMeshes)
  1001. removeObject(getName(obj.nameIndex));
  1002. // Update smallest visible detail
  1003. updateSmallestVisibleDL();
  1004. initObjects();
  1005. return true;
  1006. }
  1007. //-----------------------------------------------------------------------------
  1008. // Helper function for dealing with some of the Vectors used in a TSShape. 'meshes'
  1009. // for example contains a TSMesh* per-object, per-detail-level, with NULLs for
  1010. // undefined details for each object. Trailing NULLs are not added to the Vector,
  1011. // so you end up with a different number of pointers for each object, depending
  1012. // on which detail levels it defines. This makes it tricky to move meshes around
  1013. // since you have to know how many elements belong to each object.
  1014. // To simplify things, this function pads the Vector up to a certain length (so
  1015. // all objects can appear to have the same number of meshes), the moves a single
  1016. // element to a new index, then trims trailing NULLs again.
  1017. template<class T>
  1018. static void _PadMoveAndTrim(Vector<T*>& vec, S32 offset, S32 count,
  1019. S32 padLength, S32 oldIndex, S32 newIndex)
  1020. {
  1021. // Pad the array with NULLs
  1022. for ( S32 i = count; i < padLength; ++i )
  1023. vec.insert( offset + count, NULL );
  1024. // Move the element from the old to the new index
  1025. T* tmp = vec[offset + oldIndex];
  1026. vec.erase( offset + oldIndex );
  1027. vec.insert( offset + newIndex, tmp );
  1028. // Trim trailing NULLs from the vector
  1029. for ( S32 i = padLength - 1; i >= 0; --i )
  1030. {
  1031. if ( vec[offset + i] )
  1032. break;
  1033. else
  1034. vec.erase( offset + i );
  1035. }
  1036. }
  1037. S32 TSShape::setDetailSize(S32 oldSize, S32 newSize)
  1038. {
  1039. S32 oldIndex = findDetailBySize( oldSize );
  1040. if ( oldIndex < 0 )
  1041. {
  1042. Con::errorf( "TSShape::setDetailSize: Cannot find detail with size %d", oldSize );
  1043. return -1;
  1044. }
  1045. // Remove this detail from the list
  1046. TSShape::Detail tmpDetail = details[oldIndex];
  1047. tmpDetail.size = newSize;
  1048. details.erase(oldIndex);
  1049. // Determine the new position for the detail (details are sorted by size)
  1050. S32 newIndex = 0;
  1051. for ( newIndex = 0; newIndex < details.size(); ++newIndex )
  1052. {
  1053. if ( newSize > details[newIndex].size )
  1054. break;
  1055. }
  1056. // Add the detail at its new position
  1057. details.insert( newIndex, tmpDetail );
  1058. // Rename the detail so its trailing size value is correct
  1059. {
  1060. S32 tmp;
  1061. String oldName( getName( tmpDetail.nameIndex ) );
  1062. String newName( String::GetTrailingNumber( oldName, tmp ) );
  1063. newName += String::ToString( "%d", newSize );
  1064. renameDetail(oldName, newName);
  1065. }
  1066. if ( newIndex != oldIndex )
  1067. {
  1068. // Fixup details
  1069. for ( S32 iDet = 0; iDet < details.size(); iDet++ )
  1070. {
  1071. if ( details[iDet].subShapeNum < 0 )
  1072. {
  1073. if ( details[iDet].bbDetailLevel == oldIndex )
  1074. details[iDet].bbDetailLevel = newIndex;
  1075. }
  1076. else
  1077. {
  1078. details[iDet].objectDetailNum = iDet;
  1079. }
  1080. }
  1081. // Fixup Billboard details
  1082. _PadMoveAndTrim( billboardDetails, 0, billboardDetails.size(),
  1083. details.size(), oldIndex, newIndex );
  1084. // Now move the mesh for each object in the subshape (adding and removing
  1085. // NULLs as appropriate)
  1086. for ( S32 iObj = 0; iObj < objects.size(); ++iObj )
  1087. {
  1088. TSShape::Object& obj = objects[iObj];
  1089. S32 oldMeshCount = meshes.size();
  1090. _PadMoveAndTrim( meshes, obj.startMeshIndex, obj.numMeshes,
  1091. details.size(), oldIndex, newIndex );
  1092. obj.numMeshes += ( meshes.size() - oldMeshCount );
  1093. // Fixup startMeshIndex for remaining objects
  1094. for ( S32 j = iObj + 1; j < objects.size(); ++j )
  1095. objects[j].startMeshIndex += ( meshes.size() - oldMeshCount );
  1096. }
  1097. }
  1098. // Update smallest visible detail
  1099. updateSmallestVisibleDL();
  1100. // Nothing major, just reint object lists
  1101. initObjects();
  1102. return newIndex;
  1103. }
  1104. bool TSShape::removeDetail( S32 size )
  1105. {
  1106. S32 dl = findDetailBySize( size );
  1107. if ( ( dl < 0 ) || ( dl >= details.size() ) )
  1108. {
  1109. Con::errorf( "TSShape::removeDetail: Invalid detail index (%d)", dl );
  1110. return false;
  1111. }
  1112. // Need to make everything editable since node indexes etc will change
  1113. makeEditable();
  1114. // Destroy and remove each mesh in the detail level
  1115. for ( S32 objIndex = objects.size()-1; objIndex >= 0; objIndex-- )
  1116. {
  1117. TSShape::Object& obj = objects[objIndex];
  1118. if ( dl < obj.numMeshes )
  1119. {
  1120. if ( meshes[obj.startMeshIndex + dl] )
  1121. destructInPlace( meshes[obj.startMeshIndex + dl] );
  1122. removeMeshFromObject(objIndex, dl);
  1123. // Remove the object if there are no meshes left
  1124. if (!obj.numMeshes)
  1125. removeObject( getName( obj.nameIndex ) );
  1126. }
  1127. }
  1128. // Destroy billboard detail level
  1129. if ( dl < billboardDetails.size() )
  1130. {
  1131. if ( billboardDetails[dl] )
  1132. {
  1133. // Delete old textures
  1134. billboardDetails[dl]->deleteImposterCacheTextures();
  1135. delete billboardDetails[dl];
  1136. }
  1137. billboardDetails.erase( dl );
  1138. }
  1139. // Update smallest visible detail
  1140. updateSmallestVisibleDL();
  1141. initObjects();
  1142. return true;
  1143. }
  1144. //-----------------------------------------------------------------------------
  1145. bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq,
  1146. const String& name, S32 startFrame, S32 endFrame,
  1147. bool padRotKeys, bool padTransKeys)
  1148. {
  1149. String oldName(fromSeq);
  1150. if (path.getExtension().equal("dsq", String::NoCase))
  1151. {
  1152. S32 oldSeqCount = sequences.size();
  1153. // DSQ source file
  1154. char filenameBuf[1024];
  1155. Con::expandScriptFilename(filenameBuf, sizeof(filenameBuf), path.getFullPath().c_str());
  1156. FileStream *f;
  1157. if((f = FileStream::createAndOpen( filenameBuf, Torque::FS::File::Read )) == NULL)
  1158. {
  1159. Con::errorf("TSShape::addSequence: Could not load DSQ file '%s'", filenameBuf);
  1160. return false;
  1161. }
  1162. if (!importSequences(f, filenameBuf) || (f->getStatus() != Stream::Ok))
  1163. {
  1164. delete f;
  1165. Con::errorf("TSShape::addSequence: Load sequence file '%s' failed", filenameBuf);
  1166. return false;
  1167. }
  1168. delete f;
  1169. // Rename the new sequence if required (avoid rename if name is not
  1170. // unique (this will be fixed up later, and we don't need 2 errors about it!)
  1171. if (oldName.isEmpty())
  1172. oldName = getName(sequences.last().nameIndex);
  1173. if (!oldName.equal(name))
  1174. {
  1175. if (findSequence(name) == -1)
  1176. {
  1177. // Use a dummy intermediate name since we might be renaming from an
  1178. // existing name (and we want to rename the right sequence!)
  1179. sequences.last().nameIndex = addName("__dummy__");
  1180. renameSequence("__dummy__", name);
  1181. }
  1182. }
  1183. // Check that sequences have unique names
  1184. bool lastSequenceRejected = false;
  1185. for (S32 i = sequences.size()-1; i >= oldSeqCount; i--)
  1186. {
  1187. S32 nameIndex = (i == sequences.size()-1) ? findName(name) : sequences[i].nameIndex;
  1188. S32 seqIndex = findSequence(nameIndex);
  1189. if ((seqIndex != -1) && (seqIndex != i))
  1190. {
  1191. Con::errorf("TSShape::addSequence: Failed to add sequence '%s' "
  1192. "(name already exists)", getName(nameIndex).c_str());
  1193. sequences[i].nameIndex = addName("__dummy__");
  1194. removeSequence("__dummy__");
  1195. if (i == sequences.size())
  1196. lastSequenceRejected = true;
  1197. }
  1198. }
  1199. // @todo:Need to remove keyframes if start!=0 and end!=-1
  1200. TSShape::Sequence& seq = sequences.last();
  1201. // Store information about how this sequence was created
  1202. seq.sourceData.from = String::ToString("%s\t%s", filenameBuf, name.c_str());
  1203. seq.sourceData.total = seq.numKeyframes;
  1204. seq.sourceData.start = ((startFrame < 0) || (startFrame >= seq.numKeyframes)) ? 0 : startFrame;
  1205. seq.sourceData.end = ((endFrame < 0) || (endFrame >= seq.numKeyframes)) ? seq.numKeyframes-1 : endFrame;
  1206. return (sequences.size() != oldSeqCount);
  1207. }
  1208. /* Check that sequence to be added does not already exist */
  1209. if (findSequence(name) != -1)
  1210. {
  1211. Con::errorf("TSShape::addSequence: Cannot add sequence '%s' (name already exists)", name.c_str());
  1212. return false;
  1213. }
  1214. Resource<TSShape> hSrcShape;
  1215. TSShape* srcShape = this; // Assume we are copying an existing sequence
  1216. if (path.getExtension().equal("dts", String::NoCase) ||
  1217. path.getExtension().equal("dae", String::NoCase))
  1218. {
  1219. // DTS or DAE source file
  1220. char filenameBuf[1024];
  1221. Con::expandScriptFilename(filenameBuf, sizeof(filenameBuf), path.getFullPath().c_str());
  1222. hSrcShape = ResourceManager::get().load(filenameBuf);
  1223. if (!bool(hSrcShape))
  1224. {
  1225. Con::errorf("TSShape::addSequence: Could not load source shape '%s'", path.getFullPath().c_str());
  1226. return false;
  1227. }
  1228. srcShape = const_cast<TSShape*>((const TSShape*)hSrcShape);
  1229. if (!srcShape->sequences.size())
  1230. {
  1231. Con::errorf("TSShape::addSequence: Source shape '%s' does not contain any sequences", path.getFullPath().c_str());
  1232. return false;
  1233. }
  1234. // If no sequence name is specified, just use the first one
  1235. if (oldName.isEmpty())
  1236. oldName = srcShape->getName(srcShape->sequences[0].nameIndex);
  1237. }
  1238. else
  1239. {
  1240. // Source is an existing sequence
  1241. oldName = path.getFullPath();
  1242. }
  1243. // Find the sequence
  1244. S32 seqIndex = srcShape->findSequence(oldName);
  1245. if (seqIndex < 0)
  1246. {
  1247. Con::errorf("TSShape::addSequence (%s): Could not find sequence named '%s'", path.getFullPath().c_str(), oldName.c_str());
  1248. return false;
  1249. }
  1250. // Check keyframe range
  1251. const TSShape::Sequence* srcSeq = &srcShape->sequences[seqIndex];
  1252. if ((startFrame < 0) || (startFrame >= srcSeq->numKeyframes))
  1253. {
  1254. Con::warnf("TSShape::addSequence (%s): Start keyframe (%d) out of range (0-%d) for sequence '%s'",
  1255. path.getFullPath().c_str(), startFrame, srcSeq->numKeyframes-1, oldName.c_str());
  1256. startFrame = 0;
  1257. }
  1258. if (endFrame < 0)
  1259. endFrame = srcSeq->numKeyframes - 1;
  1260. else if (endFrame >= srcSeq->numKeyframes)
  1261. {
  1262. Con::warnf("TSShape::addSequence (%s): End keyframe (%d) out of range (0-%d) for sequence '%s'",
  1263. path.getFullPath().c_str(), endFrame, srcSeq->numKeyframes-1, oldName.c_str());
  1264. endFrame = srcSeq->numKeyframes - 1;
  1265. }
  1266. // Create array to map source nodes to our nodes
  1267. Vector<S32> nodeMap(srcShape->nodes.size());
  1268. for (S32 i = 0; i < srcShape->nodes.size(); i++)
  1269. nodeMap.push_back(findNode(srcShape->getName(srcShape->nodes[i].nameIndex)));
  1270. // Create array to map source objects to our objects
  1271. Vector<S32> objectMap(srcShape->objects.size());
  1272. for (S32 i = 0; i < srcShape->objects.size(); i++)
  1273. objectMap.push_back(findObject(srcShape->getName(srcShape->objects[i].nameIndex)));
  1274. // Copy the source sequence (need to do it this ugly way instead of just
  1275. // using push_back since srcSeq pointer may change if copying a sequence
  1276. // from inside the shape itself
  1277. sequences.increment();
  1278. TSShape::Sequence& seq = sequences.last();
  1279. srcSeq = &srcShape->sequences[seqIndex]; // update pointer as it may have changed!
  1280. seq = *srcSeq;
  1281. seq.nameIndex = addName(name);
  1282. seq.numKeyframes = endFrame - startFrame + 1;
  1283. if (seq.duration > 0)
  1284. seq.duration *= ((F32)seq.numKeyframes / srcSeq->numKeyframes);
  1285. // Add object states
  1286. // Note: only visibility animation is supported
  1287. seq.frameMatters.clearAll();
  1288. seq.matFrameMatters.clearAll();
  1289. seq.visMatters.clearAll();
  1290. for (S32 i = 0; i < objectMap.size(); i++)
  1291. {
  1292. if (objectMap[i] < 0)
  1293. continue;
  1294. if (srcSeq->visMatters.test(i))
  1295. {
  1296. // Check if visibility is animated within the frames to be copied
  1297. const F32 defaultVis = srcShape->objectStates[i].vis;
  1298. S32 objNum = srcSeq->visMatters.count(i);
  1299. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1300. {
  1301. if (srcShape->getObjectState(*srcSeq, iFrame, objNum).vis != defaultVis)
  1302. {
  1303. seq.visMatters.set(objectMap[i]);
  1304. break;
  1305. }
  1306. }
  1307. }
  1308. }
  1309. TSIntegerSet srcObjectStateSet(srcSeq->frameMatters);
  1310. srcObjectStateSet.overlap(srcSeq->matFrameMatters);
  1311. srcObjectStateSet.overlap(srcSeq->visMatters);
  1312. TSIntegerSet objectStateSet(seq.frameMatters);
  1313. objectStateSet.overlap(seq.matFrameMatters);
  1314. objectStateSet.overlap(seq.visMatters);
  1315. seq.baseObjectState = objectStates.size();
  1316. objectStates.increment(objectStateSet.count()*seq.numKeyframes);
  1317. for (S32 i = 0; i < objectMap.size(); i++)
  1318. {
  1319. if (objectMap[i] < 0)
  1320. continue;
  1321. // Note: only visibility animation is supported
  1322. if (objectStateSet.test(objectMap[i]))
  1323. {
  1324. S32 src = srcSeq->baseObjectState + srcSeq->numKeyframes * srcObjectStateSet.count(i) + startFrame;
  1325. S32 dest = seq.baseObjectState + seq.numKeyframes * objectStateSet.count(objectMap[i]);
  1326. dCopyArray(&objectStates[dest], &srcShape->objectStates[src], seq.numKeyframes);
  1327. }
  1328. }
  1329. // Add ground frames
  1330. F32 ratio = (F32)seq.numKeyframes / srcSeq->numKeyframes;
  1331. S32 groundBase = srcSeq->firstGroundFrame + startFrame*ratio;
  1332. seq.numGroundFrames *= ratio;
  1333. seq.firstGroundFrame = groundTranslations.size();
  1334. groundTranslations.reserve(mMin(groundTranslations.size() + seq.numGroundFrames, srcShape->groundTranslations.size()));
  1335. groundRotations.reserve(mMin(groundRotations.size() + seq.numGroundFrames, srcShape->groundRotations.size()));
  1336. for (S32 i = 0; i < seq.numGroundFrames; i++)
  1337. {
  1338. S32 offset = groundBase + i;
  1339. if (offset >= srcShape->groundTranslations.size())
  1340. {
  1341. Con::errorf("%s groundTranslations out of bounds! [%i/%i] ", path.getFullPath().c_str(), groundBase + i, srcShape->groundTranslations.size());
  1342. offset = srcShape->groundTranslations.size() - 1;
  1343. }
  1344. const Point3F pointValueToCopy = srcShape->groundTranslations[offset];
  1345. groundTranslations.push_back(pointValueToCopy);
  1346. S32 offset2 = groundBase + i;
  1347. if (offset2 >= srcShape->groundRotations.size())
  1348. {
  1349. Con::errorf("%s groundRotations out of bounds! [%i/%i] ", path.getFullPath().c_str(), groundBase + i, srcShape->groundRotations.size());
  1350. offset2 = srcShape->groundRotations.size() - 1;
  1351. }
  1352. const Quat16 quatValueToCopy = srcShape->groundRotations[offset2];
  1353. groundRotations.push_back(quatValueToCopy);
  1354. }
  1355. // Add triggers
  1356. seq.numTriggers = 0;
  1357. seq.firstTrigger = triggers.size();
  1358. F32 seqStartPos = (F32)startFrame / seq.numKeyframes;
  1359. F32 seqEndPos = (F32)endFrame / seq.numKeyframes;
  1360. for (S32 i = 0; i < srcSeq->numTriggers; i++)
  1361. {
  1362. const TSShape::Trigger& srcTrig = srcShape->triggers[srcSeq->firstTrigger + i];
  1363. if ((srcTrig.pos >= seqStartPos) && (srcTrig.pos <= seqEndPos))
  1364. {
  1365. triggers.push_back(srcTrig);
  1366. triggers.last().pos -= seqStartPos;
  1367. seq.numTriggers++;
  1368. }
  1369. }
  1370. // Fixup node matters arrays
  1371. seq.translationMatters.clearAll();
  1372. seq.rotationMatters.clearAll();
  1373. seq.scaleMatters.clearAll();
  1374. for (S32 i = 0; i < nodeMap.size(); i++)
  1375. {
  1376. if (nodeMap[i] < 0)
  1377. continue;
  1378. if (srcSeq->translationMatters.test(i))
  1379. {
  1380. // Check if node position is animated within the frames to be copied
  1381. const Point3F& defaultTrans = srcShape->defaultTranslations[i];
  1382. S32 tranNum = srcSeq->translationMatters.count(i);
  1383. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1384. {
  1385. if (srcShape->getTranslation(*srcSeq, iFrame, tranNum) != defaultTrans)
  1386. {
  1387. seq.translationMatters.set(nodeMap[i]);
  1388. break;
  1389. }
  1390. }
  1391. }
  1392. if (srcSeq->rotationMatters.test(i))
  1393. {
  1394. // Check if node rotation is animated within the frames to be copied
  1395. const QuatF defaultRot = srcShape->defaultRotations[i].getQuatF();
  1396. S32 rotNum = srcSeq->rotationMatters.count(i);
  1397. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1398. {
  1399. QuatF temp;
  1400. if (srcShape->getRotation(*srcSeq, iFrame, rotNum, &temp) != defaultRot)
  1401. {
  1402. seq.rotationMatters.set(nodeMap[i]);
  1403. break;
  1404. }
  1405. }
  1406. }
  1407. if (srcSeq->scaleMatters.test(i))
  1408. {
  1409. S32 scaleNum = srcSeq->scaleMatters.count(i);
  1410. // Check if node scale is animated within the frames to be copied
  1411. if (srcSeq->animatesArbitraryScale())
  1412. {
  1413. TSScale defaultScale;
  1414. defaultScale.identity();
  1415. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1416. {
  1417. TSScale temp;
  1418. if (!(srcShape->getArbitraryScale(*srcSeq, iFrame, scaleNum, &temp) == defaultScale))
  1419. {
  1420. seq.scaleMatters.set(nodeMap[i]);
  1421. break;
  1422. }
  1423. }
  1424. }
  1425. else if (srcSeq->animatesAlignedScale())
  1426. {
  1427. const Point3F defaultScale(Point3F::One);
  1428. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1429. {
  1430. if (srcShape->getAlignedScale(*srcSeq, iFrame, scaleNum) != defaultScale)
  1431. {
  1432. seq.scaleMatters.set(nodeMap[i]);
  1433. break;
  1434. }
  1435. }
  1436. }
  1437. else if (srcSeq->animatesUniformScale())
  1438. {
  1439. const F32 defaultScale = 1.0f;
  1440. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1441. {
  1442. if (srcShape->getUniformScale(*srcSeq, iFrame, scaleNum) != defaultScale)
  1443. {
  1444. seq.scaleMatters.set(nodeMap[i]);
  1445. break;
  1446. }
  1447. }
  1448. }
  1449. }
  1450. }
  1451. // Resize the node transform arrays
  1452. seq.baseTranslation = nodeTranslations.size();
  1453. nodeTranslations.increment(seq.translationMatters.count()*seq.numKeyframes);
  1454. seq.baseRotation = nodeRotations.size();
  1455. nodeRotations.increment(seq.rotationMatters.count()*seq.numKeyframes);
  1456. if (seq.flags & TSShape::ArbitraryScale)
  1457. {
  1458. S32 scaleCount = seq.scaleMatters.count();
  1459. seq.baseScale = nodeArbitraryScaleRots.size();
  1460. nodeArbitraryScaleRots.increment(scaleCount*seq.numKeyframes);
  1461. nodeArbitraryScaleFactors.increment(scaleCount*seq.numKeyframes);
  1462. }
  1463. else if (seq.flags & TSShape::AlignedScale)
  1464. {
  1465. seq.baseScale = nodeAlignedScales.size();
  1466. nodeAlignedScales.increment(seq.scaleMatters.count()*seq.numKeyframes);
  1467. }
  1468. else
  1469. {
  1470. seq.baseScale = nodeUniformScales.size();
  1471. nodeUniformScales.increment(seq.scaleMatters.count()*seq.numKeyframes);
  1472. }
  1473. // Add node transforms (remap from source node indices to our node indices). As
  1474. // well as copying animated node translations and rotations, also handle when the
  1475. // default translation and rotation are different between the source and
  1476. // destination shapes.
  1477. for (S32 i = 0; i < nodeMap.size(); i++)
  1478. {
  1479. if (nodeMap[i] < 0)
  1480. continue;
  1481. if (seq.translationMatters.test(nodeMap[i]))
  1482. {
  1483. S32 src = srcSeq->baseTranslation + srcSeq->numKeyframes * srcSeq->translationMatters.count(i) + startFrame;
  1484. S32 dest = seq.baseTranslation + seq.numKeyframes * seq.translationMatters.count(nodeMap[i]);
  1485. dCopyArray(&nodeTranslations[dest], &srcShape->nodeTranslations[src], seq.numKeyframes);
  1486. }
  1487. else if (padTransKeys && (defaultTranslations[nodeMap[i]] != srcShape->defaultTranslations[i]))
  1488. {
  1489. seq.translationMatters.set(nodeMap[i]);
  1490. S32 dest = seq.baseTranslation + seq.numKeyframes * seq.translationMatters.count(nodeMap[i]);
  1491. for (S32 j = 0; j < seq.numKeyframes; j++)
  1492. nodeTranslations.insert(dest, srcShape->defaultTranslations[i]);
  1493. }
  1494. if (seq.rotationMatters.test(nodeMap[i]))
  1495. {
  1496. S32 src = srcSeq->baseRotation + srcSeq->numKeyframes * srcSeq->rotationMatters.count(i) + startFrame;
  1497. S32 dest = seq.baseRotation + seq.numKeyframes * seq.rotationMatters.count(nodeMap[i]);
  1498. dCopyArray(&nodeRotations[dest], &srcShape->nodeRotations[src], seq.numKeyframes);
  1499. }
  1500. else if (padRotKeys && (defaultRotations[nodeMap[i]] != srcShape->defaultRotations[i]))
  1501. {
  1502. seq.rotationMatters.set(nodeMap[i]);
  1503. S32 dest = seq.baseRotation + seq.numKeyframes * seq.rotationMatters.count(nodeMap[i]);
  1504. for (S32 j = 0; j < seq.numKeyframes; j++)
  1505. nodeRotations.insert(dest, srcShape->defaultRotations[i]);
  1506. }
  1507. if (seq.scaleMatters.test(nodeMap[i]))
  1508. {
  1509. S32 src = srcSeq->baseScale + srcSeq->numKeyframes * srcSeq->scaleMatters.count(i)+ startFrame;
  1510. S32 dest = seq.baseScale + seq.numKeyframes * seq.scaleMatters.count(nodeMap[i]);
  1511. if (seq.flags & TSShape::ArbitraryScale)
  1512. {
  1513. dCopyArray(&nodeArbitraryScaleRots[dest], &srcShape->nodeArbitraryScaleRots[src], seq.numKeyframes);
  1514. dCopyArray(&nodeArbitraryScaleFactors[dest], &srcShape->nodeArbitraryScaleFactors[src], seq.numKeyframes);
  1515. }
  1516. else if (seq.flags & TSShape::AlignedScale)
  1517. dCopyArray(&nodeAlignedScales[dest], &srcShape->nodeAlignedScales[src], seq.numKeyframes);
  1518. else
  1519. dCopyArray(&nodeUniformScales[dest], &srcShape->nodeUniformScales[src], seq.numKeyframes);
  1520. }
  1521. }
  1522. // Set shape flags (only the most significant scale type)
  1523. U32 curVal = mFlags & AnyScale;
  1524. mFlags &= ~(AnyScale);
  1525. mFlags |= getMax(curVal, seq.flags & AnyScale); // take the larger value (can only convert upwards)
  1526. // Set sequence flags
  1527. seq.dirtyFlags = 0;
  1528. if (seq.rotationMatters.testAll() || seq.translationMatters.testAll() || seq.scaleMatters.testAll())
  1529. seq.dirtyFlags |= TSShapeInstance::TransformDirty;
  1530. if (seq.visMatters.testAll())
  1531. seq.dirtyFlags |= TSShapeInstance::VisDirty;
  1532. if (seq.frameMatters.testAll())
  1533. seq.dirtyFlags |= TSShapeInstance::FrameDirty;
  1534. if (seq.matFrameMatters.testAll())
  1535. seq.dirtyFlags |= TSShapeInstance::MatFrameDirty;
  1536. // Store information about how this sequence was created
  1537. seq.sourceData.from = String::ToString("%s\t%s", path.getFullPath().c_str(), oldName.c_str());
  1538. seq.sourceData.total = srcSeq->numKeyframes;
  1539. seq.sourceData.start = startFrame;
  1540. seq.sourceData.end = endFrame;
  1541. return true;
  1542. }
  1543. bool TSShape::removeSequence(const String& name)
  1544. {
  1545. // Find the sequence to be removed
  1546. S32 seqIndex = findSequence(name);
  1547. if (seqIndex < 0)
  1548. {
  1549. Con::errorf("TSShape::removeSequence: Could not find sequence '%s'", name.c_str());
  1550. return false;
  1551. }
  1552. TSShape::Sequence& seq = sequences[seqIndex];
  1553. // Remove the node transforms for this sequence
  1554. S32 transCount = eraseStates(nodeTranslations, seq.translationMatters, seq.baseTranslation, seq.numKeyframes);
  1555. S32 rotCount = eraseStates(nodeRotations, seq.rotationMatters, seq.baseRotation, seq.numKeyframes);
  1556. S32 scaleCount = 0;
  1557. if (seq.flags & TSShape::ArbitraryScale)
  1558. {
  1559. scaleCount = eraseStates(nodeArbitraryScaleRots, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1560. eraseStates(nodeArbitraryScaleFactors, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1561. }
  1562. else if (seq.flags & TSShape::AlignedScale)
  1563. scaleCount = eraseStates(nodeAlignedScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1564. else
  1565. scaleCount = eraseStates(nodeUniformScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1566. // Remove the object states for this sequence
  1567. TSIntegerSet objMatters(seq.frameMatters);
  1568. objMatters.overlap(seq.matFrameMatters);
  1569. objMatters.overlap(seq.visMatters);
  1570. S32 objCount = eraseStates(objectStates, objMatters, seq.baseObjectState, seq.numKeyframes);
  1571. // Remove groundframes and triggers
  1572. TSIntegerSet dummy;
  1573. eraseStates(groundTranslations, dummy, seq.firstGroundFrame, seq.numGroundFrames, 0);
  1574. eraseStates(groundRotations, dummy, seq.firstGroundFrame, seq.numGroundFrames, 0);
  1575. eraseStates(triggers, dummy, seq.firstTrigger, seq.numTriggers, 0);
  1576. // Fixup the base indices of the other sequences
  1577. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1578. {
  1579. sequences[i].baseTranslation -= transCount;
  1580. sequences[i].baseRotation -= rotCount;
  1581. sequences[i].baseScale -= scaleCount;
  1582. sequences[i].baseObjectState -= objCount;
  1583. sequences[i].firstGroundFrame -= seq.numGroundFrames;
  1584. sequences[i].firstTrigger -= seq.numTriggers;
  1585. }
  1586. // Remove the sequence itself
  1587. sequences.erase(seqIndex);
  1588. // Remove the sequence name if it is no longer in use
  1589. removeName(name);
  1590. return true;
  1591. }
  1592. //-----------------------------------------------------------------------------
  1593. bool TSShape::addTrigger(const String& seqName, S32 keyframe, S32 state)
  1594. {
  1595. // Find the sequence
  1596. S32 seqIndex = findSequence(seqName);
  1597. if (seqIndex < 0)
  1598. {
  1599. Con::errorf("TSShape::addTrigger: Could not find sequence '%s'", seqName.c_str());
  1600. return false;
  1601. }
  1602. TSShape::Sequence& seq = sequences[seqIndex];
  1603. if (keyframe >= seq.numKeyframes)
  1604. {
  1605. Con::errorf("TSShape::addTrigger: Keyframe out of range (0-%d for sequence '%s')",
  1606. seq.numKeyframes-1, seqName.c_str());
  1607. return false;
  1608. }
  1609. // Encode the trigger state
  1610. if (state < 0)
  1611. state = 1 << (-state-1);
  1612. else if (state > 0)
  1613. state = (1 << (state-1)) | TSShape::Trigger::StateOn;
  1614. // Fixup seq.firstTrigger if this sequence does not have any triggers yet
  1615. if (seq.numTriggers == 0)
  1616. {
  1617. seq.firstTrigger = 0;
  1618. for (S32 i = 0; i < seqIndex; i++)
  1619. seq.firstTrigger += sequences[i].numTriggers;
  1620. }
  1621. // Find where to insert the trigger (sorted by keyframe)
  1622. S32 trigIndex;
  1623. for (trigIndex = seq.firstTrigger; trigIndex < (seq.firstTrigger + seq.numTriggers); trigIndex++)
  1624. {
  1625. const TSShape::Trigger& trig = triggers[trigIndex];
  1626. if ((S32)(trig.pos * seq.numKeyframes) > keyframe)
  1627. break;
  1628. }
  1629. // Create the new trigger
  1630. TSShape::Trigger trig;
  1631. trig.pos = (F32)keyframe / getMax(1, seq.numKeyframes-1);
  1632. trig.state = state;
  1633. triggers.insert(trigIndex, trig);
  1634. seq.numTriggers++;
  1635. // set invert for other triggers if needed
  1636. if ((trig.state & TSShape::Trigger::StateOn) == 0)
  1637. {
  1638. U32 offTrigger = (trig.state & TSShape::Trigger::StateMask);
  1639. for (S32 i = 0; i < seq.numTriggers; i++)
  1640. {
  1641. if (triggers[seq.firstTrigger + i].state & offTrigger)
  1642. triggers[seq.firstTrigger + i].state |= TSShape::Trigger::InvertOnReverse;
  1643. }
  1644. }
  1645. // fixup firstTrigger index for other sequences
  1646. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1647. {
  1648. if (sequences[i].numTriggers > 0)
  1649. sequences[i].firstTrigger++;
  1650. }
  1651. // set MakePath flag so triggers will be animated
  1652. seq.flags |= TSShape::MakePath;
  1653. return true;
  1654. }
  1655. bool TSShape::removeTrigger(const String& seqName, S32 keyframe, S32 state)
  1656. {
  1657. // Find the sequence
  1658. S32 seqIndex = findSequence(seqName);
  1659. if (seqIndex < 0)
  1660. {
  1661. Con::errorf("TSShape::removeTrigger: Could not find sequence '%s'", seqName.c_str());
  1662. return false;
  1663. }
  1664. TSShape::Sequence& seq = sequences[seqIndex];
  1665. if (keyframe >= seq.numKeyframes)
  1666. {
  1667. Con::errorf("TSShape::removeTrigger: Keyframe out of range (0-%d for sequence '%s')",
  1668. seq.numKeyframes-1, seqName.c_str());
  1669. return false;
  1670. }
  1671. // Encode the trigger state
  1672. if (state < 0)
  1673. state = 1 << (-state-1);
  1674. else if (state > 0)
  1675. state = (1 << (state-1)) | TSShape::Trigger::StateOn;
  1676. // Find and remove the trigger
  1677. for (S32 trigIndex = seq.firstTrigger; trigIndex < (seq.firstTrigger + seq.numTriggers); trigIndex++)
  1678. {
  1679. TSShape::Trigger& trig = triggers[trigIndex];
  1680. S32 cmpFrame = (S32)(trig.pos * (seq.numKeyframes-1) + 0.5f);
  1681. S32 cmpState = trig.state & (~TSShape::Trigger::InvertOnReverse);
  1682. if ((cmpFrame == keyframe) && (cmpState == state))
  1683. {
  1684. triggers.erase(trigIndex);
  1685. seq.numTriggers--;
  1686. // Fix up firstTrigger for other sequences
  1687. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1688. {
  1689. if (sequences[i].numTriggers > 0)
  1690. sequences[i].firstTrigger--;
  1691. }
  1692. // Clear MakePath flag if no more triggers
  1693. if ( seq.numTriggers == 0 )
  1694. seq.flags &= (~TSShape::MakePath);
  1695. return true;
  1696. }
  1697. }
  1698. Con::errorf("TSShape::removeTrigger: Could not find trigger (%d, %d) for sequence '%s'",
  1699. keyframe, state, seqName.c_str());
  1700. return false;
  1701. }
  1702. void TSShape::getNodeKeyframe(S32 nodeIndex, const TSShape::Sequence& seq, S32 keyframe, MatrixF* mat) const
  1703. {
  1704. // Get the node rotation and translation
  1705. QuatF rot;
  1706. if (seq.rotationMatters.test(nodeIndex))
  1707. {
  1708. S32 index = seq.rotationMatters.count(nodeIndex) * seq.numKeyframes + keyframe;
  1709. nodeRotations[seq.baseRotation + index].getQuatF(&rot);
  1710. }
  1711. else
  1712. defaultRotations[nodeIndex].getQuatF(&rot);
  1713. Point3F trans;
  1714. if (seq.translationMatters.test(nodeIndex))
  1715. {
  1716. S32 index = seq.translationMatters.count(nodeIndex) * seq.numKeyframes + keyframe;
  1717. trans = nodeTranslations[seq.baseTranslation + index];
  1718. }
  1719. else
  1720. trans = defaultTranslations[nodeIndex];
  1721. // Set the keyframe matrix
  1722. rot.setMatrix(mat);
  1723. mat->setPosition(trans);
  1724. }
  1725. bool TSShape::setSequenceBlend(const String& seqName, bool blend, const String& blendRefSeqName, S32 blendRefFrame)
  1726. {
  1727. // Find the target sequence
  1728. S32 seqIndex = findSequence(seqName);
  1729. if (seqIndex < 0)
  1730. {
  1731. Con::errorf("TSShape::setSequenceBlend: Could not find sequence named '%s'", seqName.c_str());
  1732. return false;
  1733. }
  1734. TSShape::Sequence& seq = sequences[seqIndex];
  1735. // Ignore if blend flag is already correct
  1736. if (seq.isBlend() == blend)
  1737. return true;
  1738. // Find the sequence containing the reference frame
  1739. S32 blendRefSeqIndex = findSequence(blendRefSeqName);
  1740. if (blendRefSeqIndex < 0)
  1741. {
  1742. Con::errorf("TSShape::setSequenceBlend: Could not find reference sequence named '%s'", blendRefSeqName.c_str());
  1743. return false;
  1744. }
  1745. TSShape::Sequence& blendRefSeq = sequences[blendRefSeqIndex];
  1746. if ((blendRefFrame < 0) || (blendRefFrame >= blendRefSeq.numKeyframes))
  1747. {
  1748. Con::errorf("TSShape::setSequenceBlend: Reference frame out of range (0-%d)", blendRefSeq.numKeyframes-1);
  1749. return false;
  1750. }
  1751. // Set the new flag
  1752. if (blend)
  1753. seq.flags |= TSShape::Blend;
  1754. else
  1755. seq.flags &= (~TSShape::Blend);
  1756. // For each animated node in the target sequence, need to add or subtract the
  1757. // reference keyframe from each frame
  1758. TSIntegerSet nodeMatters(seq.rotationMatters);
  1759. nodeMatters.overlap(seq.translationMatters);
  1760. S32 end = nodeMatters.end();
  1761. for (S32 nodeIndex = nodeMatters.start(); nodeIndex < end; nodeMatters.next(nodeIndex))
  1762. {
  1763. MatrixF refMat;
  1764. getNodeKeyframe(nodeIndex, blendRefSeq, blendRefFrame, &refMat);
  1765. // Add or subtract the reference?
  1766. if (blend)
  1767. refMat.inverse();
  1768. bool updateRot(false), updateTrans(false);
  1769. S32 rotOffset(0), transOffset(0);
  1770. if (seq.rotationMatters.test(nodeIndex))
  1771. {
  1772. updateRot = true;
  1773. rotOffset = seq.baseRotation + seq.rotationMatters.count(nodeIndex) * seq.numKeyframes;
  1774. }
  1775. if (seq.translationMatters.test(nodeIndex))
  1776. {
  1777. updateTrans = true;
  1778. transOffset = seq.baseTranslation + seq.translationMatters.count(nodeIndex) * seq.numKeyframes;
  1779. }
  1780. for (S32 frame = 0; frame < seq.numKeyframes; frame++)
  1781. {
  1782. MatrixF oldMat;
  1783. getNodeKeyframe(nodeIndex, seq, frame, &oldMat);
  1784. MatrixF newMat;
  1785. newMat.mul(refMat, oldMat);
  1786. if (updateRot)
  1787. nodeRotations[rotOffset + frame].set(QuatF(newMat));
  1788. if (updateTrans)
  1789. nodeTranslations[transOffset + frame] = newMat.getPosition();
  1790. }
  1791. }
  1792. // Update sequence blend information
  1793. seq.sourceData.blendSeq = blendRefSeqName;
  1794. seq.sourceData.blendFrame = blendRefFrame;
  1795. return true;
  1796. }
  1797. bool TSShape::setSequenceGroundSpeed(const String& seqName, const Point3F& trans, const Point3F& rot)
  1798. {
  1799. // Find the sequence
  1800. S32 seqIndex = findSequence(seqName);
  1801. if (seqIndex < 0)
  1802. {
  1803. Con::errorf("setSequenceGroundSpeed: Could not find sequence named '%s'", seqName.c_str());
  1804. return false;
  1805. }
  1806. TSShape::Sequence& seq = sequences[seqIndex];
  1807. // Determine how many ground-frames to generate (FPS=10, at least 1 frame)
  1808. const F32 groundFrameRate = 10.0f;
  1809. S32 numFrames = getMax(1, (S32)(seq.duration * groundFrameRate));
  1810. // Allocate space for the frames (add/delete frames as required)
  1811. S32 frameAdjust = numFrames - seq.numGroundFrames;
  1812. for (S32 i = 0; i < mAbs(frameAdjust); i++)
  1813. {
  1814. if (frameAdjust > 0)
  1815. {
  1816. groundTranslations.insert(seq.firstGroundFrame);
  1817. groundRotations.insert(seq.firstGroundFrame);
  1818. }
  1819. else
  1820. {
  1821. groundTranslations.erase(seq.firstGroundFrame);
  1822. groundRotations.erase(seq.firstGroundFrame);
  1823. }
  1824. }
  1825. // Fixup ground frame indices
  1826. seq.numGroundFrames += frameAdjust;
  1827. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1828. sequences[i].firstGroundFrame += frameAdjust;
  1829. // Generate the ground-frames
  1830. Point3F adjTrans = trans;
  1831. Point3F adjRot = rot;
  1832. if (seq.numGroundFrames > 0)
  1833. {
  1834. adjTrans /= seq.numGroundFrames;
  1835. adjRot /= seq.numGroundFrames;
  1836. }
  1837. QuatF rotSpeed(adjRot);
  1838. QuatF groundRot(rotSpeed);
  1839. for (S32 i = 0; i < seq.numGroundFrames; i++)
  1840. {
  1841. groundTranslations[seq.firstGroundFrame + i] = adjTrans * (i + 1);
  1842. groundRotations[seq.firstGroundFrame + i].set(groundRot);
  1843. groundRot *= rotSpeed;
  1844. }
  1845. // set MakePath flag so ground frames will be animated
  1846. seq.flags |= TSShape::MakePath;
  1847. return true;
  1848. }
  1849. void TSShape::makeEditable()
  1850. {
  1851. mNeedReinit = true;
  1852. if (mShapeVertexData.base == NULL)
  1853. return;
  1854. for (U32 i = 0; i < meshes.size(); i++)
  1855. {
  1856. if (meshes[i])
  1857. {
  1858. meshes[i]->makeEditable();
  1859. }
  1860. }
  1861. mShapeVertexData.set(NULL, 0);
  1862. }
  1863. bool TSShape::needsReinit()
  1864. {
  1865. return mVertexSize == 0 || mShapeVertexData.base == NULL || mNeedReinit;
  1866. }