tsShape.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  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 "ts/tsShape.h"
  24. #include "ts/tsLastDetail.h"
  25. #include "ts/tsMaterialList.h"
  26. #include "core/stringTable.h"
  27. #include "console/console.h"
  28. #include "ts/tsShapeInstance.h"
  29. #include "collision/convex.h"
  30. #include "materials/matInstance.h"
  31. #include "materials/materialManager.h"
  32. #include "math/mathIO.h"
  33. #include "core/util/endian.h"
  34. #include "core/stream/fileStream.h"
  35. #include "console/compiler.h"
  36. #include "core/fileObject.h"
  37. #ifdef TORQUE_COLLADA
  38. extern TSShape* loadColladaShape(const Torque::Path &path);
  39. #endif
  40. #ifdef TORQUE_ASSIMP
  41. extern TSShape* assimpLoadShape(const Torque::Path &path);
  42. #endif
  43. /// most recent version -- this is the version we write
  44. S32 TSShape::smVersion = 28;
  45. /// the version currently being read...valid only during a read
  46. S32 TSShape::smReadVersion = -1;
  47. const U32 TSShape::smMostRecentExporterVersion = DTS_EXPORTER_CURRENT_VERSION;
  48. F32 TSShape::smAlphaOutLastDetail = -1.0f;
  49. F32 TSShape::smAlphaInBillboard = 0.15f;
  50. F32 TSShape::smAlphaOutBillboard = 0.15f;
  51. F32 TSShape::smAlphaInDefault = -1.0f;
  52. F32 TSShape::smAlphaOutDefault = -1.0f;
  53. // don't bother even loading this many of the highest detail levels (but
  54. // always load last renderable detail)
  55. S32 TSShape::smNumSkipLoadDetails = 0;
  56. bool TSShape::smInitOnRead = true;
  57. bool TSShape::smUseHardwareSkinning = true;
  58. U32 TSShape::smMaxSkinBones = 70;
  59. TSShape::TSShape()
  60. {
  61. materialList = NULL;
  62. mReadVersion = -1; // -1 means constructed from scratch (e.g., in exporter or no read yet)
  63. mSequencesConstructed = false;
  64. mShapeData = NULL;
  65. mShapeDataSize = 0;
  66. mUseDetailFromScreenError = false;
  67. mNeedReinit = false;
  68. mDetailLevelLookup.setSize( 1 );
  69. mDetailLevelLookup[0].set( -1, 0 );
  70. VECTOR_SET_ASSOCIATION(sequences);
  71. VECTOR_SET_ASSOCIATION(nodeRotations);
  72. VECTOR_SET_ASSOCIATION(nodeTranslations);
  73. VECTOR_SET_ASSOCIATION(nodeUniformScales);
  74. VECTOR_SET_ASSOCIATION(nodeAlignedScales);
  75. VECTOR_SET_ASSOCIATION(nodeArbitraryScaleRots);
  76. VECTOR_SET_ASSOCIATION(nodeArbitraryScaleFactors);
  77. VECTOR_SET_ASSOCIATION(groundRotations);
  78. VECTOR_SET_ASSOCIATION(groundTranslations);
  79. VECTOR_SET_ASSOCIATION(triggers);
  80. VECTOR_SET_ASSOCIATION(billboardDetails);
  81. VECTOR_SET_ASSOCIATION(detailCollisionAccelerators);
  82. VECTOR_SET_ASSOCIATION(names);
  83. VECTOR_SET_ASSOCIATION( nodes );
  84. VECTOR_SET_ASSOCIATION( objects );
  85. VECTOR_SET_ASSOCIATION( objectStates );
  86. VECTOR_SET_ASSOCIATION( subShapeFirstNode );
  87. VECTOR_SET_ASSOCIATION( subShapeFirstObject );
  88. VECTOR_SET_ASSOCIATION( detailFirstSkin );
  89. VECTOR_SET_ASSOCIATION( subShapeNumNodes );
  90. VECTOR_SET_ASSOCIATION( subShapeNumObjects );
  91. VECTOR_SET_ASSOCIATION( details );
  92. VECTOR_SET_ASSOCIATION( defaultRotations );
  93. VECTOR_SET_ASSOCIATION( defaultTranslations );
  94. VECTOR_SET_ASSOCIATION( subShapeFirstTranslucentObject );
  95. VECTOR_SET_ASSOCIATION( meshes );
  96. VECTOR_SET_ASSOCIATION( alphaIn );
  97. VECTOR_SET_ASSOCIATION( alphaOut );
  98. }
  99. TSShape::~TSShape()
  100. {
  101. delete materialList;
  102. S32 i;
  103. // everything left over here is a legit mesh
  104. for (i=0; i<meshes.size(); i++)
  105. {
  106. if (!meshes[i])
  107. continue;
  108. // Handle meshes that were either assembled with the shape or added later
  109. if (((S8*)meshes[i] >= mShapeData) && ((S8*)meshes[i] < (mShapeData + mShapeDataSize)))
  110. destructInPlace(meshes[i]);
  111. else
  112. delete meshes[i];
  113. }
  114. for (i=0; i<billboardDetails.size(); i++)
  115. {
  116. delete billboardDetails[i];
  117. billboardDetails[i] = NULL;
  118. }
  119. billboardDetails.clear();
  120. // Delete any generated accelerators
  121. S32 dca;
  122. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  123. {
  124. ConvexHullAccelerator* accel = detailCollisionAccelerators[dca];
  125. if (accel != NULL) {
  126. delete [] accel->vertexList;
  127. delete [] accel->normalList;
  128. for (S32 j = 0; j < accel->numVerts; j++)
  129. delete [] accel->emitStrings[j];
  130. delete [] accel->emitStrings;
  131. delete accel;
  132. }
  133. }
  134. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  135. detailCollisionAccelerators[dca] = NULL;
  136. if( mShapeData )
  137. delete[] mShapeData;
  138. }
  139. const String& TSShape::getName( S32 nameIndex ) const
  140. {
  141. AssertFatal(nameIndex>=0 && nameIndex<names.size(),"TSShape::getName");
  142. return names[nameIndex];
  143. }
  144. const String& TSShape::getMeshName( S32 meshIndex ) const
  145. {
  146. S32 nameIndex = objects[meshIndex].nameIndex;
  147. if ( nameIndex < 0 )
  148. return String::EmptyString;
  149. return names[nameIndex];
  150. }
  151. const String& TSShape::getNodeName( S32 nodeIndex ) const
  152. {
  153. S32 nameIdx = nodes[nodeIndex].nameIndex;
  154. if ( nameIdx < 0 )
  155. return String::EmptyString;
  156. return names[nameIdx];
  157. }
  158. const String& TSShape::getSequenceName( S32 seqIndex ) const
  159. {
  160. AssertFatal(seqIndex >= 0 && seqIndex<sequences.size(),"TSShape::getSequenceName index beyond range");
  161. S32 nameIdx = sequences[seqIndex].nameIndex;
  162. if ( nameIdx < 0 )
  163. return String::EmptyString;
  164. return names[nameIdx];
  165. }
  166. S32 TSShape::findName(const String &name) const
  167. {
  168. for (S32 i=0; i<names.size(); i++)
  169. {
  170. if (names[i].equal( name, String::NoCase ))
  171. return i;
  172. }
  173. return -1;
  174. }
  175. const String& TSShape::getTargetName( S32 mapToNameIndex ) const
  176. {
  177. S32 targetCount = materialList->getMaterialNameList().size();
  178. if(mapToNameIndex < 0 || mapToNameIndex >= targetCount)
  179. return String::EmptyString;
  180. return materialList->getMaterialNameList()[mapToNameIndex];
  181. }
  182. S32 TSShape::getTargetCount() const
  183. {
  184. if(!this)
  185. return -1;
  186. return materialList->getMaterialNameList().size();
  187. }
  188. S32 TSShape::findNode(S32 nameIndex) const
  189. {
  190. for (S32 i=0; i<nodes.size(); i++)
  191. if (nodes[i].nameIndex==nameIndex)
  192. return i;
  193. return -1;
  194. }
  195. S32 TSShape::findObject(S32 nameIndex) const
  196. {
  197. for (S32 i=0; i<objects.size(); i++)
  198. if (objects[i].nameIndex==nameIndex)
  199. return i;
  200. return -1;
  201. }
  202. S32 TSShape::findDetail(S32 nameIndex) const
  203. {
  204. for (S32 i=0; i<details.size(); i++)
  205. if (details[i].nameIndex==nameIndex)
  206. return i;
  207. return -1;
  208. }
  209. S32 TSShape::findDetailBySize(S32 size) const
  210. {
  211. for (S32 i=0; i<details.size(); i++)
  212. if (details[i].size==size)
  213. return i;
  214. return -1;
  215. }
  216. S32 TSShape::findSequence(S32 nameIndex) const
  217. {
  218. for (S32 i=0; i<sequences.size(); i++)
  219. if (sequences[i].nameIndex==nameIndex)
  220. return i;
  221. return -1;
  222. }
  223. bool TSShape::findMeshIndex(const String& meshName, S32& objIndex, S32& meshIndex)
  224. {
  225. // Determine the object name and detail size from the mesh name
  226. S32 detailSize = 999;
  227. objIndex = findObject(String::GetTrailingNumber(meshName, detailSize));
  228. if (objIndex < 0)
  229. return false;
  230. // Determine the subshape this object belongs to
  231. S32 subShapeIndex = getSubShapeForObject(objIndex);
  232. AssertFatal(subShapeIndex < subShapeFirstObject.size(), "Could not find subshape for object!");
  233. // Get the detail levels for the subshape
  234. Vector<S32> validDetails;
  235. getSubShapeDetails(subShapeIndex, validDetails);
  236. // Find the detail with the correct size
  237. for (meshIndex = 0; meshIndex < validDetails.size(); meshIndex++)
  238. {
  239. const TSShape::Detail& det = details[validDetails[meshIndex]];
  240. if (detailSize == det.size)
  241. return true;
  242. }
  243. return false;
  244. }
  245. bool TSShape::needsBufferUpdate()
  246. {
  247. // No buffer? definitely need an update!
  248. if (mVertexSize == 0 || mShapeVertexData.size == 0)
  249. return true;
  250. // Check if we have modified vertex data
  251. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  252. {
  253. TSMesh *mesh = *iter;
  254. if (!mesh ||
  255. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  256. mesh->getMeshType() != TSMesh::SkinMeshType))
  257. continue;
  258. // NOTE: cant use mVertexData.isReady since that might not be init'd at this stage
  259. if (mesh->mVertSize == 0)
  260. return true;
  261. }
  262. return false;
  263. }
  264. TSMesh* TSShape::findMesh(const String& meshName)
  265. {
  266. S32 objIndex, meshIndex;
  267. if (!findMeshIndex(meshName, objIndex, meshIndex))
  268. return 0;
  269. return meshes[objects[objIndex].startMeshIndex + meshIndex];
  270. }
  271. S32 TSShape::getSubShapeForNode(S32 nodeIndex)
  272. {
  273. for (S32 i = 0; i < subShapeFirstNode.size(); i++)
  274. {
  275. S32 start = subShapeFirstNode[i];
  276. S32 end = start + subShapeNumNodes[i];
  277. if ((nodeIndex >= start) && (nodeIndex < end))
  278. return i;;
  279. }
  280. return -1;
  281. }
  282. S32 TSShape::getSubShapeForObject(S32 objIndex)
  283. {
  284. for (S32 i = 0; i < subShapeFirstObject.size(); i++)
  285. {
  286. S32 start = subShapeFirstObject[i];
  287. S32 end = start + subShapeNumObjects[i];
  288. if ((objIndex >= start) && (objIndex < end))
  289. return i;
  290. }
  291. return -1;
  292. }
  293. void TSShape::getSubShapeDetails(S32 subShapeIndex, Vector<S32>& validDetails)
  294. {
  295. validDetails.clear();
  296. for (S32 i = 0; i < details.size(); i++)
  297. {
  298. if ((details[i].subShapeNum == subShapeIndex) ||
  299. (details[i].subShapeNum < 0))
  300. validDetails.push_back(i);
  301. }
  302. }
  303. void TSShape::getNodeWorldTransform(S32 nodeIndex, MatrixF* mat) const
  304. {
  305. if ( nodeIndex == -1 )
  306. {
  307. mat->identity();
  308. }
  309. else
  310. {
  311. // Calculate the world transform of the given node
  312. defaultRotations[nodeIndex].getQuatF().setMatrix(mat);
  313. mat->setPosition(defaultTranslations[nodeIndex]);
  314. S32 parentIndex = nodes[nodeIndex].parentIndex;
  315. while (parentIndex != -1)
  316. {
  317. MatrixF mat2(*mat);
  318. defaultRotations[parentIndex].getQuatF().setMatrix(mat);
  319. mat->setPosition(defaultTranslations[parentIndex]);
  320. mat->mul(mat2);
  321. parentIndex = nodes[parentIndex].parentIndex;
  322. }
  323. }
  324. }
  325. void TSShape::getNodeObjects(S32 nodeIndex, Vector<S32>& nodeObjects)
  326. {
  327. for (S32 i = 0; i < objects.size(); i++)
  328. {
  329. if ((nodeIndex == -1) || (objects[i].nodeIndex == nodeIndex))
  330. nodeObjects.push_back(i);
  331. }
  332. }
  333. void TSShape::getNodeChildren(S32 nodeIndex, Vector<S32>& nodeChildren)
  334. {
  335. for (S32 i = 0; i < nodes.size(); i++)
  336. {
  337. if (nodes[i].parentIndex == nodeIndex)
  338. nodeChildren.push_back(i);
  339. }
  340. }
  341. void TSShape::getObjectDetails(S32 objIndex, Vector<S32>& objDetails)
  342. {
  343. // Get the detail levels for this subshape
  344. Vector<S32> validDetails;
  345. getSubShapeDetails(getSubShapeForObject(objIndex), validDetails);
  346. // Get the non-null details for this object
  347. const TSShape::Object& obj = objects[objIndex];
  348. for (S32 i = 0; i < obj.numMeshes; i++)
  349. {
  350. if (meshes[obj.startMeshIndex + i])
  351. objDetails.push_back(validDetails[i]);
  352. }
  353. }
  354. void TSShape::init()
  355. {
  356. initObjects();
  357. initVertexFeatures();
  358. initMaterialList();
  359. mNeedReinit = false;
  360. }
  361. void TSShape::initObjects()
  362. {
  363. S32 numSubShapes = subShapeFirstNode.size();
  364. AssertFatal(numSubShapes == subShapeFirstObject.size(), "TSShape::initObjects");
  365. S32 i, j;
  366. // set up parent/child relationships on nodes and objects
  367. for (i = 0; i<nodes.size(); i++)
  368. nodes[i].firstObject = nodes[i].firstChild = nodes[i].nextSibling = -1;
  369. for (i = 0; i<nodes.size(); i++)
  370. {
  371. S32 parentIndex = nodes[i].parentIndex;
  372. if (parentIndex >= 0)
  373. {
  374. if (nodes[parentIndex].firstChild<0)
  375. nodes[parentIndex].firstChild = i;
  376. else
  377. {
  378. S32 child = nodes[parentIndex].firstChild;
  379. while (nodes[child].nextSibling >= 0)
  380. child = nodes[child].nextSibling;
  381. nodes[child].nextSibling = i;
  382. }
  383. }
  384. }
  385. for (i = 0; i<objects.size(); i++)
  386. {
  387. objects[i].nextSibling = -1;
  388. S32 nodeIndex = objects[i].nodeIndex;
  389. if (nodeIndex >= 0)
  390. {
  391. if (nodes[nodeIndex].firstObject<0)
  392. nodes[nodeIndex].firstObject = i;
  393. else
  394. {
  395. S32 objectIndex = nodes[nodeIndex].firstObject;
  396. while (objects[objectIndex].nextSibling >= 0)
  397. objectIndex = objects[objectIndex].nextSibling;
  398. objects[objectIndex].nextSibling = i;
  399. }
  400. }
  401. }
  402. mFlags = 0;
  403. for (i = 0; i<sequences.size(); i++)
  404. {
  405. if (!sequences[i].animatesScale())
  406. continue;
  407. U32 curVal = mFlags & AnyScale;
  408. U32 newVal = sequences[i].flags & AnyScale;
  409. mFlags &= ~(AnyScale);
  410. mFlags |= getMax(curVal, newVal); // take the larger value (can only convert upwards)
  411. }
  412. // set up alphaIn and alphaOut vectors...
  413. alphaIn.setSize(details.size());
  414. alphaOut.setSize(details.size());
  415. for (i = 0; i<details.size(); i++)
  416. {
  417. if (details[i].size<0)
  418. {
  419. // we don't care...
  420. alphaIn[i] = 0.0f;
  421. alphaOut[i] = 0.0f;
  422. }
  423. else if (i + 1 == details.size() || details[i + 1].size<0)
  424. {
  425. alphaIn[i] = 0.0f;
  426. alphaOut[i] = smAlphaOutLastDetail;
  427. }
  428. else
  429. {
  430. if (details[i + 1].subShapeNum<0)
  431. {
  432. // following detail is a billboard detail...treat special...
  433. alphaIn[i] = smAlphaInBillboard;
  434. alphaOut[i] = smAlphaOutBillboard;
  435. }
  436. else
  437. {
  438. // next detail is normal detail
  439. alphaIn[i] = smAlphaInDefault;
  440. alphaOut[i] = smAlphaOutDefault;
  441. }
  442. }
  443. }
  444. for (i = mSmallestVisibleDL - 1; i >= 0; i--)
  445. {
  446. if (i<smNumSkipLoadDetails)
  447. {
  448. // this detail level renders when pixel size
  449. // is larger than our cap...zap all the meshes and decals
  450. // associated with it and use the next detail level
  451. // instead...
  452. S32 ss = details[i].subShapeNum;
  453. S32 od = details[i].objectDetailNum;
  454. if (ss == details[i + 1].subShapeNum && od == details[i + 1].objectDetailNum)
  455. // doh! already done this one (init can be called multiple times on same shape due
  456. // to sequence importing).
  457. continue;
  458. details[i].subShapeNum = details[i + 1].subShapeNum;
  459. details[i].objectDetailNum = details[i + 1].objectDetailNum;
  460. }
  461. }
  462. for (i = 0; i<details.size(); i++)
  463. {
  464. S32 count = 0;
  465. S32 ss = details[i].subShapeNum;
  466. S32 od = details[i].objectDetailNum;
  467. if (ss<0)
  468. {
  469. // billboard detail...
  470. details[i].polyCount = 2;
  471. continue;
  472. }
  473. S32 start = subShapeFirstObject[ss];
  474. S32 end = start + subShapeNumObjects[ss];
  475. for (j = start; j<end; j++)
  476. {
  477. Object & obj = objects[j];
  478. if (od<obj.numMeshes)
  479. {
  480. TSMesh * mesh = meshes[obj.startMeshIndex + od];
  481. count += mesh ? mesh->getNumPolys() : 0;
  482. }
  483. }
  484. details[i].polyCount = count;
  485. }
  486. // Init the collision accelerator array. Note that we don't compute the
  487. // accelerators until the app requests them
  488. {
  489. S32 dca;
  490. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  491. {
  492. ConvexHullAccelerator* accel = detailCollisionAccelerators[dca];
  493. if (accel != NULL) {
  494. delete[] accel->vertexList;
  495. delete[] accel->normalList;
  496. for (S32 vertID = 0; vertID < accel->numVerts; vertID++)
  497. delete[] accel->emitStrings[vertID];
  498. delete[] accel->emitStrings;
  499. delete accel;
  500. }
  501. }
  502. detailCollisionAccelerators.setSize(details.size());
  503. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  504. detailCollisionAccelerators[dca] = NULL;
  505. }
  506. // Assign mesh parents & format
  507. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  508. {
  509. TSMesh *mesh = *iter;
  510. if (!mesh)
  511. continue;
  512. if (mesh->mParentMesh >= meshes.size())
  513. {
  514. Con::warnf("Mesh %i has a bad parentMeshObject (%i)", iter - meshes.begin(), mesh->mParentMesh);
  515. }
  516. if (mesh->mParentMesh >= 0 && mesh->mParentMesh < meshes.size())
  517. {
  518. mesh->mParentMeshObject = meshes[mesh->mParentMesh];
  519. }
  520. else
  521. {
  522. mesh->mParentMeshObject = NULL;
  523. }
  524. mesh->mVertexFormat = &mVertexFormat;
  525. }
  526. }
  527. void TSShape::initVertexBuffers()
  528. {
  529. // Assumes mVertexData is valid
  530. if (!mShapeVertexData.vertexDataReady)
  531. {
  532. AssertFatal(false, "WTF");
  533. }
  534. U32 destIndices = 0;
  535. U32 destPrims = 0;
  536. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  537. {
  538. TSMesh *mesh = *iter;
  539. if (!mesh ||
  540. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  541. mesh->getMeshType() != TSMesh::SkinMeshType))
  542. continue;
  543. destIndices += mesh->mIndices.size();
  544. destPrims += mesh->mPrimitives.size();
  545. }
  546. // For HW skinning we can just use the static buffer
  547. if (TSShape::smUseHardwareSkinning)
  548. {
  549. getVertexBuffer(mShapeVertexBuffer, GFXBufferTypeStatic);
  550. }
  551. // Also the IBO
  552. mShapeVertexIndices.set(GFX, destIndices, destPrims, GFXBufferTypeStatic);
  553. U16 *indicesStart = NULL;
  554. mShapeVertexIndices.lock(&indicesStart, NULL);
  555. U16 *ibIndices = indicesStart;
  556. GFXPrimitive *piInput = mShapeVertexIndices->mPrimitiveArray;
  557. U32 vertStart = 0;
  558. U32 primStart = 0;
  559. U32 indStart = 0;
  560. // Create VBO
  561. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  562. {
  563. TSMesh *mesh = *iter;
  564. if (!mesh ||
  565. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  566. mesh->getMeshType() != TSMesh::SkinMeshType))
  567. continue;
  568. // Make the offset vbo
  569. mesh->mPrimBufferOffset = primStart;
  570. // Dump primitives to locked buffer
  571. mesh->dumpPrimitives(vertStart, indStart, piInput, ibIndices);
  572. AssertFatal(mesh->mVertOffset / mVertexSize == vertStart, "offset mismatch");
  573. vertStart += mesh->mNumVerts;
  574. primStart += mesh->mPrimitives.size();
  575. indStart += mesh->mIndices.size();
  576. mesh->mVB = mShapeVertexBuffer;
  577. mesh->mPB = mShapeVertexIndices;
  578. // Advance
  579. piInput += mesh->mPrimitives.size();
  580. ibIndices += mesh->mIndices.size();
  581. if (TSSkinMesh::smDebugSkinVerts && mesh->getMeshType() == TSMesh::SkinMeshType)
  582. {
  583. static_cast<TSSkinMesh*>(mesh)->printVerts();
  584. }
  585. }
  586. #ifdef TORQUE_DEBUG
  587. // Verify prims
  588. if (TSSkinMesh::smDebugSkinVerts)
  589. {
  590. U32 vertsInBuffer = mShapeVertexData.size / mVertexSize;
  591. U32 indsInBuffer = ibIndices - indicesStart;
  592. for (U32 primID = 0; primID < primStart; primID++)
  593. {
  594. GFXPrimitive &prim = mShapeVertexIndices->mPrimitiveArray[primID];
  595. if (prim.type != GFXTriangleList && prim.type != GFXTriangleStrip)
  596. {
  597. AssertFatal(false, "Unexpected triangle list");
  598. }
  599. if (prim.type == GFXTriangleStrip)
  600. continue;
  601. AssertFatal(prim.startVertex < vertsInBuffer, "wrong start vertex");
  602. AssertFatal((prim.startVertex + prim.numVertices) <= vertsInBuffer, "too many verts");
  603. AssertFatal(prim.startIndex + (prim.numPrimitives * 3) <= indsInBuffer, "too many inds");
  604. for (U32 i = prim.startIndex; i < prim.startIndex + (prim.numPrimitives * 3); i++)
  605. {
  606. if (indicesStart[i] >= vertsInBuffer)
  607. {
  608. AssertFatal(false, "vert not in buffer");
  609. }
  610. U16 idx = indicesStart[i];
  611. if (idx < prim.minIndex)
  612. {
  613. AssertFatal(false, "index out of minIndex range");
  614. }
  615. }
  616. }
  617. }
  618. #endif
  619. mShapeVertexIndices.unlock();
  620. }
  621. void TSShape::getVertexBuffer(TSVertexBufferHandle &vb, GFXBufferType bufferType)
  622. {
  623. vb.set(GFX, mVertexSize, &mVertexFormat, mShapeVertexData.size / mVertexSize, bufferType);
  624. U8 *vertPtr = vb.lock();
  625. dMemcpy(vertPtr, mShapeVertexData.base, mShapeVertexData.size);
  626. vb.unlock();
  627. }
  628. void TSShape::initVertexBufferPointers()
  629. {
  630. if (mBasicVertexFormat.vertexSize == -1)
  631. return;
  632. AssertFatal(mVertexSize == mBasicVertexFormat.vertexSize, "vertex size mismatch");
  633. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  634. {
  635. TSMesh *mesh = *iter;
  636. if (mesh &&
  637. (mesh->getMeshType() == TSMesh::StandardMeshType ||
  638. mesh->getMeshType() == TSMesh::SkinMeshType))
  639. {
  640. // Set buffer
  641. AssertFatal(mesh->mNumVerts == 0 || mesh->mNumVerts >= mesh->vertsPerFrame, "invalid verts per frame");
  642. if (mesh->mVertSize > 0 && !mesh->mVertexData.isReady())
  643. {
  644. U32 boneOffset = 0;
  645. U32 texCoordOffset = 0;
  646. AssertFatal(mesh->mVertSize == mVertexFormat.getSizeInBytes(), "mismatch in format size");
  647. if (mBasicVertexFormat.boneOffset >= 0)
  648. {
  649. boneOffset = mBasicVertexFormat.boneOffset;
  650. }
  651. if (mBasicVertexFormat.texCoordOffset >= 0)
  652. {
  653. texCoordOffset = mBasicVertexFormat.texCoordOffset;
  654. }
  655. // Initialize the vertex data
  656. mesh->mVertexData.set(mShapeVertexData.base + mesh->mVertOffset, mesh->mVertSize, mesh->mNumVerts, texCoordOffset, boneOffset, false);
  657. mesh->mVertexData.setReady(true);
  658. }
  659. }
  660. }
  661. }
  662. void TSShape::initVertexFeatures()
  663. {
  664. if (!needsBufferUpdate())
  665. {
  666. // Init format from basic format
  667. mVertexFormat.clear();
  668. mBasicVertexFormat.getFormat(mVertexFormat);
  669. mVertexSize = mVertexFormat.getSizeInBytes();
  670. initVertexBufferPointers();
  671. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  672. {
  673. TSMesh *mesh = *iter;
  674. if (mesh &&
  675. (mesh->getMeshType() == TSMesh::SkinMeshType))
  676. {
  677. static_cast<TSSkinMesh*>(mesh)->createSkinBatchData();
  678. }
  679. }
  680. // Make sure VBO is init'd
  681. initVertexBuffers();
  682. return;
  683. }
  684. // Cleanout VBO
  685. mShapeVertexBuffer = NULL;
  686. // Make sure mesh has verts stored in mesh data, we're recreating the buffer
  687. TSBasicVertexFormat basicFormat;
  688. initVertexBufferPointers();
  689. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  690. {
  691. TSMesh *mesh = *iter;
  692. if (mesh &&
  693. (mesh->getMeshType() == TSMesh::StandardMeshType ||
  694. mesh->getMeshType() == TSMesh::SkinMeshType))
  695. {
  696. // Make sure we have everything in the vert lists
  697. mesh->makeEditable();
  698. // We need the skin batching data here to determine bone counts
  699. if (mesh->getMeshType() == TSMesh::SkinMeshType)
  700. {
  701. static_cast<TSSkinMesh*>(mesh)->createSkinBatchData();
  702. }
  703. basicFormat.addMeshRequirements(mesh);
  704. }
  705. }
  706. mVertexFormat.clear();
  707. mBasicVertexFormat = basicFormat;
  708. mBasicVertexFormat.getFormat(mVertexFormat);
  709. mBasicVertexFormat.vertexSize = mVertexFormat.getSizeInBytes();
  710. mVertexSize = mBasicVertexFormat.vertexSize;
  711. U32 destVertex = 0;
  712. U32 destIndices = 0;
  713. // Go fix up meshes to include defaults for optional features
  714. // and initialize them if they're not a skin mesh.
  715. U32 count = 0;
  716. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  717. {
  718. TSMesh *mesh = *iter;
  719. if (!mesh ||
  720. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  721. mesh->getMeshType() != TSMesh::SkinMeshType))
  722. continue;
  723. mesh->mVertSize = mVertexSize;
  724. mesh->mVertOffset = destVertex;
  725. destVertex += mesh->mVertSize * mesh->getNumVerts();
  726. destIndices += mesh->mIndices.size();
  727. count += 1;
  728. }
  729. // Don't set up if we have no meshes
  730. if (count == 0)
  731. {
  732. mShapeVertexData.set(NULL, 0);
  733. mShapeVertexData.vertexDataReady = false;
  734. return;
  735. }
  736. // Now we can create the VBO
  737. mShapeVertexData.set(NULL, 0);
  738. U8 *vertexData = (U8*)dMalloc_aligned(destVertex, 16);
  739. U8 *vertexDataPtr = vertexData;
  740. mShapeVertexData.set(vertexData, destVertex);
  741. // Create VBO
  742. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  743. {
  744. TSMesh *mesh = *iter;
  745. if (!mesh ||
  746. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  747. mesh->getMeshType() != TSMesh::SkinMeshType))
  748. continue;
  749. U32 boneOffset = 0;
  750. U32 texCoordOffset = 0;
  751. AssertFatal(mesh->mVertSize == mVertexFormat.getSizeInBytes(), "mismatch in format size");
  752. if (mBasicVertexFormat.boneOffset >= 0)
  753. {
  754. boneOffset = mBasicVertexFormat.boneOffset;
  755. }
  756. if (mBasicVertexFormat.texCoordOffset >= 0)
  757. {
  758. texCoordOffset = mBasicVertexFormat.texCoordOffset;
  759. }
  760. // Dump everything
  761. mesh->mVertexData.setReady(false);
  762. mesh->mVertSize = mVertexSize;
  763. AssertFatal(mesh->mVertOffset == vertexDataPtr - vertexData, "vertex offset mismatch");
  764. mesh->mNumVerts = mesh->getNumVerts();
  765. // Correct bad meshes
  766. if (mesh->mNumVerts != 0 && mesh->vertsPerFrame > mesh->mNumVerts)
  767. {
  768. Con::warnf("Shape mesh has bad vertsPerFrame (%i, should be <= %i)", mesh->vertsPerFrame, mesh->mNumVerts);
  769. mesh->vertsPerFrame = mesh->mNumVerts;
  770. }
  771. mesh->mVertexData.set(mShapeVertexData.base + mesh->mVertOffset, mesh->mVertSize, mesh->mNumVerts, texCoordOffset, boneOffset, false);
  772. mesh->convertToVertexData();
  773. mesh->mVertexData.setReady(true);
  774. #ifdef TORQUE_DEBUG
  775. AssertFatal(mesh->mNumVerts == mesh->mVerts.size(), "vert mismatch");
  776. for (U32 i = 0; i < mesh->mNumVerts; i++)
  777. {
  778. Point3F v1 = mesh->mVerts[i];
  779. Point3F v2 = mesh->mVertexData.getBase(i).vert();
  780. AssertFatal(mesh->mVerts[i] == mesh->mVertexData.getBase(i).vert(), "vert data mismatch");
  781. }
  782. if (mesh->getMeshType() == TSMesh::SkinMeshType)
  783. {
  784. AssertFatal(mesh->getMaxBonesPerVert() != 0, "Skin mesh has no bones used, very strange!");
  785. }
  786. #endif
  787. // Advance
  788. vertexDataPtr += mesh->mVertSize * mesh->mNumVerts;
  789. AssertFatal(vertexDataPtr - vertexData <= destVertex, "Vertex data overflow");
  790. }
  791. mShapeVertexData.vertexDataReady = true;
  792. initVertexBuffers();
  793. }
  794. void TSShape::setupBillboardDetails( const String &cachePath )
  795. {
  796. // set up billboard details -- only do this once, meaning that
  797. // if we add a sequence to the shape we don't redo the billboard
  798. // details...
  799. if ( !billboardDetails.empty() )
  800. return;
  801. for ( U32 i=0; i < details.size(); i++ )
  802. {
  803. const Detail &det = details[i];
  804. if ( det.subShapeNum >= 0 )
  805. continue; // not a billboard detail
  806. while (billboardDetails.size() <= i )
  807. billboardDetails.push_back(NULL);
  808. billboardDetails[i] = new TSLastDetail( this,
  809. cachePath,
  810. det.bbEquatorSteps,
  811. det.bbPolarSteps,
  812. det.bbPolarAngle,
  813. det.bbIncludePoles,
  814. det.bbDetailLevel,
  815. det.bbDimension );
  816. billboardDetails[i]->update();
  817. }
  818. }
  819. void TSShape::initMaterialList()
  820. {
  821. S32 numSubShapes = subShapeFirstObject.size();
  822. #if defined(TORQUE_MAX_LIB)
  823. subShapeFirstTranslucentObject.setSize(numSubShapes);
  824. #endif
  825. S32 i,j,k;
  826. // for each subshape, find the first translucent object
  827. // also, while we're at it, set mHasTranslucency
  828. for (S32 ss = 0; ss<numSubShapes; ss++)
  829. {
  830. S32 start = subShapeFirstObject[ss];
  831. S32 end = subShapeNumObjects[ss];
  832. subShapeFirstTranslucentObject[ss] = end;
  833. for (i=start; i<end; i++)
  834. {
  835. // check to see if this object has translucency
  836. Object & obj = objects[i];
  837. for (j=0; j<obj.numMeshes; j++)
  838. {
  839. TSMesh * mesh = meshes[obj.startMeshIndex+j];
  840. if (!mesh)
  841. continue;
  842. for (k=0; k<mesh->mPrimitives.size(); k++)
  843. {
  844. if (mesh->mPrimitives[k].matIndex & TSDrawPrimitive::NoMaterial)
  845. continue;
  846. S32 flags = materialList->getFlags(mesh->mPrimitives[k].matIndex & TSDrawPrimitive::MaterialMask);
  847. if (flags & TSMaterialList::AuxiliaryMap)
  848. continue;
  849. if (flags & TSMaterialList::Translucent)
  850. {
  851. mFlags |= HasTranslucency;
  852. subShapeFirstTranslucentObject[ss] = i;
  853. break;
  854. }
  855. }
  856. if (k!=mesh->mPrimitives.size())
  857. break;
  858. }
  859. if (j!=obj.numMeshes)
  860. break;
  861. }
  862. if (i!=end)
  863. break;
  864. }
  865. }
  866. bool TSShape::preloadMaterialList(const Torque::Path &path)
  867. {
  868. if (materialList)
  869. materialList->setTextureLookupPath(path.getPath());
  870. return true;
  871. }
  872. bool TSShape::buildConvexHull(S32 dl) const
  873. {
  874. AssertFatal(dl>=0 && dl<details.size(),"TSShape::buildConvexHull: detail out of range");
  875. bool ok = true;
  876. const Detail & detail = details[dl];
  877. S32 ss = detail.subShapeNum;
  878. S32 od = detail.objectDetailNum;
  879. S32 start = subShapeFirstObject[ss];
  880. S32 end = subShapeNumObjects[ss];
  881. for (S32 i=start; i<end; i++)
  882. {
  883. TSMesh * mesh = meshes[objects[i].startMeshIndex+od];
  884. if (!mesh)
  885. continue;
  886. ok &= mesh->buildConvexHull();
  887. }
  888. return ok;
  889. }
  890. Vector<MatrixF> gTempNodeTransforms(__FILE__, __LINE__);
  891. void TSShape::computeBounds(S32 dl, Box3F & bounds) const
  892. {
  893. // if dl==-1, nothing to do
  894. if (dl==-1)
  895. return;
  896. AssertFatal(dl>=0 && dl<details.size(),"TSShapeInstance::computeBounds");
  897. // get subshape and object detail
  898. const TSDetail * detail = &details[dl];
  899. S32 ss = detail->subShapeNum;
  900. S32 od = detail->objectDetailNum;
  901. // If we have no subshapes then there is
  902. // no valid bounds for this detail level.
  903. if ( ss < 0 )
  904. return;
  905. // set up temporary storage for non-local transforms...
  906. S32 i;
  907. S32 start = subShapeFirstNode[ss];
  908. S32 end = subShapeNumNodes[ss] + start;
  909. gTempNodeTransforms.setSize(end-start);
  910. for (i=start; i<end; i++)
  911. {
  912. MatrixF mat;
  913. QuatF q;
  914. TSTransform::setMatrix(defaultRotations[i].getQuatF(&q),defaultTranslations[i],&mat);
  915. if (nodes[i].parentIndex>=0)
  916. gTempNodeTransforms[i-start].mul(gTempNodeTransforms[nodes[i].parentIndex-start],mat);
  917. else
  918. gTempNodeTransforms[i-start] = mat;
  919. }
  920. // run through objects and updating bounds as we go
  921. bounds.minExtents.set( 10E30f, 10E30f, 10E30f);
  922. bounds.maxExtents.set(-10E30f,-10E30f,-10E30f);
  923. Box3F box;
  924. start = subShapeFirstObject[ss];
  925. end = subShapeNumObjects[ss] + start;
  926. for (i=start; i<end; i++)
  927. {
  928. const Object * object = &objects[i];
  929. TSMesh * mesh = od<object->numMeshes ? meshes[object->startMeshIndex+od] : NULL;
  930. if (mesh)
  931. {
  932. static MatrixF idMat(true);
  933. if (object->nodeIndex<0)
  934. mesh->computeBounds(idMat,box);
  935. else
  936. mesh->computeBounds(gTempNodeTransforms[object->nodeIndex-start],box);
  937. bounds.minExtents.setMin(box.minExtents);
  938. bounds.maxExtents.setMax(box.maxExtents);
  939. }
  940. }
  941. }
  942. TSShapeAlloc TSShape::smTSAlloc;
  943. #define tsalloc TSShape::smTSAlloc
  944. // messy stuff: check to see if we should "skip" meshNum
  945. // this assumes that meshes for a given object are in a row
  946. // skipDL is the lowest detail number we keep (i.e., the # of details we skip)
  947. bool TSShape::checkSkip(S32 meshNum, S32 & curObject, S32 skipDL)
  948. {
  949. if (skipDL==0)
  950. // easy out...
  951. return false;
  952. // skip detail level exists on this subShape
  953. S32 skipSS = details[skipDL].subShapeNum;
  954. if (curObject<objects.size())
  955. {
  956. S32 start = objects[curObject].startMeshIndex;
  957. if (meshNum>=start)
  958. {
  959. // we are either from this object, the next object, or a decal
  960. if (meshNum < start + objects[curObject].numMeshes)
  961. {
  962. // this object...
  963. if (subShapeFirstObject[skipSS]>curObject)
  964. // haven't reached this subshape yet
  965. return true;
  966. if (skipSS+1==subShapeFirstObject.size() || curObject<subShapeFirstObject[skipSS+1])
  967. // curObject is on subshape of skip detail...make sure it's after skipDL
  968. return (meshNum-start<details[skipDL].objectDetailNum);
  969. // if we get here, then curObject occurs on subShape after skip detail (so keep it)
  970. return false;
  971. }
  972. else
  973. // advance object, try again
  974. return checkSkip(meshNum,++curObject,skipDL);
  975. }
  976. }
  977. AssertFatal(0,"TSShape::checkSkip: assertion failed");
  978. return false;
  979. }
  980. void TSShape::assembleShape()
  981. {
  982. S32 i,j;
  983. // get counts...
  984. S32 numNodes = tsalloc.get32();
  985. S32 numObjects = tsalloc.get32();
  986. S32 numDecals = tsalloc.get32();
  987. S32 numSubShapes = tsalloc.get32();
  988. S32 numIflMaterials = tsalloc.get32();
  989. S32 numNodeRots;
  990. S32 numNodeTrans;
  991. S32 numNodeUniformScales;
  992. S32 numNodeAlignedScales;
  993. S32 numNodeArbitraryScales;
  994. if (smReadVersion<22)
  995. {
  996. numNodeRots = numNodeTrans = tsalloc.get32() - numNodes;
  997. numNodeUniformScales = numNodeAlignedScales = numNodeArbitraryScales = 0;
  998. }
  999. else
  1000. {
  1001. numNodeRots = tsalloc.get32();
  1002. numNodeTrans = tsalloc.get32();
  1003. numNodeUniformScales = tsalloc.get32();
  1004. numNodeAlignedScales = tsalloc.get32();
  1005. numNodeArbitraryScales = tsalloc.get32();
  1006. }
  1007. S32 numGroundFrames = 0;
  1008. if (smReadVersion>23)
  1009. numGroundFrames = tsalloc.get32();
  1010. S32 numObjectStates = tsalloc.get32();
  1011. S32 numDecalStates = tsalloc.get32();
  1012. S32 numTriggers = tsalloc.get32();
  1013. S32 numDetails = tsalloc.get32();
  1014. S32 numMeshes = tsalloc.get32();
  1015. S32 numSkins = 0;
  1016. if (smReadVersion<23)
  1017. // in later versions, skins are kept with other meshes
  1018. numSkins = tsalloc.get32();
  1019. S32 numNames = tsalloc.get32();
  1020. // Note that we are recalculating these values later on for safety.
  1021. mSmallestVisibleSize = (F32)tsalloc.get32();
  1022. mSmallestVisibleDL = tsalloc.get32();
  1023. tsalloc.checkGuard();
  1024. // get bounds...
  1025. tsalloc.get32((S32*)&mRadius,1);
  1026. tsalloc.get32((S32*)&tubeRadius,1);
  1027. tsalloc.get32((S32*)&center,3);
  1028. tsalloc.get32((S32*)&mBounds,6);
  1029. tsalloc.checkGuard();
  1030. // copy various vectors...
  1031. S32 * ptr32 = tsalloc.copyToShape32(numNodes*5);
  1032. nodes.set(ptr32,numNodes);
  1033. tsalloc.checkGuard();
  1034. ptr32 = tsalloc.copyToShape32(numObjects*6,true);
  1035. if (!ptr32)
  1036. ptr32 = tsalloc.allocShape32(numSkins*6); // pre v23 shapes store skins and meshes separately...no longer
  1037. else
  1038. tsalloc.allocShape32(numSkins*6);
  1039. objects.set(ptr32,numObjects);
  1040. tsalloc.checkGuard();
  1041. // DEPRECATED decals
  1042. ptr32 = tsalloc.getPointer32(numDecals*5);
  1043. tsalloc.checkGuard();
  1044. // DEPRECATED ifl materials
  1045. ptr32 = tsalloc.copyToShape32(numIflMaterials*5);
  1046. tsalloc.checkGuard();
  1047. ptr32 = tsalloc.copyToShape32(numSubShapes,true);
  1048. subShapeFirstNode.set(ptr32,numSubShapes);
  1049. ptr32 = tsalloc.copyToShape32(numSubShapes,true);
  1050. subShapeFirstObject.set(ptr32,numSubShapes);
  1051. // DEPRECATED subShapeFirstDecal
  1052. ptr32 = tsalloc.getPointer32(numSubShapes);
  1053. tsalloc.checkGuard();
  1054. ptr32 = tsalloc.copyToShape32(numSubShapes);
  1055. subShapeNumNodes.set(ptr32,numSubShapes);
  1056. ptr32 = tsalloc.copyToShape32(numSubShapes);
  1057. subShapeNumObjects.set(ptr32,numSubShapes);
  1058. // DEPRECATED subShapeNumDecals
  1059. ptr32 = tsalloc.getPointer32(numSubShapes);
  1060. tsalloc.checkGuard();
  1061. ptr32 = tsalloc.allocShape32(numSubShapes);
  1062. subShapeFirstTranslucentObject.set(ptr32,numSubShapes);
  1063. // get default translation and rotation
  1064. S16 * ptr16 = tsalloc.allocShape16(0);
  1065. for (i=0;i<numNodes;i++)
  1066. tsalloc.copyToShape16(4);
  1067. defaultRotations.set(ptr16,numNodes);
  1068. tsalloc.align32();
  1069. ptr32 = tsalloc.allocShape32(0);
  1070. for (i=0;i<numNodes;i++)
  1071. {
  1072. tsalloc.copyToShape32(3);
  1073. tsalloc.copyToShape32(sizeof(Point3F)-12); // handle alignment issues w/ point3f
  1074. }
  1075. defaultTranslations.set(ptr32,numNodes);
  1076. // get any node sequence data stored in shape
  1077. nodeTranslations.setSize(numNodeTrans);
  1078. for (i=0;i<numNodeTrans;i++)
  1079. tsalloc.get32((S32*)&nodeTranslations[i],3);
  1080. nodeRotations.setSize(numNodeRots);
  1081. for (i=0;i<numNodeRots;i++)
  1082. tsalloc.get16((S16*)&nodeRotations[i],4);
  1083. tsalloc.align32();
  1084. tsalloc.checkGuard();
  1085. if (smReadVersion>21)
  1086. {
  1087. // more node sequence data...scale
  1088. nodeUniformScales.setSize(numNodeUniformScales);
  1089. for (i=0;i<numNodeUniformScales;i++)
  1090. tsalloc.get32((S32*)&nodeUniformScales[i],1);
  1091. nodeAlignedScales.setSize(numNodeAlignedScales);
  1092. for (i=0;i<numNodeAlignedScales;i++)
  1093. tsalloc.get32((S32*)&nodeAlignedScales[i],3);
  1094. nodeArbitraryScaleFactors.setSize(numNodeArbitraryScales);
  1095. for (i=0;i<numNodeArbitraryScales;i++)
  1096. tsalloc.get32((S32*)&nodeArbitraryScaleFactors[i],3);
  1097. nodeArbitraryScaleRots.setSize(numNodeArbitraryScales);
  1098. for (i=0;i<numNodeArbitraryScales;i++)
  1099. tsalloc.get16((S16*)&nodeArbitraryScaleRots[i],4);
  1100. tsalloc.align32();
  1101. tsalloc.checkGuard();
  1102. }
  1103. // old shapes need ground transforms moved to ground arrays...but only do it once
  1104. if (smReadVersion<22 && tsalloc.allocShape32(0))
  1105. {
  1106. for (i=0; i<sequences.size(); i++)
  1107. {
  1108. // move ground transform data to ground vectors
  1109. Sequence & seq = sequences[i];
  1110. S32 oldSz = groundTranslations.size();
  1111. groundTranslations.setSize(oldSz+seq.numGroundFrames);
  1112. groundRotations.setSize(oldSz+seq.numGroundFrames);
  1113. for (S32 groundFrm =0; groundFrm<seq.numGroundFrames; groundFrm++)
  1114. {
  1115. groundTranslations[groundFrm +oldSz] = nodeTranslations[seq.firstGroundFrame+ groundFrm -numNodes];
  1116. groundRotations[groundFrm +oldSz] = nodeRotations[seq.firstGroundFrame+ groundFrm -numNodes];
  1117. }
  1118. seq.firstGroundFrame = oldSz;
  1119. seq.baseTranslation -= numNodes;
  1120. seq.baseRotation -= numNodes;
  1121. seq.baseScale = 0; // not used on older shapes...but keep it clean
  1122. }
  1123. }
  1124. // version 22 & 23 shapes accidentally had no ground transforms, and ground for
  1125. // earlier shapes is handled just above, so...
  1126. if (smReadVersion>23)
  1127. {
  1128. groundTranslations.setSize(numGroundFrames);
  1129. for (i=0;i<numGroundFrames;i++)
  1130. tsalloc.get32((S32*)&groundTranslations[i],3);
  1131. groundRotations.setSize(numGroundFrames);
  1132. for (i=0;i<numGroundFrames;i++)
  1133. tsalloc.get16((S16*)&groundRotations[i],4);
  1134. tsalloc.align32();
  1135. tsalloc.checkGuard();
  1136. }
  1137. // object states
  1138. ptr32 = tsalloc.copyToShape32(numObjectStates*3);
  1139. objectStates.set(ptr32,numObjectStates);
  1140. tsalloc.allocShape32(numSkins*3); // provide buffer after objectStates for older shapes
  1141. tsalloc.checkGuard();
  1142. // DEPRECATED decal states
  1143. ptr32 = tsalloc.getPointer32(numDecalStates);
  1144. tsalloc.checkGuard();
  1145. // frame triggers
  1146. ptr32 = tsalloc.getPointer32(numTriggers*2);
  1147. triggers.setSize(numTriggers);
  1148. dMemcpy(triggers.address(),ptr32,sizeof(S32)*numTriggers*2);
  1149. tsalloc.checkGuard();
  1150. // details
  1151. if ( smReadVersion >= 26 )
  1152. {
  1153. U32 alignedSize32 = sizeof( Detail ) / 4;
  1154. ptr32 = tsalloc.copyToShape32( numDetails * alignedSize32, true );
  1155. details.set( ptr32, numDetails );
  1156. }
  1157. else
  1158. {
  1159. // Previous to version 26 the Detail structure
  1160. // only contained the first 7 values...
  1161. //
  1162. // struct Detail
  1163. // {
  1164. // S32 nameIndex;
  1165. // S32 subShapeNum;
  1166. // S32 objectDetailNum;
  1167. // F32 size;
  1168. // F32 averageError;
  1169. // F32 maxError;
  1170. // S32 polyCount;
  1171. // };
  1172. //
  1173. // In the code below we're reading just these 7 values and
  1174. // copying them to the new larger structure.
  1175. ptr32 = tsalloc.copyToShape32( numDetails * 7, true );
  1176. details.setSize( numDetails );
  1177. for ( U32 detID = 0; detID < details.size(); detID++, ptr32 += 7 )
  1178. {
  1179. Detail *det = &(details[detID]);
  1180. // Clear the struct... we don't want to leave
  1181. // garbage in the parts that are unfilled.
  1182. U32 alignedSize32 = sizeof( Detail );
  1183. dMemset( det, 0, alignedSize32 );
  1184. // Copy the old struct values over.
  1185. dMemcpy( det, ptr32, 7 * 4 );
  1186. // If this is an autobillboard then we need to
  1187. // fill in the new part of the struct.
  1188. if ( det->subShapeNum >= 0 )
  1189. continue;
  1190. S32 lastDetailOpts = det->objectDetailNum;
  1191. det->bbEquatorSteps = lastDetailOpts & 0x7F; // bits 0..6
  1192. det->bbPolarSteps = (lastDetailOpts >> 7) & 0x3F; // bits 7..12
  1193. det->bbPolarAngle = 0.5f * M_PI_F * (1.0f/64.0f) * (F32) (( lastDetailOpts >>13 ) & 0x3F); // bits 13..18
  1194. det->bbDetailLevel = (lastDetailOpts >> 19) & 0x0F; // 19..22
  1195. det->bbDimension = (lastDetailOpts >> 23) & 0xFF; // 23..30
  1196. det->bbIncludePoles = (lastDetailOpts & 0x80000000)!=0; // bit 31
  1197. }
  1198. }
  1199. // Some DTS exporters (MAX - I'm looking at you!) write garbage into the
  1200. // averageError and maxError values which stops LOD from working correctly.
  1201. // Try to detect and fix it
  1202. for ( U32 erID = 0; erID < details.size(); erID++ )
  1203. {
  1204. if ( ( details[erID].averageError == 0 ) || ( details[erID].averageError > 10000 ) ||
  1205. ( details[erID].maxError == 0 ) || ( details[erID].maxError > 10000 ) )
  1206. {
  1207. details[erID].averageError = details[erID].maxError = -1.0f;
  1208. }
  1209. }
  1210. // We don't trust the value of mSmallestVisibleDL loaded from the dts
  1211. // since some legacy meshes seem to have the wrong value. Recalculate it
  1212. // now that we have the details loaded.
  1213. updateSmallestVisibleDL();
  1214. S32 skipDL = getMin(mSmallestVisibleDL,smNumSkipLoadDetails);
  1215. if (skipDL < 0)
  1216. skipDL = 0;
  1217. tsalloc.checkGuard();
  1218. if (TSShape::smReadVersion >= 27)
  1219. {
  1220. // Vertex format is set here
  1221. S8 *vboData = NULL;
  1222. S32 vboSize = 0;
  1223. mBasicVertexFormat.readAlloc(&tsalloc);
  1224. mVertexFormat.clear();
  1225. mBasicVertexFormat.getFormat(mVertexFormat);
  1226. mVertexSize = mVertexFormat.getSizeInBytes();
  1227. AssertFatal(mVertexSize == mBasicVertexFormat.vertexSize, "vertex size mismatch");
  1228. vboSize = tsalloc.get32();
  1229. vboData = tsalloc.getPointer8(vboSize);
  1230. if (tsalloc.getBuffer() && vboSize > 0)
  1231. {
  1232. U8 *vertexData = (U8*)dMalloc_aligned(vboSize, 16);
  1233. dMemcpy(vertexData, vboData, vboSize);
  1234. mShapeVertexData.set(vertexData, vboSize);
  1235. mShapeVertexData.vertexDataReady = true;
  1236. }
  1237. else
  1238. {
  1239. mShapeVertexData.set(NULL, 0);
  1240. }
  1241. }
  1242. else
  1243. {
  1244. mShapeVertexData.set(NULL, 0);
  1245. }
  1246. // about to read in the meshes...first must allocate some scratch space
  1247. S32 scratchSize = getMax(numSkins,numMeshes);
  1248. TSMesh::smVertsList.setSize(scratchSize);
  1249. TSMesh::smTVertsList.setSize(scratchSize);
  1250. if ( smReadVersion >= 26 )
  1251. {
  1252. TSMesh::smTVerts2List.setSize(scratchSize);
  1253. TSMesh::smColorsList.setSize(scratchSize);
  1254. }
  1255. TSMesh::smNormsList.setSize(scratchSize);
  1256. TSMesh::smEncodedNormsList.setSize(scratchSize);
  1257. TSMesh::smDataCopied.setSize(scratchSize);
  1258. TSSkinMesh::smInitTransformList.setSize(scratchSize);
  1259. TSSkinMesh::smVertexIndexList.setSize(scratchSize);
  1260. TSSkinMesh::smBoneIndexList.setSize(scratchSize);
  1261. TSSkinMesh::smWeightList.setSize(scratchSize);
  1262. TSSkinMesh::smNodeIndexList.setSize(scratchSize);
  1263. for (i=0; i<numMeshes; i++)
  1264. {
  1265. TSMesh::smVertsList[i]=NULL;
  1266. TSMesh::smTVertsList[i]=NULL;
  1267. if ( smReadVersion >= 26 )
  1268. {
  1269. TSMesh::smTVerts2List[i] = NULL;
  1270. TSMesh::smColorsList[i] = NULL;
  1271. }
  1272. TSMesh::smNormsList[i]=NULL;
  1273. TSMesh::smEncodedNormsList[i]=NULL;
  1274. TSMesh::smDataCopied[i]=false;
  1275. TSSkinMesh::smInitTransformList[i] = NULL;
  1276. TSSkinMesh::smVertexIndexList[i] = NULL;
  1277. TSSkinMesh::smBoneIndexList[i] = NULL;
  1278. TSSkinMesh::smWeightList[i] = NULL;
  1279. TSSkinMesh::smNodeIndexList[i] = NULL;
  1280. }
  1281. // read in the meshes (sans skins)...straightforward read one at a time
  1282. TSMesh **ptrmesh = (TSMesh**)tsalloc.allocShape32((numMeshes + numSkins*numDetails) * (sizeof(TSMesh*) / 4));
  1283. S32 curObject = 0; // for tracking skipped meshes
  1284. for (i=0; i<numMeshes; i++)
  1285. {
  1286. bool skip = checkSkip(i,curObject,skipDL); // skip this mesh?
  1287. S32 meshType = tsalloc.get32();
  1288. if (meshType == TSMesh::DecalMeshType)
  1289. // decal mesh deprecated
  1290. skip = true;
  1291. TSMesh * mesh = TSMesh::assembleMesh(meshType,skip);
  1292. if (ptrmesh)
  1293. {
  1294. ptrmesh[i] = skip ? 0 : mesh;
  1295. }
  1296. // fill in location of verts, tverts, and normals for detail levels
  1297. if (mesh && meshType!=TSMesh::DecalMeshType)
  1298. {
  1299. TSMesh::smVertsList[i] = mesh->mVerts.address();
  1300. TSMesh::smTVertsList[i] = mesh->mTverts.address();
  1301. if (smReadVersion >= 26)
  1302. {
  1303. TSMesh::smTVerts2List[i] = mesh->mTverts2.address();
  1304. TSMesh::smColorsList[i] = mesh->mColors.address();
  1305. }
  1306. TSMesh::smNormsList[i] = mesh->mNorms.address();
  1307. TSMesh::smEncodedNormsList[i] = mesh->mEncodedNorms.address();
  1308. TSMesh::smDataCopied[i] = !skip; // as long as we didn't skip this mesh, the data should be in shape now
  1309. if (meshType==TSMesh::SkinMeshType)
  1310. {
  1311. TSSkinMesh * skin = (TSSkinMesh*)mesh;
  1312. TSMesh::smVertsList[i] = skin->batchData.initialVerts.address();
  1313. TSMesh::smNormsList[i] = skin->batchData.initialNorms.address();
  1314. TSSkinMesh::smInitTransformList[i] = skin->batchData.initialTransforms.address();
  1315. TSSkinMesh::smVertexIndexList[i] = skin->vertexIndex.address();
  1316. TSSkinMesh::smBoneIndexList[i] = skin->boneIndex.address();
  1317. TSSkinMesh::smWeightList[i] = skin->weight.address();
  1318. TSSkinMesh::smNodeIndexList[i] = skin->batchData.nodeIndex.address();
  1319. }
  1320. }
  1321. }
  1322. meshes.set(ptrmesh, numMeshes);
  1323. tsalloc.checkGuard();
  1324. // names
  1325. char * nameBufferStart = (char*)tsalloc.getPointer8(0);
  1326. char * name = nameBufferStart;
  1327. S32 nameBufferSize = 0;
  1328. names.setSize(numNames);
  1329. for (i=0; i<numNames; i++)
  1330. {
  1331. for (j=0; name[j]; j++)
  1332. ;
  1333. names[i] = name;
  1334. nameBufferSize += j + 1;
  1335. name += j + 1;
  1336. }
  1337. tsalloc.getPointer8(nameBufferSize);
  1338. tsalloc.align32();
  1339. tsalloc.checkGuard();
  1340. if (smReadVersion<23)
  1341. {
  1342. // get detail information about skins...
  1343. S32 * detFirstSkin = tsalloc.getPointer32(numDetails);
  1344. S32 * detailNumSkins = tsalloc.getPointer32(numDetails);
  1345. tsalloc.checkGuard();
  1346. // about to read in skins...clear out scratch space...
  1347. if (numSkins)
  1348. {
  1349. TSSkinMesh::smInitTransformList.setSize(numSkins);
  1350. TSSkinMesh::smVertexIndexList.setSize(numSkins);
  1351. TSSkinMesh::smBoneIndexList.setSize(numSkins);
  1352. TSSkinMesh::smWeightList.setSize(numSkins);
  1353. TSSkinMesh::smNodeIndexList.setSize(numSkins);
  1354. }
  1355. for (i=0; i<numSkins; i++)
  1356. {
  1357. TSMesh::smVertsList[i]=NULL;
  1358. TSMesh::smTVertsList[i]=NULL;
  1359. TSMesh::smNormsList[i]=NULL;
  1360. TSMesh::smEncodedNormsList[i]=NULL;
  1361. TSMesh::smDataCopied[i]=false;
  1362. TSSkinMesh::smInitTransformList[i] = NULL;
  1363. TSSkinMesh::smVertexIndexList[i] = NULL;
  1364. TSSkinMesh::smBoneIndexList[i] = NULL;
  1365. TSSkinMesh::smWeightList[i] = NULL;
  1366. TSSkinMesh::smNodeIndexList[i] = NULL;
  1367. }
  1368. // skins
  1369. ptr32 = tsalloc.allocShape32(numSkins);
  1370. for (i=0; i<numSkins; i++)
  1371. {
  1372. bool skip = i<detFirstSkin[skipDL];
  1373. TSSkinMesh * skin = (TSSkinMesh*)TSMesh::assembleMesh(TSMesh::SkinMeshType,skip);
  1374. if (meshes.address())
  1375. {
  1376. // add pointer to skin in shapes list of meshes
  1377. // we reserved room for this above...
  1378. meshes.set(meshes.address(),meshes.size()+1);
  1379. meshes[meshes.size()-1] = skip ? NULL : skin;
  1380. }
  1381. // fill in location of verts, tverts, and normals for shared detail levels
  1382. if (skin)
  1383. {
  1384. TSMesh::smVertsList[i] = skin->batchData.initialVerts.address();
  1385. TSMesh::smTVertsList[i] = skin->mTverts.address();
  1386. TSMesh::smNormsList[i] = skin->batchData.initialNorms.address();
  1387. TSMesh::smEncodedNormsList[i] = skin->mEncodedNorms.address();
  1388. TSMesh::smDataCopied[i] = !skip; // as long as we didn't skip this mesh, the data should be in shape now
  1389. TSSkinMesh::smInitTransformList[i] = skin->batchData.initialTransforms.address();
  1390. TSSkinMesh::smVertexIndexList[i] = skin->vertexIndex.address();
  1391. TSSkinMesh::smBoneIndexList[i] = skin->boneIndex.address();
  1392. TSSkinMesh::smWeightList[i] = skin->weight.address();
  1393. TSSkinMesh::smNodeIndexList[i] = skin->batchData.nodeIndex.address();
  1394. }
  1395. }
  1396. tsalloc.checkGuard();
  1397. // we now have skins in mesh list...add skin objects to object list and patch things up
  1398. fixupOldSkins(numMeshes,numSkins,numDetails,detFirstSkin,detailNumSkins);
  1399. }
  1400. // allocate storage space for some arrays (filled in during Shape::init)...
  1401. ptr32 = tsalloc.allocShape32(numDetails);
  1402. alphaIn.set(ptr32,numDetails);
  1403. ptr32 = tsalloc.allocShape32(numDetails);
  1404. alphaOut.set(ptr32,numDetails);
  1405. }
  1406. void TSShape::disassembleShape()
  1407. {
  1408. S32 i;
  1409. // set counts...
  1410. S32 numNodes = tsalloc.set32(nodes.size());
  1411. S32 numObjects = tsalloc.set32(objects.size());
  1412. tsalloc.set32(0); // DEPRECATED decals
  1413. S32 numSubShapes = tsalloc.set32(subShapeFirstNode.size());
  1414. tsalloc.set32(0); // DEPRECATED ifl materials
  1415. S32 numNodeRotations = tsalloc.set32(nodeRotations.size());
  1416. S32 numNodeTranslations = tsalloc.set32(nodeTranslations.size());
  1417. S32 numNodeUniformScales = tsalloc.set32(nodeUniformScales.size());
  1418. S32 numNodeAlignedScales = tsalloc.set32(nodeAlignedScales.size());
  1419. S32 numNodeArbitraryScales = tsalloc.set32(nodeArbitraryScaleFactors.size());
  1420. S32 numGroundFrames = tsalloc.set32(groundTranslations.size());
  1421. S32 numObjectStates = tsalloc.set32(objectStates.size());
  1422. tsalloc.set32(0); // DEPRECATED decals
  1423. S32 numTriggers = tsalloc.set32(triggers.size());
  1424. S32 numDetails = tsalloc.set32(details.size());
  1425. S32 numMeshes = tsalloc.set32(meshes.size());
  1426. S32 numNames = tsalloc.set32(names.size());
  1427. tsalloc.set32((S32)mSmallestVisibleSize);
  1428. tsalloc.set32(mSmallestVisibleDL);
  1429. tsalloc.setGuard();
  1430. // get bounds...
  1431. tsalloc.copyToBuffer32((S32*)&mRadius,1);
  1432. tsalloc.copyToBuffer32((S32*)&tubeRadius,1);
  1433. tsalloc.copyToBuffer32((S32*)&center,3);
  1434. tsalloc.copyToBuffer32((S32*)&mBounds,6);
  1435. tsalloc.setGuard();
  1436. // copy various vectors...
  1437. tsalloc.copyToBuffer32((S32*)nodes.address(),numNodes*5);
  1438. tsalloc.setGuard();
  1439. tsalloc.copyToBuffer32((S32*)objects.address(),numObjects*6);
  1440. tsalloc.setGuard();
  1441. // DEPRECATED: no copy decals
  1442. tsalloc.setGuard();
  1443. tsalloc.copyToBuffer32(0,0); // DEPRECATED: ifl materials!
  1444. tsalloc.setGuard();
  1445. tsalloc.copyToBuffer32((S32*)subShapeFirstNode.address(),numSubShapes);
  1446. tsalloc.copyToBuffer32((S32*)subShapeFirstObject.address(),numSubShapes);
  1447. tsalloc.copyToBuffer32(0, numSubShapes); // DEPRECATED: no copy subShapeFirstDecal
  1448. tsalloc.setGuard();
  1449. tsalloc.copyToBuffer32((S32*)subShapeNumNodes.address(),numSubShapes);
  1450. tsalloc.copyToBuffer32((S32*)subShapeNumObjects.address(),numSubShapes);
  1451. tsalloc.copyToBuffer32(0, numSubShapes); // DEPRECATED: no copy subShapeNumDecals
  1452. tsalloc.setGuard();
  1453. // default transforms...
  1454. tsalloc.copyToBuffer16((S16*)defaultRotations.address(),numNodes*4);
  1455. tsalloc.copyToBuffer32((S32*)defaultTranslations.address(),numNodes*3);
  1456. // animated transforms...
  1457. tsalloc.copyToBuffer16((S16*)nodeRotations.address(),numNodeRotations*4);
  1458. tsalloc.copyToBuffer32((S32*)nodeTranslations.address(),numNodeTranslations*3);
  1459. tsalloc.setGuard();
  1460. // ...with scale
  1461. tsalloc.copyToBuffer32((S32*)nodeUniformScales.address(),numNodeUniformScales);
  1462. tsalloc.copyToBuffer32((S32*)nodeAlignedScales.address(),numNodeAlignedScales*3);
  1463. tsalloc.copyToBuffer32((S32*)nodeArbitraryScaleFactors.address(),numNodeArbitraryScales*3);
  1464. tsalloc.copyToBuffer16((S16*)nodeArbitraryScaleRots.address(),numNodeArbitraryScales*4);
  1465. tsalloc.setGuard();
  1466. tsalloc.copyToBuffer32((S32*)groundTranslations.address(),3*numGroundFrames);
  1467. tsalloc.copyToBuffer16((S16*)groundRotations.address(),4*numGroundFrames);
  1468. tsalloc.setGuard();
  1469. // object states..
  1470. tsalloc.copyToBuffer32((S32*)objectStates.address(),numObjectStates*3);
  1471. tsalloc.setGuard();
  1472. // decal states...
  1473. // DEPRECATED (numDecalStates = 0)
  1474. tsalloc.setGuard();
  1475. // frame triggers
  1476. tsalloc.copyToBuffer32((S32*)triggers.address(),numTriggers*2);
  1477. tsalloc.setGuard();
  1478. // details
  1479. if (TSShape::smVersion > 25)
  1480. {
  1481. U32 alignedSize32 = sizeof( Detail ) / 4;
  1482. tsalloc.copyToBuffer32((S32*)details.address(),numDetails * alignedSize32 );
  1483. }
  1484. else
  1485. {
  1486. // Legacy details => no explicit autobillboard parameters
  1487. U32 legacyDetailSize32 = 7; // only store the first 7 4-byte values of each detail
  1488. for ( S32 bbID = 0; bbID < details.size(); bbID++ )
  1489. tsalloc.copyToBuffer32( (S32*)&details[bbID], legacyDetailSize32 );
  1490. }
  1491. tsalloc.setGuard();
  1492. if (TSShape::smVersion >= 27)
  1493. {
  1494. // Vertex format now included with mesh data. Note this doesn't include index data which
  1495. // is constructed directly in the buffer from the meshes
  1496. mBasicVertexFormat.writeAlloc(&tsalloc);
  1497. tsalloc.set32(mShapeVertexData.size);
  1498. tsalloc.copyToBuffer8((S8*)mShapeVertexData.base, mShapeVertexData.size);
  1499. }
  1500. // read in the meshes (sans skins)...
  1501. bool * isMesh = new bool[numMeshes]; // funny business because decals are pretend meshes (legacy issue)
  1502. for (i=0;i<numMeshes;i++)
  1503. isMesh[i]=false;
  1504. for (i=0; i<objects.size(); i++)
  1505. {
  1506. for (S32 j=0; j<objects[i].numMeshes; j++)
  1507. // even if an empty mesh, it's a mesh...
  1508. isMesh[objects[i].startMeshIndex+j]=true;
  1509. }
  1510. for (i=0; i<numMeshes; i++)
  1511. {
  1512. TSMesh * mesh = NULL;
  1513. // decal mesh deprecated
  1514. if (isMesh[i])
  1515. mesh = meshes[i];
  1516. tsalloc.set32( (mesh && mesh->getMeshType() != TSMesh::DecalMeshType) ? mesh->getMeshType() : TSMesh::NullMeshType);
  1517. if (mesh)
  1518. mesh->disassemble();
  1519. }
  1520. delete [] isMesh;
  1521. tsalloc.setGuard();
  1522. // names
  1523. for (i=0; i<numNames; i++)
  1524. tsalloc.copyToBuffer8((S8 *)(names[i].c_str()),names[i].length()+1);
  1525. tsalloc.setGuard();
  1526. }
  1527. //-------------------------------------------------
  1528. // write whole shape
  1529. //-------------------------------------------------
  1530. /** Determine whether we can write this shape in TSTPRO compatible format */
  1531. bool TSShape::canWriteOldFormat() const
  1532. {
  1533. // Cannot use old format if using autobillboard details
  1534. for (S32 i = 0; i < details.size(); i++)
  1535. {
  1536. if (details[i].subShapeNum < 0)
  1537. return false;
  1538. }
  1539. for (S32 i = 0; i < meshes.size(); i++)
  1540. {
  1541. if (!meshes[i])
  1542. continue;
  1543. // Cannot use old format if using the new functionality (COLORs, 2nd UV set)
  1544. if (meshes[i]->mTverts2.size() || meshes[i]->mColors.size())
  1545. return false;
  1546. // Cannot use old format if any primitive has too many triangles
  1547. // (ie. cannot fit in a S16)
  1548. for (S32 j = 0; j < meshes[i]->mPrimitives.size(); j++)
  1549. {
  1550. if ((meshes[i]->mPrimitives[j].start +
  1551. meshes[i]->mPrimitives[j].numElements) >= (1 << 15))
  1552. {
  1553. return false;
  1554. }
  1555. }
  1556. }
  1557. return true;
  1558. }
  1559. void TSShape::write(Stream * s, bool saveOldFormat)
  1560. {
  1561. S32 currentVersion = smVersion;
  1562. if (saveOldFormat)
  1563. smVersion = 24;
  1564. // write version
  1565. s->write(smVersion | (mExporterVersion<<16));
  1566. tsalloc.setWrite();
  1567. disassembleShape();
  1568. S32 * buffer32 = tsalloc.getBuffer32();
  1569. S16 * buffer16 = tsalloc.getBuffer16();
  1570. S8 * buffer8 = tsalloc.getBuffer8();
  1571. S32 size32 = tsalloc.getBufferSize32();
  1572. S32 size16 = tsalloc.getBufferSize16();
  1573. S32 size8 = tsalloc.getBufferSize8();
  1574. // convert sizes to dwords...
  1575. if (size16 & 1)
  1576. size16 += 2;
  1577. size16 >>= 1;
  1578. if (size8 & 3)
  1579. size8 += 4;
  1580. size8 >>= 2;
  1581. S32 sizeMemBuffer, start16, start8;
  1582. sizeMemBuffer = size32 + size16 + size8;
  1583. start16 = size32;
  1584. start8 = start16+size16;
  1585. // in dwords -- write will properly endian-flip.
  1586. s->write(sizeMemBuffer);
  1587. s->write(start16);
  1588. s->write(start8);
  1589. // endian-flip the entire write buffers.
  1590. fixEndian(buffer32,buffer16,buffer8,size32,size16,size8);
  1591. // now write buffers
  1592. s->write(size32*4,buffer32);
  1593. s->write(size16*4,buffer16);
  1594. s->write(size8 *4,buffer8);
  1595. // write sequences - write will properly endian-flip.
  1596. s->write(sequences.size());
  1597. for (S32 i=0; i<sequences.size(); i++)
  1598. sequences[i].write(s);
  1599. // write material list - write will properly endian-flip.
  1600. materialList->write(*s);
  1601. delete [] buffer32;
  1602. delete [] buffer16;
  1603. delete [] buffer8;
  1604. smVersion = currentVersion;
  1605. }
  1606. //-------------------------------------------------
  1607. // read whole shape
  1608. //-------------------------------------------------
  1609. bool TSShape::read(Stream * s)
  1610. {
  1611. // read version - read handles endian-flip
  1612. s->read(&smReadVersion);
  1613. mExporterVersion = smReadVersion >> 16;
  1614. smReadVersion &= 0xFF;
  1615. if (smReadVersion>smVersion)
  1616. {
  1617. // error -- don't support future versions yet :>
  1618. Con::errorf(ConsoleLogEntry::General,
  1619. "Error: attempt to load a version %i dts-shape, can currently only load version %i and before.",
  1620. smReadVersion,smVersion);
  1621. return false;
  1622. }
  1623. mReadVersion = smReadVersion;
  1624. S32 * memBuffer32;
  1625. S16 * memBuffer16;
  1626. S8 * memBuffer8;
  1627. S32 count32, count16, count8;
  1628. if (mReadVersion<19)
  1629. {
  1630. Con::errorf("... Shape with old version.");
  1631. return false;
  1632. }
  1633. else
  1634. {
  1635. S32 i;
  1636. U32 sizeMemBuffer, startU16, startU8;
  1637. // in dwords. - read handles endian-flip
  1638. s->read(&sizeMemBuffer);
  1639. s->read(&startU16);
  1640. s->read(&startU8);
  1641. if (s->getStatus()!=Stream::Ok)
  1642. {
  1643. Con::errorf(ConsoleLogEntry::General, "Error: bad shape file.");
  1644. return false;
  1645. }
  1646. S32 * tmp = new S32[sizeMemBuffer];
  1647. s->read(sizeof(S32)*sizeMemBuffer,(U8*)tmp);
  1648. memBuffer32 = tmp;
  1649. memBuffer16 = (S16*)(tmp+startU16);
  1650. memBuffer8 = (S8*)(tmp+startU8);
  1651. count32 = startU16;
  1652. count16 = startU8-startU16;
  1653. count8 = sizeMemBuffer-startU8;
  1654. // read sequences
  1655. S32 numSequences;
  1656. s->read(&numSequences);
  1657. sequences.setSize(numSequences);
  1658. for (i=0; i<numSequences; i++)
  1659. {
  1660. sequences[i].read(s);
  1661. // Store initial (empty) source data
  1662. sequences[i].sourceData.total = sequences[i].numKeyframes;
  1663. sequences[i].sourceData.end = sequences[i].sourceData.total - 1;
  1664. }
  1665. // read material list
  1666. delete materialList; // just in case...
  1667. materialList = new TSMaterialList;
  1668. materialList->read(*s);
  1669. }
  1670. // since we read in the buffers, we need to endian-flip their entire contents...
  1671. fixEndian(memBuffer32,memBuffer16,memBuffer8,count32,count16,count8);
  1672. tsalloc.setRead(memBuffer32,memBuffer16,memBuffer8,true);
  1673. assembleShape(); // determine size of buffer needed
  1674. mShapeDataSize = tsalloc.getSize();
  1675. tsalloc.doAlloc();
  1676. mShapeData = tsalloc.getBuffer();
  1677. tsalloc.setRead(memBuffer32,memBuffer16,memBuffer8,false);
  1678. assembleShape(); // copy to buffer
  1679. AssertFatal(tsalloc.getSize()==mShapeDataSize,"TSShape::read: shape data buffer size mis-calculated");
  1680. delete [] memBuffer32;
  1681. if (smInitOnRead)
  1682. {
  1683. init();
  1684. }
  1685. return true;
  1686. }
  1687. void TSShape::createEmptyShape()
  1688. {
  1689. nodes.set(dMalloc(1 * sizeof(Node)), 1);
  1690. nodes[0].nameIndex = 1;
  1691. nodes[0].parentIndex = -1;
  1692. nodes[0].firstObject = 0;
  1693. nodes[0].firstChild = -1;
  1694. nodes[0].nextSibling = -1;
  1695. objects.set(dMalloc(1 * sizeof(Object)), 1);
  1696. objects[0].nameIndex = 2;
  1697. objects[0].numMeshes = 1;
  1698. objects[0].startMeshIndex = 0;
  1699. objects[0].nodeIndex = 0;
  1700. objects[0].nextSibling = -1;
  1701. objects[0].firstDecal = -1;
  1702. objectStates.set(dMalloc(1 * sizeof(ObjectState)), 1);
  1703. objectStates[0].vis = 1;
  1704. objectStates[0].frameIndex = 0;
  1705. objectStates[0].matFrameIndex = 0;
  1706. subShapeFirstNode.set(dMalloc(1 * sizeof(S32)), 1);
  1707. subShapeFirstNode[0] = 0;
  1708. subShapeFirstObject.set(dMalloc(1 * sizeof(S32)), 1);
  1709. subShapeFirstObject[0] = 0;
  1710. detailFirstSkin.set(NULL, 0);
  1711. subShapeNumNodes.set(dMalloc(1 * sizeof(S32)), 1);
  1712. subShapeNumNodes[0] = 1;
  1713. subShapeNumObjects.set(dMalloc(1 * sizeof(S32)), 1);
  1714. subShapeNumObjects[0] = 1;
  1715. details.set(dMalloc(1 * sizeof(Detail)), 1);
  1716. details[0].nameIndex = 0;
  1717. details[0].subShapeNum = 0;
  1718. details[0].objectDetailNum = 0;
  1719. details[0].size = 2.0f;
  1720. details[0].averageError = -1.0f;
  1721. details[0].maxError = -1.0f;
  1722. details[0].polyCount = 0;
  1723. defaultRotations.set(dMalloc(1 * sizeof(Quat16)), 1);
  1724. defaultRotations[0].x = 0.0f;
  1725. defaultRotations[0].y = 0.0f;
  1726. defaultRotations[0].z = 0.0f;
  1727. defaultRotations[0].w = 0.0f;
  1728. defaultTranslations.set(dMalloc(1 * sizeof(Point3F)), 1);
  1729. defaultTranslations[0].set(0.0f, 0.0f, 0.0f);
  1730. subShapeFirstTranslucentObject.set(dMalloc(1 * sizeof(S32)), 1);
  1731. subShapeFirstTranslucentObject[0] = 1;
  1732. alphaIn.set(dMalloc(1 * sizeof(F32)), 1);
  1733. alphaIn[0] = 0;
  1734. alphaOut.set(dMalloc(1 * sizeof(F32)), 1);
  1735. alphaOut[0] = -1;
  1736. sequences.set(NULL, 0);
  1737. nodeRotations.set(NULL, 0);
  1738. nodeTranslations.set(NULL, 0);
  1739. nodeUniformScales.set(NULL, 0);
  1740. nodeAlignedScales.set(NULL, 0);
  1741. nodeArbitraryScaleRots.set(NULL, 0);
  1742. nodeArbitraryScaleFactors.set(NULL, 0);
  1743. groundRotations.set(NULL, 0);
  1744. groundTranslations.set(NULL, 0);
  1745. triggers.set(NULL, 0);
  1746. billboardDetails.set(NULL, 0);
  1747. names.setSize(3);
  1748. names[0] = StringTable->insert("Detail2");
  1749. names[1] = StringTable->insert("Mesh2");
  1750. names[2] = StringTable->insert("Mesh");
  1751. mRadius = 0.866025f;
  1752. tubeRadius = 0.707107f;
  1753. center.set(0.0f, 0.5f, 0.0f);
  1754. mBounds.minExtents.set(-0.5f, 0.0f, -0.5f);
  1755. mBounds.maxExtents.set(0.5f, 1.0f, 0.5f);
  1756. mExporterVersion = 124;
  1757. mSmallestVisibleSize = 2;
  1758. mSmallestVisibleDL = 0;
  1759. mReadVersion = 24;
  1760. mFlags = 0;
  1761. mSequencesConstructed = 0;
  1762. mUseDetailFromScreenError = false;
  1763. mDetailLevelLookup.setSize( 1 );
  1764. mDetailLevelLookup[0].set( -1, 0 );
  1765. // Init the collision accelerator array. Note that we don't compute the
  1766. // accelerators until the app requests them
  1767. detailCollisionAccelerators.setSize(details.size());
  1768. for (U32 i = 0; i < detailCollisionAccelerators.size(); i++)
  1769. detailCollisionAccelerators[i] = NULL;
  1770. }
  1771. void TSShape::fixEndian(S32 * buff32, S16 * buff16, S8 *, S32 count32, S32 count16, S32)
  1772. {
  1773. // if endian-ness isn't the same, need to flip the buffer contents.
  1774. if (0x12345678!=convertLEndianToHost(0x12345678))
  1775. {
  1776. for (S32 i=0; i<count32; i++)
  1777. buff32[i]=convertLEndianToHost(buff32[i]);
  1778. for (S32 i=0; i<count16*2; i++)
  1779. buff16[i]=convertLEndianToHost(buff16[i]);
  1780. }
  1781. }
  1782. template<> void *Resource<TSShape>::create(const Torque::Path &path)
  1783. {
  1784. // Execute the shape script if it exists
  1785. Torque::Path scriptPath(path);
  1786. scriptPath.setExtension("cs");
  1787. // Don't execute the script if we're already doing so!
  1788. StringTableEntry currentScript = Platform::stripBasePath(CodeBlock::getCurrentCodeBlockFullPath());
  1789. if (!scriptPath.getFullPath().equal(currentScript))
  1790. {
  1791. Torque::Path scriptPathDSO(scriptPath);
  1792. scriptPathDSO.setExtension("cs.dso");
  1793. if (Torque::FS::IsFile(scriptPathDSO) || Torque::FS::IsFile(scriptPath))
  1794. {
  1795. String evalCmd = "exec(\"" + scriptPath + "\");";
  1796. String instantGroup = Con::getVariable("InstantGroup");
  1797. Con::setIntVariable("InstantGroup", RootGroupId);
  1798. Con::evaluate((const char*)evalCmd.c_str(), false, scriptPath.getFullPath());
  1799. Con::setVariable("InstantGroup", instantGroup.c_str());
  1800. }
  1801. }
  1802. // Attempt to load the shape
  1803. TSShape * ret = 0;
  1804. bool readSuccess = false;
  1805. const String extension = path.getExtension();
  1806. if ( extension.equal( "dts", String::NoCase ) )
  1807. {
  1808. FileStream stream;
  1809. stream.open( path.getFullPath(), Torque::FS::File::Read );
  1810. if ( stream.getStatus() != Stream::Ok )
  1811. {
  1812. Con::errorf( "Resource<TSShape>::create - Could not open '%s'", path.getFullPath().c_str() );
  1813. return NULL;
  1814. }
  1815. ret = new TSShape;
  1816. readSuccess = ret->read(&stream);
  1817. }
  1818. else if ( extension.equal( "dae", String::NoCase ) || extension.equal( "kmz", String::NoCase ) )
  1819. {
  1820. #ifdef TORQUE_COLLADA
  1821. // Attempt to load the DAE file
  1822. ret = loadColladaShape(path);
  1823. readSuccess = (ret != NULL);
  1824. #else
  1825. // No COLLADA support => attempt to load the cached DTS file instead
  1826. Torque::Path cachedPath = path;
  1827. cachedPath.setExtension("cached.dts");
  1828. FileStream stream;
  1829. stream.open( cachedPath.getFullPath(), Torque::FS::File::Read );
  1830. if ( stream.getStatus() != Stream::Ok )
  1831. {
  1832. Con::errorf( "Resource<TSShape>::create - Could not open '%s'", cachedPath.getFullPath().c_str() );
  1833. return NULL;
  1834. }
  1835. ret = new TSShape;
  1836. readSuccess = ret->read(&stream);
  1837. #endif
  1838. }
  1839. else
  1840. {
  1841. //Con::errorf( "Resource<TSShape>::create - '%s' has an unknown file format", path.getFullPath().c_str() );
  1842. //delete ret;
  1843. //return NULL;
  1844. // andrewmac: Open Asset Import Library
  1845. #ifdef TORQUE_ASSIMP
  1846. ret = assimpLoadShape(path);
  1847. readSuccess = (ret != NULL);
  1848. #endif
  1849. // andrewmac : I could have used another conditional macro but I think this is suffice:
  1850. if (!readSuccess)
  1851. {
  1852. Con::errorf("Resource<TSShape>::create - '%s' has an unknown file format", path.getFullPath().c_str());
  1853. delete ret;
  1854. return NULL;
  1855. }
  1856. }
  1857. if( !readSuccess )
  1858. {
  1859. Con::errorf( "Resource<TSShape>::create - Error reading '%s'", path.getFullPath().c_str() );
  1860. delete ret;
  1861. ret = NULL;
  1862. }
  1863. return ret;
  1864. }
  1865. template<> ResourceBase::Signature Resource<TSShape>::signature()
  1866. {
  1867. return MakeFourCC('t','s','s','h');
  1868. }
  1869. TSShape::ConvexHullAccelerator* TSShape::getAccelerator(S32 dl)
  1870. {
  1871. AssertFatal(dl < details.size(), "Error, bad detail level!");
  1872. if (dl == -1)
  1873. return NULL;
  1874. AssertFatal( detailCollisionAccelerators.size() == details.size(),
  1875. "TSShape::getAccelerator() - mismatched array sizes!" );
  1876. if (detailCollisionAccelerators[dl] == NULL)
  1877. computeAccelerator(dl);
  1878. AssertFatal(detailCollisionAccelerators[dl] != NULL, "This should be non-null after computing it!");
  1879. return detailCollisionAccelerators[dl];
  1880. }
  1881. void TSShape::computeAccelerator(S32 dl)
  1882. {
  1883. AssertFatal(dl < details.size(), "Error, bad detail level!");
  1884. // Have we already computed this?
  1885. if (detailCollisionAccelerators[dl] != NULL)
  1886. return;
  1887. // Create a bogus features list...
  1888. ConvexFeature cf;
  1889. MatrixF mat(true);
  1890. Point3F n(0, 0, 1);
  1891. const TSDetail* detail = &details[dl];
  1892. S32 ss = detail->subShapeNum;
  1893. S32 od = detail->objectDetailNum;
  1894. S32 start = subShapeFirstObject[ss];
  1895. S32 end = subShapeNumObjects[ss] + start;
  1896. if (start < end)
  1897. {
  1898. // run through objects and collide
  1899. // DMMNOTE: This assumes that the transform of the collision hulls is
  1900. // identity...
  1901. U32 surfaceKey = 0;
  1902. for (S32 i = start; i < end; i++)
  1903. {
  1904. const TSObject* obj = &objects[i];
  1905. if (obj->numMeshes && od < obj->numMeshes) {
  1906. TSMesh* mesh = meshes[obj->startMeshIndex + od];
  1907. if (mesh)
  1908. mesh->getFeatures(0, mat, n, &cf, surfaceKey);
  1909. }
  1910. }
  1911. }
  1912. Vector<Point3F> fixedVerts;
  1913. VECTOR_SET_ASSOCIATION(fixedVerts);
  1914. S32 i;
  1915. for (i = 0; i < cf.mVertexList.size(); i++) {
  1916. S32 j;
  1917. bool found = false;
  1918. for (j = 0; j < cf.mFaceList.size(); j++) {
  1919. if (cf.mFaceList[j].vertex[0] == i ||
  1920. cf.mFaceList[j].vertex[1] == i ||
  1921. cf.mFaceList[j].vertex[2] == i) {
  1922. found = true;
  1923. break;
  1924. }
  1925. }
  1926. if (!found)
  1927. continue;
  1928. found = false;
  1929. for (j = 0; j < fixedVerts.size(); j++) {
  1930. if (fixedVerts[j] == cf.mVertexList[i]) {
  1931. found = true;
  1932. break;
  1933. }
  1934. }
  1935. if (found == true) {
  1936. // Ok, need to replace any references to vertex i in the facelists with
  1937. // a reference to vertex j in the fixed list
  1938. for (S32 k = 0; k < cf.mFaceList.size(); k++) {
  1939. for (S32 l = 0; l < 3; l++) {
  1940. if (cf.mFaceList[k].vertex[l] == i)
  1941. cf.mFaceList[k].vertex[l] = j;
  1942. }
  1943. }
  1944. } else {
  1945. for (S32 k = 0; k < cf.mFaceList.size(); k++) {
  1946. for (S32 l = 0; l < 3; l++) {
  1947. if (cf.mFaceList[k].vertex[l] == i)
  1948. cf.mFaceList[k].vertex[l] = fixedVerts.size();
  1949. }
  1950. }
  1951. fixedVerts.push_back(cf.mVertexList[i]);
  1952. }
  1953. }
  1954. cf.mVertexList.setSize(0);
  1955. cf.mVertexList = fixedVerts;
  1956. // Ok, so now we have a vertex list. Lets copy that out...
  1957. ConvexHullAccelerator* accel = new ConvexHullAccelerator;
  1958. detailCollisionAccelerators[dl] = accel;
  1959. accel->numVerts = cf.mVertexList.size();
  1960. accel->vertexList = new Point3F[accel->numVerts];
  1961. dMemcpy(accel->vertexList, cf.mVertexList.address(), sizeof(Point3F) * accel->numVerts);
  1962. accel->normalList = new Point3F[cf.mFaceList.size()];
  1963. for (i = 0; i < cf.mFaceList.size(); i++)
  1964. accel->normalList[i] = cf.mFaceList[i].normal;
  1965. accel->emitStrings = new U8*[accel->numVerts];
  1966. dMemset(accel->emitStrings, 0, sizeof(U8*) * accel->numVerts);
  1967. for (i = 0; i < accel->numVerts; i++) {
  1968. S32 j;
  1969. Vector<U32> faces;
  1970. VECTOR_SET_ASSOCIATION(faces);
  1971. for (j = 0; j < cf.mFaceList.size(); j++) {
  1972. if (cf.mFaceList[j].vertex[0] == i ||
  1973. cf.mFaceList[j].vertex[1] == i ||
  1974. cf.mFaceList[j].vertex[2] == i) {
  1975. faces.push_back(j);
  1976. }
  1977. }
  1978. AssertFatal(faces.size() != 0, "Huh? Vertex unreferenced by any faces");
  1979. // Insert all faces that didn't make the first cut, but share a plane with
  1980. // a face that's on the short list.
  1981. for (j = 0; j < cf.mFaceList.size(); j++) {
  1982. bool found = false;
  1983. S32 k;
  1984. for (k = 0; k < faces.size(); k++) {
  1985. if (faces[k] == j)
  1986. found = true;
  1987. }
  1988. if (found)
  1989. continue;
  1990. found = false;
  1991. for (k = 0; k < faces.size(); k++) {
  1992. if (mDot(accel->normalList[faces[k]], accel->normalList[j]) > 0.999) {
  1993. found = true;
  1994. break;
  1995. }
  1996. }
  1997. if (found)
  1998. faces.push_back(j);
  1999. }
  2000. Vector<U32> vertRemaps;
  2001. VECTOR_SET_ASSOCIATION(vertRemaps);
  2002. for (j = 0; j < faces.size(); j++) {
  2003. for (U32 k = 0; k < 3; k++) {
  2004. U32 insert = cf.mFaceList[faces[j]].vertex[k];
  2005. bool found = false;
  2006. for (S32 l = 0; l < vertRemaps.size(); l++) {
  2007. if (insert == vertRemaps[l]) {
  2008. found = true;
  2009. break;
  2010. }
  2011. }
  2012. if (!found)
  2013. vertRemaps.push_back(insert);
  2014. }
  2015. }
  2016. Vector<Point2I> edges;
  2017. VECTOR_SET_ASSOCIATION(edges);
  2018. for (j = 0; j < faces.size(); j++) {
  2019. for (U32 k = 0; k < 3; k++) {
  2020. U32 edgeStart = cf.mFaceList[faces[j]].vertex[(k + 0) % 3];
  2021. U32 edgeEnd = cf.mFaceList[faces[j]].vertex[(k + 1) % 3];
  2022. U32 e0 = getMin(edgeStart, edgeEnd);
  2023. U32 e1 = getMax(edgeStart, edgeEnd);
  2024. bool found = false;
  2025. for (S32 l = 0; l < edges.size(); l++) {
  2026. if (edges[l].x == e0 && edges[l].y == e1) {
  2027. found = true;
  2028. break;
  2029. }
  2030. }
  2031. if (!found)
  2032. edges.push_back(Point2I(e0, e1));
  2033. }
  2034. }
  2035. //AssertFatal(vertRemaps.size() < 256 && faces.size() < 256 && edges.size() < 256,
  2036. // "Error, ran over the shapebase assumptions about convex hulls.");
  2037. U32 emitStringLen = 1 + vertRemaps.size() +
  2038. 1 + (edges.size() * 2) +
  2039. 1 + (faces.size() * 4);
  2040. accel->emitStrings[i] = new U8[emitStringLen];
  2041. U32 currPos = 0;
  2042. accel->emitStrings[i][currPos++] = vertRemaps.size();
  2043. for (j = 0; j < vertRemaps.size(); j++)
  2044. accel->emitStrings[i][currPos++] = vertRemaps[j];
  2045. accel->emitStrings[i][currPos++] = edges.size();
  2046. for (j = 0; j < edges.size(); j++) {
  2047. S32 l;
  2048. U32 old = edges[j].x;
  2049. bool found = false;
  2050. for (l = 0; l < vertRemaps.size(); l++) {
  2051. if (vertRemaps[l] == old) {
  2052. found = true;
  2053. accel->emitStrings[i][currPos++] = l;
  2054. break;
  2055. }
  2056. }
  2057. AssertFatal(found, "Error, couldn't find the remap!");
  2058. old = edges[j].y;
  2059. found = false;
  2060. for (l = 0; l < vertRemaps.size(); l++) {
  2061. if (vertRemaps[l] == old) {
  2062. found = true;
  2063. accel->emitStrings[i][currPos++] = l;
  2064. break;
  2065. }
  2066. }
  2067. AssertFatal(found, "Error, couldn't find the remap!");
  2068. }
  2069. accel->emitStrings[i][currPos++] = faces.size();
  2070. for (j = 0; j < faces.size(); j++) {
  2071. accel->emitStrings[i][currPos++] = faces[j];
  2072. for (U32 k = 0; k < 3; k++) {
  2073. U32 old = cf.mFaceList[faces[j]].vertex[k];
  2074. bool found = false;
  2075. for (S32 l = 0; l < vertRemaps.size(); l++) {
  2076. if (vertRemaps[l] == old) {
  2077. found = true;
  2078. accel->emitStrings[i][currPos++] = l;
  2079. break;
  2080. }
  2081. }
  2082. AssertFatal(found, "Error, couldn't find the remap!");
  2083. }
  2084. }
  2085. AssertFatal(currPos == emitStringLen, "Error, over/underflowed the emission string!");
  2086. }
  2087. }
  2088. void TSShape::finalizeEditable()
  2089. {
  2090. for (U32 i = 0; i < meshes.size(); i++)
  2091. {
  2092. if (meshes[i])
  2093. {
  2094. meshes[i]->clearEditable();
  2095. }
  2096. }
  2097. }