tsShape.cpp 76 KB

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