tsShape.cpp 75 KB

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