tsMesh.cpp 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124
  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/tsMesh.h"
  24. #include "ts/tsMeshIntrinsics.h"
  25. #include "ts/tsDecal.h"
  26. #include "ts/tsSortedMesh.h"
  27. #include "ts/tsShape.h"
  28. #include "ts/tsShapeInstance.h"
  29. #include "ts/tsRenderState.h"
  30. #include "ts/tsMaterialList.h"
  31. #include "ts/instancingMatHook.h"
  32. #include "math/mMath.h"
  33. #include "math/mathIO.h"
  34. #include "math/mathUtils.h"
  35. #include "console/console.h"
  36. #include "scene/sceneObject.h"
  37. #include "core/bitRender.h"
  38. #include "collision/convex.h"
  39. #include "collision/optimizedPolyList.h"
  40. #include "core/frameAllocator.h"
  41. #include "platform/profiler.h"
  42. #include "materials/sceneData.h"
  43. #include "materials/materialManager.h"
  44. #include "scene/sceneManager.h"
  45. #include "scene/sceneRenderState.h"
  46. #include "materials/matInstance.h"
  47. #include "renderInstance/renderPassManager.h"
  48. #include "materials/customMaterialDefinition.h"
  49. #include "gfx/util/triListOpt.h"
  50. #include "util/triRayCheck.h"
  51. #include "opcode/Opcode.h"
  52. #if defined(TORQUE_OS_XENON)
  53. # include "platformXbox/platformXbox.h"
  54. #endif
  55. GFXPrimitiveType drawTypes[] = { GFXTriangleList, GFXTriangleStrip, GFXTriangleFan };
  56. #define getDrawType(a) (drawTypes[a])
  57. // structures used to share data between detail levels...
  58. // used (and valid) during load only
  59. Vector<Point3F*> TSMesh::smVertsList;
  60. Vector<Point3F*> TSMesh::smNormsList;
  61. Vector<U8*> TSMesh::smEncodedNormsList;
  62. Vector<Point2F*> TSMesh::smTVertsList;
  63. Vector<Point2F*> TSMesh::smTVerts2List;
  64. Vector<ColorI*> TSMesh::smColorsList;
  65. Vector<bool> TSMesh::smDataCopied;
  66. Vector<MatrixF*> TSSkinMesh::smInitTransformList;
  67. Vector<S32*> TSSkinMesh::smVertexIndexList;
  68. Vector<S32*> TSSkinMesh::smBoneIndexList;
  69. Vector<F32*> TSSkinMesh::smWeightList;
  70. Vector<S32*> TSSkinMesh::smNodeIndexList;
  71. Vector<Point3F> gNormalStore;
  72. bool TSMesh::smUseTriangles = false; // convert all primitives to triangle lists on load
  73. bool TSMesh::smUseOneStrip = true; // join triangle strips into one long strip on load
  74. S32 TSMesh::smMinStripSize = 1; // smallest number of _faces_ allowed per strip (all else put in tri list)
  75. bool TSMesh::smUseEncodedNormals = false;
  76. const F32 TSMesh::VISIBILITY_EPSILON = 0.0001f;
  77. S32 TSMesh::smMaxInstancingVerts = 200;
  78. // quick function to force object to face camera -- currently throws out roll :(
  79. void tsForceFaceCamera( MatrixF *mat, const Point3F *objScale )
  80. {
  81. Point4F p;
  82. mat->getColumn( 3, &p );
  83. mat->identity();
  84. mat->setColumn( 3, p );
  85. if ( objScale )
  86. {
  87. MatrixF scale( true );
  88. scale.scale( *objScale );
  89. mat->mul( scale );
  90. }
  91. }
  92. //-----------------------------------------------------
  93. // TSMesh render methods
  94. //-----------------------------------------------------
  95. void TSMesh::render( TSVertexBufferHandle &instanceVB, GFXPrimitiveBufferHandle &instancePB )
  96. {
  97. // A TSMesh never uses the instanceVB.
  98. TORQUE_UNUSED( instanceVB );
  99. TORQUE_UNUSED( instancePB );
  100. innerRender( mVB, mPB );
  101. }
  102. void TSMesh::innerRender( TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb )
  103. {
  104. if ( !vb.isValid() || !pb.isValid() )
  105. return;
  106. GFX->setVertexBuffer( vb );
  107. GFX->setPrimitiveBuffer( pb );
  108. for( U32 p = 0; p < primitives.size(); p++ )
  109. GFX->drawPrimitive( p );
  110. }
  111. void TSMesh::render( TSMaterialList *materials,
  112. const TSRenderState &rdata,
  113. bool isSkinDirty,
  114. const Vector<MatrixF> &transforms,
  115. TSVertexBufferHandle &vertexBuffer,
  116. GFXPrimitiveBufferHandle &primitiveBuffer )
  117. {
  118. // These are only used by TSSkinMesh.
  119. TORQUE_UNUSED( isSkinDirty );
  120. TORQUE_UNUSED( transforms );
  121. TORQUE_UNUSED( vertexBuffer );
  122. TORQUE_UNUSED( primitiveBuffer );
  123. // Pass our shared VB.
  124. innerRender( materials, rdata, mVB, mPB );
  125. }
  126. void TSMesh::innerRender( TSMaterialList *materials, const TSRenderState &rdata, TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb )
  127. {
  128. PROFILE_SCOPE( TSMesh_InnerRender );
  129. if( vertsPerFrame <= 0 )
  130. return;
  131. F32 meshVisibility = rdata.getFadeOverride() * mVisibility;
  132. if ( meshVisibility < VISIBILITY_EPSILON )
  133. return;
  134. const SceneRenderState *state = rdata.getSceneState();
  135. RenderPassManager *renderPass = state->getRenderPass();
  136. MeshRenderInst *coreRI = renderPass->allocInst<MeshRenderInst>();
  137. coreRI->type = RenderPassManager::RIT_Mesh;
  138. const MatrixF &objToWorld = GFX->getWorldMatrix();
  139. // Sort by the center point or the bounds.
  140. if ( rdata.useOriginSort() )
  141. coreRI->sortDistSq = ( objToWorld.getPosition() - state->getCameraPosition() ).lenSquared();
  142. else
  143. {
  144. Box3F rBox = mBounds;
  145. objToWorld.mul( rBox );
  146. coreRI->sortDistSq = rBox.getSqDistanceToPoint( state->getCameraPosition() );
  147. }
  148. if (getFlags(Billboard))
  149. {
  150. Point3F camPos = state->getDiffuseCameraPosition();
  151. Point3F objPos;
  152. objToWorld.getColumn(3, &objPos);
  153. Point3F targetVector = camPos - objPos;
  154. if(getFlags(BillboardZAxis))
  155. targetVector.z = 0.0f;
  156. targetVector.normalize();
  157. MatrixF orient = MathUtils::createOrientFromDir(targetVector);
  158. orient.setPosition(objPos);
  159. orient.scale(objToWorld.getScale());
  160. coreRI->objectToWorld = renderPass->allocUniqueXform( orient );
  161. }
  162. else
  163. coreRI->objectToWorld = renderPass->allocUniqueXform( objToWorld );
  164. coreRI->worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  165. coreRI->projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  166. AssertFatal( vb.isValid(), "TSMesh::innerRender() - Got invalid vertex buffer!" );
  167. AssertFatal( pb.isValid(), "TSMesh::innerRender() - Got invalid primitive buffer!" );
  168. coreRI->vertBuff = &vb;
  169. coreRI->primBuff = &pb;
  170. coreRI->defaultKey2 = (U32) coreRI->vertBuff;
  171. coreRI->materialHint = rdata.getMaterialHint();
  172. coreRI->visibility = meshVisibility;
  173. coreRI->cubemap = rdata.getCubemap();
  174. // NOTICE: SFXBB is removed and refraction is disabled!
  175. //coreRI->backBuffTex = GFX->getSfxBackBuffer();
  176. for ( S32 i = 0; i < primitives.size(); i++ )
  177. {
  178. const TSDrawPrimitive &draw = primitives[i];
  179. // We need to have a material.
  180. if ( draw.matIndex & TSDrawPrimitive::NoMaterial )
  181. continue;
  182. #ifdef TORQUE_DEBUG
  183. // for inspection if you happen to be running in a debugger and can't do bit
  184. // operations in your head.
  185. S32 triangles = draw.matIndex & TSDrawPrimitive::Triangles;
  186. S32 strip = draw.matIndex & TSDrawPrimitive::Strip;
  187. S32 fan = draw.matIndex & TSDrawPrimitive::Fan;
  188. S32 indexed = draw.matIndex & TSDrawPrimitive::Indexed;
  189. S32 type = draw.matIndex & TSDrawPrimitive::TypeMask;
  190. TORQUE_UNUSED(triangles);
  191. TORQUE_UNUSED(strip);
  192. TORQUE_UNUSED(fan);
  193. TORQUE_UNUSED(indexed);
  194. TORQUE_UNUSED(type);
  195. #endif
  196. const U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  197. BaseMatInstance *matInst = materials->getMaterialInst( matIndex );
  198. #ifndef TORQUE_OS_MAC
  199. // Get the instancing material if this mesh qualifies.
  200. if ( meshType != SkinMeshType && pb->mPrimitiveArray[i].numVertices < smMaxInstancingVerts )
  201. matInst = InstancingMaterialHook::getInstancingMat( matInst );
  202. #endif
  203. // If we don't have a material instance after the overload then
  204. // there is nothing to render... skip this primitive.
  205. matInst = state->getOverrideMaterial( matInst );
  206. if ( !matInst || !matInst->isValid())
  207. continue;
  208. // If the material needs lights then gather them
  209. // here once and set them on the core render inst.
  210. if ( matInst->isForwardLit() && !coreRI->lights[0] && rdata.getLightQuery() )
  211. rdata.getLightQuery()->getLights( coreRI->lights, 8 );
  212. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  213. *ri = *coreRI;
  214. ri->matInst = matInst;
  215. ri->defaultKey = matInst->getStateHint();
  216. ri->primBuffIndex = i;
  217. // Translucent materials need the translucent type.
  218. if ( matInst->getMaterial()->isTranslucent() )
  219. {
  220. ri->type = RenderPassManager::RIT_Translucent;
  221. ri->translucentSort = true;
  222. }
  223. renderPass->addInst( ri );
  224. }
  225. }
  226. const Point3F * TSMesh::getNormals( S32 firstVert )
  227. {
  228. if ( getFlags( UseEncodedNormals ) )
  229. {
  230. gNormalStore.setSize( vertsPerFrame );
  231. for ( S32 i = 0; i < encodedNorms.size(); i++ )
  232. gNormalStore[i] = decodeNormal( encodedNorms[ i + firstVert ] );
  233. return gNormalStore.address();
  234. }
  235. return &norms[firstVert];
  236. }
  237. //-----------------------------------------------------
  238. // TSMesh collision methods
  239. //-----------------------------------------------------
  240. bool TSMesh::buildPolyList( S32 frame, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  241. {
  242. S32 firstVert = vertsPerFrame * frame, i, base = 0;
  243. // add the verts...
  244. if ( vertsPerFrame )
  245. {
  246. if ( mVertexData.isReady() )
  247. {
  248. OptimizedPolyList* opList = dynamic_cast<OptimizedPolyList*>(polyList);
  249. if ( opList )
  250. {
  251. base = opList->mVertexList.size();
  252. for ( i = 0; i < vertsPerFrame; i++ )
  253. {
  254. // Don't use vertex() method as we want to retain the original indices
  255. OptimizedPolyList::VertIndex vert;
  256. vert.vertIdx = opList->insertPoint( mVertexData[ i + firstVert ].vert() );
  257. vert.normalIdx = opList->insertNormal( mVertexData[ i + firstVert ].normal() );
  258. vert.uv0Idx = opList->insertUV0( mVertexData[ i + firstVert ].tvert() );
  259. if ( mHasTVert2 )
  260. vert.uv1Idx = opList->insertUV1( mVertexData[ i + firstVert ].tvert2() );
  261. opList->mVertexList.push_back( vert );
  262. }
  263. }
  264. else
  265. {
  266. base = polyList->addPointAndNormal( mVertexData[firstVert].vert(), mVertexData[firstVert].normal() );
  267. for ( i = 1; i < vertsPerFrame; i++ )
  268. {
  269. polyList->addPointAndNormal( mVertexData[ i + firstVert ].vert(), mVertexData[ i + firstVert ].normal() );
  270. }
  271. }
  272. }
  273. else
  274. {
  275. OptimizedPolyList* opList = dynamic_cast<OptimizedPolyList*>(polyList);
  276. if ( opList )
  277. {
  278. base = opList->mVertexList.size();
  279. for ( i = 0; i < vertsPerFrame; i++ )
  280. {
  281. // Don't use vertex() method as we want to retain the original indices
  282. OptimizedPolyList::VertIndex vert;
  283. vert.vertIdx = opList->insertPoint( verts[ i + firstVert ] );
  284. vert.normalIdx = opList->insertNormal( norms[ i + firstVert ] );
  285. vert.uv0Idx = opList->insertUV0( tverts[ i + firstVert ] );
  286. if ( mHasTVert2 )
  287. vert.uv1Idx = opList->insertUV1( tverts2[ i + firstVert ] );
  288. opList->mVertexList.push_back( vert );
  289. }
  290. }
  291. else
  292. {
  293. base = polyList->addPointAndNormal( verts[firstVert], norms[firstVert] );
  294. for ( i = 1; i < vertsPerFrame; i++ )
  295. polyList->addPointAndNormal( verts[ i + firstVert ], norms[ i + firstVert ] );
  296. }
  297. }
  298. }
  299. // add the polys...
  300. for ( i = 0; i < primitives.size(); i++ )
  301. {
  302. TSDrawPrimitive & draw = primitives[i];
  303. U32 start = draw.start;
  304. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  305. U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  306. BaseMatInstance* material = ( materials ? materials->getMaterialInst( matIndex ) : 0 );
  307. // gonna depend on what kind of primitive it is...
  308. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  309. {
  310. for ( S32 j = 0; j < draw.numElements; )
  311. {
  312. U32 idx0 = base + indices[start + j + 0];
  313. U32 idx1 = base + indices[start + j + 1];
  314. U32 idx2 = base + indices[start + j + 2];
  315. polyList->begin(material,surfaceKey++);
  316. polyList->vertex( idx0 );
  317. polyList->vertex( idx1 );
  318. polyList->vertex( idx2 );
  319. polyList->plane( idx0, idx1, idx2 );
  320. polyList->end();
  321. j += 3;
  322. }
  323. }
  324. else
  325. {
  326. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::buildPolyList (2)" );
  327. U32 idx0 = base + indices[start + 0];
  328. U32 idx1;
  329. U32 idx2 = base + indices[start + 1];
  330. U32 * nextIdx = &idx1;
  331. for ( S32 j = 2; j < draw.numElements; j++ )
  332. {
  333. *nextIdx = idx2;
  334. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  335. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  336. idx2 = base + indices[start + j];
  337. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  338. continue;
  339. polyList->begin( material, surfaceKey++ );
  340. polyList->vertex( idx0 );
  341. polyList->vertex( idx1 );
  342. polyList->vertex( idx2 );
  343. polyList->plane( idx0, idx1, idx2 );
  344. polyList->end();
  345. }
  346. }
  347. }
  348. return true;
  349. }
  350. bool TSMesh::getFeatures( S32 frame, const MatrixF& mat, const VectorF&, ConvexFeature* cf, U32& )
  351. {
  352. S32 firstVert = vertsPerFrame * frame;
  353. S32 i;
  354. S32 base = cf->mVertexList.size();
  355. for ( i = 0; i < vertsPerFrame; i++ )
  356. {
  357. cf->mVertexList.increment();
  358. mat.mulP( mVertexData[firstVert + i].vert(), &cf->mVertexList.last() );
  359. }
  360. // add the polys...
  361. for ( i = 0; i < primitives.size(); i++ )
  362. {
  363. TSDrawPrimitive & draw = primitives[i];
  364. U32 start = draw.start;
  365. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  366. // gonna depend on what kind of primitive it is...
  367. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  368. {
  369. for ( S32 j = 0; j < draw.numElements; j += 3 )
  370. {
  371. PlaneF plane( cf->mVertexList[base + indices[start + j + 0]],
  372. cf->mVertexList[base + indices[start + j + 1]],
  373. cf->mVertexList[base + indices[start + j + 2]]);
  374. cf->mFaceList.increment();
  375. cf->mFaceList.last().normal = plane;
  376. cf->mFaceList.last().vertex[0] = base + indices[start + j + 0];
  377. cf->mFaceList.last().vertex[1] = base + indices[start + j + 1];
  378. cf->mFaceList.last().vertex[2] = base + indices[start + j + 2];
  379. for ( U32 l = 0; l < 3; l++ )
  380. {
  381. U32 newEdge0, newEdge1;
  382. U32 zero = base + indices[start + j + l];
  383. U32 one = base + indices[start + j + ((l+1)%3)];
  384. newEdge0 = getMin( zero, one );
  385. newEdge1 = getMax( zero, one );
  386. bool found = false;
  387. for ( S32 k = 0; k < cf->mEdgeList.size(); k++ )
  388. {
  389. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  390. cf->mEdgeList[k].vertex[1] == newEdge1)
  391. {
  392. found = true;
  393. break;
  394. }
  395. }
  396. if ( !found )
  397. {
  398. cf->mEdgeList.increment();
  399. cf->mEdgeList.last().vertex[0] = newEdge0;
  400. cf->mEdgeList.last().vertex[1] = newEdge1;
  401. }
  402. }
  403. }
  404. }
  405. else
  406. {
  407. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::buildPolyList (2)" );
  408. U32 idx0 = base + indices[start + 0];
  409. U32 idx1;
  410. U32 idx2 = base + indices[start + 1];
  411. U32 * nextIdx = &idx1;
  412. for ( S32 j = 2; j < draw.numElements; j++ )
  413. {
  414. *nextIdx = idx2;
  415. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  416. idx2 = base + indices[start + j];
  417. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  418. continue;
  419. PlaneF plane( cf->mVertexList[idx0],
  420. cf->mVertexList[idx1],
  421. cf->mVertexList[idx2] );
  422. cf->mFaceList.increment();
  423. cf->mFaceList.last().normal = plane;
  424. cf->mFaceList.last().vertex[0] = idx0;
  425. cf->mFaceList.last().vertex[1] = idx1;
  426. cf->mFaceList.last().vertex[2] = idx2;
  427. U32 newEdge0, newEdge1;
  428. newEdge0 = getMin( idx0, idx1 );
  429. newEdge1 = getMax( idx0, idx1 );
  430. bool found = false;
  431. S32 k;
  432. for ( k = 0; k < cf->mEdgeList.size(); k++ )
  433. {
  434. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  435. cf->mEdgeList[k].vertex[1] == newEdge1)
  436. {
  437. found = true;
  438. break;
  439. }
  440. }
  441. if ( !found )
  442. {
  443. cf->mEdgeList.increment();
  444. cf->mEdgeList.last().vertex[0] = newEdge0;
  445. cf->mEdgeList.last().vertex[1] = newEdge1;
  446. }
  447. newEdge0 = getMin( idx1, idx2 );
  448. newEdge1 = getMax( idx1, idx2 );
  449. found = false;
  450. for ( k = 0; k < cf->mEdgeList.size(); k++ )
  451. {
  452. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  453. cf->mEdgeList[k].vertex[1] == newEdge1 )
  454. {
  455. found = true;
  456. break;
  457. }
  458. }
  459. if ( !found )
  460. {
  461. cf->mEdgeList.increment();
  462. cf->mEdgeList.last().vertex[0] = newEdge0;
  463. cf->mEdgeList.last().vertex[1] = newEdge1;
  464. }
  465. newEdge0 = getMin(idx0, idx2);
  466. newEdge1 = getMax(idx0, idx2);
  467. found = false;
  468. for ( k = 0; k < cf->mEdgeList.size(); k++ )
  469. {
  470. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  471. cf->mEdgeList[k].vertex[1] == newEdge1 )
  472. {
  473. found = true;
  474. break;
  475. }
  476. }
  477. if ( !found )
  478. {
  479. cf->mEdgeList.increment();
  480. cf->mEdgeList.last().vertex[0] = newEdge0;
  481. cf->mEdgeList.last().vertex[1] = newEdge1;
  482. }
  483. }
  484. }
  485. }
  486. return false;
  487. }
  488. void TSMesh::support( S32 frame, const Point3F &v, F32 *currMaxDP, Point3F *currSupport )
  489. {
  490. if ( vertsPerFrame == 0 )
  491. return;
  492. U32 waterMark = FrameAllocator::getWaterMark();
  493. F32* pDots = (F32*)FrameAllocator::alloc( sizeof(F32) * vertsPerFrame );
  494. S32 firstVert = vertsPerFrame * frame;
  495. m_point3F_bulk_dot( &v.x,
  496. &mVertexData[firstVert].vert().x,
  497. vertsPerFrame,
  498. mVertexData.vertSize(),
  499. pDots );
  500. F32 localdp = *currMaxDP;
  501. S32 index = -1;
  502. for ( S32 i = 0; i < vertsPerFrame; i++ )
  503. {
  504. if ( pDots[i] > localdp )
  505. {
  506. localdp = pDots[i];
  507. index = i;
  508. }
  509. }
  510. FrameAllocator::setWaterMark(waterMark);
  511. if ( index != -1 )
  512. {
  513. *currMaxDP = localdp;
  514. *currSupport = mVertexData[index + firstVert].vert();
  515. }
  516. }
  517. bool TSMesh::castRay( S32 frame, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  518. {
  519. if ( planeNormals.empty() )
  520. buildConvexHull(); // if haven't done it yet...
  521. // Keep track of startTime and endTime. They start out at just under 0 and just over 1, respectively.
  522. // As we check against each plane, prune start and end times back to represent current intersection of
  523. // line with all the planes (or rather with all the half-spaces defined by the planes).
  524. // But, instead of explicitly keeping track of startTime and endTime, keep track as numerator and denominator
  525. // so that we can avoid as many divisions as possible.
  526. // F32 startTime = -0.01f;
  527. F32 startNum = -0.01f;
  528. F32 startDen = 1.00f;
  529. // F32 endTime = 1.01f;
  530. F32 endNum = 1.01f;
  531. F32 endDen = 1.00f;
  532. S32 curPlane = 0;
  533. U32 curMaterial = 0;
  534. bool found = false;
  535. // the following block of code is an optimization...
  536. // it isn't necessary if the longer version of the main loop is used
  537. bool tmpFound;
  538. S32 tmpPlane;
  539. F32 sgn = -1.0f;
  540. F32 * pnum = &startNum;
  541. F32 * pden = &startDen;
  542. S32 * pplane = &curPlane;
  543. bool * pfound = &found;
  544. S32 startPlane = frame * planesPerFrame;
  545. for ( S32 i = startPlane; i < startPlane + planesPerFrame; i++ )
  546. {
  547. // if start & end outside, no collision
  548. // if start & end inside, continue
  549. // if start outside, end inside, or visa versa, find intersection of line with plane
  550. // then update intersection of line with hull (using startTime and endTime)
  551. F32 dot1 = mDot( planeNormals[i], start ) - planeConstants[i];
  552. F32 dot2 = mDot( planeNormals[i], end) - planeConstants[i];
  553. if ( dot1 * dot2 > 0.0f )
  554. {
  555. // same side of the plane...which side -- dot==0 considered inside
  556. if ( dot1 > 0.0f )
  557. return false; // start and end outside of this plane, no collision
  558. // start and end inside plane, continue
  559. continue;
  560. }
  561. //AssertFatal( dot1 / ( dot1 - dot2 ) >= 0.0f && dot1 / ( dot1 - dot2 ) <= 1.0f,"TSMesh::castRay (1)" );
  562. // find intersection (time) with this plane...
  563. // F32 time = dot1 / (dot1-dot2);
  564. F32 num = mFabs( dot1 );
  565. F32 den = mFabs( dot1 - dot2 );
  566. // the following block of code is an optimized version...
  567. // this can be commented out and the following block of code used instead
  568. // if debugging a problem in this code, that should probably be done
  569. // if you want to see how this works, look at the following block of code,
  570. // not this one...
  571. // Note that this does not get optimized appropriately...it is included this way
  572. // as an idea for future optimization.
  573. if ( sgn * dot1 >= 0 )
  574. {
  575. sgn *= -1.0f;
  576. pnum = (F32*) ((dsize_t)pnum ^ (dsize_t)&endNum ^ (dsize_t)&startNum);
  577. pden = (F32*) ((dsize_t)pden ^ (dsize_t)&endDen ^ (dsize_t)&startDen);
  578. pplane = (S32*) ((dsize_t)pplane ^ (dsize_t)&tmpPlane ^ (dsize_t)&curPlane);
  579. pfound = (bool*) ((dsize_t)pfound ^ (dsize_t)&tmpFound ^ (dsize_t)&found);
  580. }
  581. bool noCollision = num * endDen * sgn < endNum * den * sgn && num * startDen * sgn < startNum * den * sgn;
  582. if (num * *pden * sgn < *pnum * den * sgn && !noCollision)
  583. {
  584. *pnum = num;
  585. *pden = den;
  586. *pplane = i;
  587. *pfound = true;
  588. }
  589. else if ( noCollision )
  590. return false;
  591. // if (dot1<=0.0f)
  592. // {
  593. // // start is inside plane, end is outside...chop off end
  594. // if (num*endDen<endNum*den) // if (time<endTime)
  595. // {
  596. // if (num*startDen<startNum*den) //if (time<startTime)
  597. // // no intersection of line and hull
  598. // return false;
  599. // // endTime = time;
  600. // endNum = num;
  601. // endDen = den;
  602. // }
  603. // // else, no need to do anything, just continue (we've been more inside than this)
  604. // }
  605. // else // dot2<=0.0f
  606. // {
  607. // // end is inside poly, start is outside...chop off start
  608. // AssertFatal(dot2<=0.0f,"TSMesh::castRay (2)");
  609. // if (num*startDen>startNum*den) // if (time>startTime)
  610. // {
  611. // if (num*endDen>endNum*den) //if (time>endTime)
  612. // // no intersection of line and hull
  613. // return false;
  614. // // startTime = time;
  615. // startNum = num;
  616. // startDen = den;
  617. // curPlane = i;
  618. // curMaterial = planeMaterials[i-startPlane];
  619. // found = true;
  620. // }
  621. // // else, no need to do anything, just continue (we've been more inside than this)
  622. // }
  623. }
  624. // setup rayInfo
  625. if ( found && rayInfo )
  626. {
  627. curMaterial = planeMaterials[ curPlane - startPlane ];
  628. rayInfo->t = (F32)startNum/(F32)startDen; // finally divide...
  629. rayInfo->normal = planeNormals[curPlane];
  630. if (materials && materials->size() > 0)
  631. rayInfo->material = materials->getMaterialInst( curMaterial );
  632. else
  633. rayInfo->material = NULL;
  634. rayInfo->setContactPoint( start, end );
  635. return true;
  636. }
  637. else if ( found )
  638. return true;
  639. // only way to get here is if start is inside hull...
  640. // we could return null and just plug in garbage for the material and normal...
  641. return false;
  642. }
  643. bool TSMesh::castRayRendered( S32 frame, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  644. {
  645. if( vertsPerFrame <= 0 )
  646. return false;
  647. if( mNumVerts == 0 )
  648. return false;
  649. S32 firstVert = vertsPerFrame * frame;
  650. bool found = false;
  651. F32 best_t = F32_MAX;
  652. U32 bestIdx0 = 0, bestIdx1 = 0, bestIdx2 = 0;
  653. BaseMatInstance* bestMaterial = NULL;
  654. Point3F dir = end - start;
  655. for ( S32 i = 0; i < primitives.size(); i++ )
  656. {
  657. TSDrawPrimitive & draw = primitives[i];
  658. U32 drawStart = draw.start;
  659. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::castRayRendered (1)" );
  660. U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  661. BaseMatInstance* material = ( materials ? materials->getMaterialInst( matIndex ) : 0 );
  662. U32 idx0, idx1, idx2;
  663. // gonna depend on what kind of primitive it is...
  664. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  665. {
  666. for ( S32 j = 0; j < draw.numElements-2; j += 3 )
  667. {
  668. idx0 = indices[drawStart + j + 0];
  669. idx1 = indices[drawStart + j + 1];
  670. idx2 = indices[drawStart + j + 2];
  671. F32 cur_t = 0;
  672. Point2F b;
  673. if(castRayTriangle(start, dir, mVertexData[firstVert + idx0].vert(),
  674. mVertexData[firstVert + idx1].vert(), mVertexData[firstVert + idx2].vert(), cur_t, b))
  675. {
  676. if(cur_t < best_t)
  677. {
  678. best_t = cur_t;
  679. bestIdx0 = idx0;
  680. bestIdx1 = idx1;
  681. bestIdx2 = idx2;
  682. bestMaterial = material;
  683. found = true;
  684. }
  685. }
  686. }
  687. }
  688. else
  689. {
  690. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::castRayRendered (2)" );
  691. idx0 = indices[drawStart + 0];
  692. idx2 = indices[drawStart + 1];
  693. U32 * nextIdx = &idx1;
  694. for ( S32 j = 2; j < draw.numElements; j++ )
  695. {
  696. *nextIdx = idx2;
  697. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  698. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  699. idx2 = indices[drawStart + j];
  700. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  701. continue;
  702. F32 cur_t = 0;
  703. Point2F b;
  704. if(castRayTriangle(start, dir, mVertexData[firstVert + idx0].vert(),
  705. mVertexData[firstVert + idx1].vert(), mVertexData[firstVert + idx2].vert(), cur_t, b))
  706. {
  707. if(cur_t < best_t)
  708. {
  709. best_t = cur_t;
  710. bestIdx0 = firstVert + idx0;
  711. bestIdx1 = firstVert + idx1;
  712. bestIdx2 = firstVert + idx2;
  713. bestMaterial = material;
  714. found = true;
  715. }
  716. }
  717. }
  718. }
  719. }
  720. // setup rayInfo
  721. if ( found && rayInfo )
  722. {
  723. rayInfo->t = best_t;
  724. Point3F normal;
  725. mCross(mVertexData[bestIdx2].vert()-mVertexData[bestIdx0].vert(),mVertexData[bestIdx1].vert()-mVertexData[bestIdx0].vert(),&normal);
  726. if ( mDot( normal, normal ) < 0.001f )
  727. {
  728. mCross( mVertexData[bestIdx0].vert() - mVertexData[bestIdx1].vert(), mVertexData[bestIdx2].vert() - mVertexData[bestIdx1].vert(), &normal );
  729. if ( mDot( normal, normal ) < 0.001f )
  730. {
  731. mCross( mVertexData[bestIdx1].vert() - mVertexData[bestIdx2].vert(), mVertexData[bestIdx0].vert() - mVertexData[bestIdx2].vert(), &normal );
  732. }
  733. }
  734. normal.normalize();
  735. rayInfo->normal = normal;
  736. rayInfo->material = bestMaterial;
  737. rayInfo->setContactPoint( start, end );
  738. return true;
  739. }
  740. else if ( found )
  741. return true;
  742. return false;
  743. }
  744. bool TSMesh::addToHull( U32 idx0, U32 idx1, U32 idx2 )
  745. {
  746. // calculate the normal of this triangle... remember, we lose precision
  747. // when we subtract two large numbers that are very close to each other,
  748. // so depending on how we calculate the normal, we could get a
  749. // different result. so, we will calculate the normal three different
  750. // ways and take the one that gives us the largest vector before we
  751. // normalize.
  752. Point3F normal1, normal2, normal3;
  753. mCross(mVertexData[idx2].vert()-mVertexData[idx0].vert(),mVertexData[idx1].vert()-mVertexData[idx0].vert(),&normal1);
  754. mCross(mVertexData[idx0].vert()-mVertexData[idx1].vert(),mVertexData[idx2].vert()-mVertexData[idx1].vert(),&normal2);
  755. mCross(mVertexData[idx1].vert()-mVertexData[idx2].vert(),mVertexData[idx0].vert()-mVertexData[idx2].vert(),&normal3);
  756. Point3F normal = normal1;
  757. F32 greatestMagSquared = mDot(normal1, normal1);
  758. F32 magSquared = mDot(normal2, normal2);
  759. if (magSquared > greatestMagSquared)
  760. {
  761. normal = normal2;
  762. greatestMagSquared = magSquared;
  763. }
  764. magSquared = mDot(normal3, normal3);
  765. if (magSquared > greatestMagSquared)
  766. {
  767. normal = normal3;
  768. greatestMagSquared = magSquared;
  769. }
  770. if (mDot(normal, normal) < 0.00000001f)
  771. return false;
  772. normal.normalize();
  773. F32 k = mDot( normal, mVertexData[idx0].vert() );
  774. for ( S32 i = 0; i < planeNormals.size(); i++ )
  775. {
  776. if ( mDot( planeNormals[i], normal ) > 0.99f && mFabs( k-planeConstants[i] ) < 0.01f )
  777. return false; // this is a repeat...
  778. }
  779. // new plane, add it to the list...
  780. planeNormals.push_back( normal );
  781. planeConstants.push_back( k );
  782. return true;
  783. }
  784. bool TSMesh::buildConvexHull()
  785. {
  786. // already done, return without error
  787. if ( planeNormals.size() )
  788. return true;
  789. bool error = false;
  790. // should probably only have 1 frame, but just in case...
  791. planesPerFrame = 0;
  792. S32 frame, i, j;
  793. for ( frame = 0; frame < numFrames; frame++ )
  794. {
  795. S32 firstVert = vertsPerFrame * frame;
  796. S32 firstPlane = planeNormals.size();
  797. for ( i = 0; i < primitives.size(); i++ )
  798. {
  799. TSDrawPrimitive & draw = primitives[i];
  800. U32 start = draw.start;
  801. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildConvexHull (1)" );
  802. // gonna depend on what kind of primitive it is...
  803. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  804. {
  805. for ( j = 0; j < draw.numElements; j += 3 )
  806. if ( addToHull( indices[start + j + 0] + firstVert,
  807. indices[start + j + 1] + firstVert,
  808. indices[start + j + 2] + firstVert ) && frame == 0 )
  809. planeMaterials.push_back( draw.matIndex & TSDrawPrimitive::MaterialMask );
  810. }
  811. else
  812. {
  813. AssertFatal( (draw.matIndex&TSDrawPrimitive::Strip) == TSDrawPrimitive::Strip,"TSMesh::buildConvexHull (2)" );
  814. U32 idx0 = indices[start + 0] + firstVert;
  815. U32 idx1;
  816. U32 idx2 = indices[start + 1] + firstVert;
  817. U32 * nextIdx = &idx1;
  818. for ( j = 2; j < draw.numElements; j++ )
  819. {
  820. *nextIdx = idx2;
  821. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  822. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1 );
  823. idx2 = indices[start + j] + firstVert;
  824. if ( addToHull( idx0, idx1, idx2 ) && frame == 0 )
  825. planeMaterials.push_back( draw.matIndex & TSDrawPrimitive::MaterialMask );
  826. }
  827. }
  828. }
  829. // make sure all the verts on this frame are inside all the planes
  830. for ( i = 0; i < vertsPerFrame; i++ )
  831. for ( j = firstPlane; j < planeNormals.size(); j++ )
  832. if ( mDot( mVertexData[firstVert + i].vert(), planeNormals[j] ) - planeConstants[j] < 0.01 ) // .01 == a little slack
  833. error = true;
  834. if ( frame == 0 )
  835. planesPerFrame = planeNormals.size();
  836. if ( (frame + 1) * planesPerFrame != planeNormals.size() )
  837. {
  838. // eek, not all frames have same number of planes...
  839. while ( (frame + 1) * planesPerFrame > planeNormals.size() )
  840. {
  841. // we're short, duplicate last plane till we match
  842. U32 sz = planeNormals.size();
  843. planeNormals.increment();
  844. planeNormals.last() = planeNormals[sz-1];
  845. planeConstants.increment();
  846. planeConstants.last() = planeConstants[sz-1];
  847. }
  848. while ( (frame + 1) * planesPerFrame < planeNormals.size() )
  849. {
  850. // harsh -- last frame has more than other frames
  851. // duplicate last plane in each frame
  852. for ( S32 k = frame - 1; k >= 0; k-- )
  853. {
  854. planeNormals.insert( k * planesPerFrame + planesPerFrame );
  855. planeNormals[k * planesPerFrame + planesPerFrame] = planeNormals[k * planesPerFrame + planesPerFrame - 1];
  856. planeConstants.insert( k * planesPerFrame + planesPerFrame );
  857. planeConstants[k * planesPerFrame + planesPerFrame] = planeConstants[k * planesPerFrame + planesPerFrame - 1];
  858. if ( k == 0 )
  859. {
  860. planeMaterials.increment();
  861. planeMaterials.last() = planeMaterials[planeMaterials.size() - 2];
  862. }
  863. }
  864. planesPerFrame++;
  865. }
  866. }
  867. AssertFatal( (frame + 1) * planesPerFrame == planeNormals.size(),"TSMesh::buildConvexHull (3)" );
  868. }
  869. return !error;
  870. }
  871. //-----------------------------------------------------
  872. // TSMesh bounds methods
  873. //-----------------------------------------------------
  874. void TSMesh::computeBounds()
  875. {
  876. MatrixF mat(true);
  877. computeBounds( mat, mBounds, -1, &mCenter, &mRadius );
  878. }
  879. void TSMesh::computeBounds( const MatrixF &transform, Box3F &bounds, S32 frame, Point3F *center, F32 *radius )
  880. {
  881. const Point3F *baseVert = NULL;
  882. S32 stride = 0;
  883. S32 numVerts = 0;
  884. if(mVertexData.isReady())
  885. {
  886. baseVert = &mVertexData[0].vert();
  887. stride = mVertexData.vertSize();
  888. if ( frame < 0 )
  889. numVerts = mNumVerts;
  890. else
  891. {
  892. baseVert = &mVertexData[frame * vertsPerFrame].vert();
  893. numVerts = vertsPerFrame;
  894. }
  895. }
  896. else
  897. {
  898. baseVert = verts.address();
  899. stride = sizeof(Point3F);
  900. if ( frame < 0 )
  901. numVerts = verts.size();
  902. else
  903. {
  904. baseVert += frame * vertsPerFrame;
  905. numVerts = vertsPerFrame;
  906. }
  907. }
  908. computeBounds( baseVert, numVerts, stride, transform, bounds, center, radius );
  909. }
  910. void TSMesh::computeBounds( const Point3F *v, S32 numVerts, S32 stride, const MatrixF &transform, Box3F &bounds, Point3F *center, F32 *radius )
  911. {
  912. const U8 *_vb = reinterpret_cast<const U8 *>(v);
  913. if ( !numVerts )
  914. {
  915. bounds.minExtents = Point3F::Zero;
  916. bounds.maxExtents = Point3F::Zero;
  917. if ( center )
  918. *center = Point3F::Zero;
  919. if ( radius )
  920. *radius = 0;
  921. return;
  922. }
  923. S32 i;
  924. Point3F p;
  925. transform.mulP( *v, &bounds.minExtents );
  926. bounds.maxExtents = bounds.minExtents;
  927. for ( i = 0; i < numVerts; i++ )
  928. {
  929. const Point3F &curVert = *reinterpret_cast<const Point3F *>(_vb + i * stride);
  930. transform.mulP( curVert, &p );
  931. bounds.maxExtents.setMax( p );
  932. bounds.minExtents.setMin( p );
  933. }
  934. Point3F c;
  935. if ( !center )
  936. center = &c;
  937. center->x = 0.5f * (bounds.minExtents.x + bounds.maxExtents.x);
  938. center->y = 0.5f * (bounds.minExtents.y + bounds.maxExtents.y);
  939. center->z = 0.5f * (bounds.minExtents.z + bounds.maxExtents.z);
  940. if ( radius )
  941. {
  942. *radius = 0.0f;
  943. for ( i = 0; i < numVerts; i++ )
  944. {
  945. const Point3F &curVert = *reinterpret_cast<const Point3F *>(_vb + i * stride);
  946. transform.mulP( curVert, &p );
  947. p -= *center;
  948. *radius = getMax( *radius, mDot( p, p ) );
  949. }
  950. *radius = mSqrt( *radius );
  951. }
  952. }
  953. //-----------------------------------------------------
  954. S32 TSMesh::getNumPolys() const
  955. {
  956. S32 count = 0;
  957. for ( S32 i = 0; i < primitives.size(); i++ )
  958. {
  959. switch (primitives[i].matIndex & TSDrawPrimitive::TypeMask)
  960. {
  961. case TSDrawPrimitive::Triangles:
  962. count += primitives[i].numElements / 3;
  963. break;
  964. case TSDrawPrimitive::Fan:
  965. count += primitives[i].numElements - 2;
  966. break;
  967. case TSDrawPrimitive::Strip:
  968. // Don't count degenerate triangles
  969. for ( S32 j = primitives[i].start;
  970. j < primitives[i].start+primitives[i].numElements-2;
  971. j++ )
  972. {
  973. if ((indices[j] != indices[j+1]) &&
  974. (indices[j] != indices[j+2]) &&
  975. (indices[j+1] != indices[j+2]))
  976. count++;
  977. }
  978. break;
  979. }
  980. }
  981. return count;
  982. }
  983. //-----------------------------------------------------
  984. TSMesh::TSMesh() : meshType( StandardMeshType )
  985. {
  986. VECTOR_SET_ASSOCIATION( planeNormals );
  987. VECTOR_SET_ASSOCIATION( planeConstants );
  988. VECTOR_SET_ASSOCIATION( planeMaterials );
  989. parentMesh = -1;
  990. mOptTree = NULL;
  991. mOpMeshInterface = NULL;
  992. mOpTris = NULL;
  993. mOpPoints = NULL;
  994. mDynamic = false;
  995. mVisibility = 1.0f;
  996. mHasTVert2 = false;
  997. mHasColor = false;
  998. mNumVerts = 0;
  999. }
  1000. //-----------------------------------------------------
  1001. // TSMesh destructor
  1002. //-----------------------------------------------------
  1003. TSMesh::~TSMesh()
  1004. {
  1005. SAFE_DELETE( mOptTree );
  1006. SAFE_DELETE( mOpMeshInterface );
  1007. SAFE_DELETE_ARRAY( mOpTris );
  1008. SAFE_DELETE_ARRAY( mOpPoints );
  1009. mNumVerts = 0;
  1010. }
  1011. //-----------------------------------------------------
  1012. // TSSkinMesh methods
  1013. //-----------------------------------------------------
  1014. void TSSkinMesh::updateSkin( const Vector<MatrixF> &transforms, TSVertexBufferHandle &instanceVB, GFXPrimitiveBufferHandle &instancePB )
  1015. {
  1016. PROFILE_SCOPE( TSSkinMesh_UpdateSkin );
  1017. AssertFatal(batchDataInitialized, "Batch data not initialized. Call createBatchData() before any skin update is called.");
  1018. // set arrays
  1019. #if defined(TORQUE_MAX_LIB)
  1020. verts.setSize(batchData.initialVerts.size());
  1021. norms.setSize(batchData.initialNorms.size());
  1022. #else
  1023. if ( !batchDataInitialized && encodedNorms.size() )
  1024. {
  1025. // we co-opt responsibility for updating encoded normals from mesh
  1026. gNormalStore.setSize( vertsPerFrame );
  1027. for ( S32 i = 0; i < vertsPerFrame; i++ )
  1028. gNormalStore[i] = decodeNormal( encodedNorms[i] );
  1029. batchData.initialNorms.set( gNormalStore.address(), vertsPerFrame );
  1030. }
  1031. #endif
  1032. static Vector<MatrixF> sBoneTransforms;
  1033. sBoneTransforms.setSize( batchData.nodeIndex.size() );
  1034. // set up bone transforms
  1035. PROFILE_START(TSSkinMesh_UpdateTransforms);
  1036. for( S32 i=0; i<batchData.nodeIndex.size(); i++ )
  1037. {
  1038. S32 node = batchData.nodeIndex[i];
  1039. sBoneTransforms[i].mul( transforms[node], batchData.initialTransforms[i] );
  1040. }
  1041. const MatrixF * matrices = &sBoneTransforms[0];
  1042. PROFILE_END();
  1043. // Perform skinning
  1044. const bool bBatchByVert = !batchData.vertexBatchOperations.empty();
  1045. if(bBatchByVert)
  1046. {
  1047. const Point3F *inVerts = &batchData.initialVerts[0];
  1048. const Point3F *inNorms = &batchData.initialNorms[0];
  1049. Point3F srcVtx, srcNrm;
  1050. AssertFatal( batchData.vertexBatchOperations.size() == batchData.initialVerts.size(), "Assumption failed!" );
  1051. register Point3F skinnedVert;
  1052. register Point3F skinnedNorm;
  1053. for( Vector<BatchData::BatchedVertex>::const_iterator itr = batchData.vertexBatchOperations.begin();
  1054. itr != batchData.vertexBatchOperations.end(); itr++ )
  1055. {
  1056. const BatchData::BatchedVertex &curVert = *itr;
  1057. skinnedVert.zero();
  1058. skinnedNorm.zero();
  1059. for( S32 tOp = 0; tOp < curVert.transformCount; tOp++ )
  1060. {
  1061. const BatchData::TransformOp &transformOp = curVert.transform[tOp];
  1062. const MatrixF& deltaTransform = matrices[transformOp.transformIndex];
  1063. deltaTransform.mulP( inVerts[curVert.vertexIndex], &srcVtx );
  1064. skinnedVert += ( srcVtx * transformOp.weight );
  1065. deltaTransform.mulV( inNorms[curVert.vertexIndex], &srcNrm );
  1066. skinnedNorm += srcNrm * transformOp.weight;
  1067. }
  1068. // Assign results
  1069. __TSMeshVertexBase &dest = mVertexData[curVert.vertexIndex];
  1070. dest.vert(skinnedVert);
  1071. dest.normal(skinnedNorm);
  1072. }
  1073. }
  1074. else // Batch by transform
  1075. {
  1076. U8 *outPtr = reinterpret_cast<U8 *>(mVertexData.address());
  1077. dsize_t outStride = mVertexData.vertSize();
  1078. #if defined(USE_MEM_VERTEX_BUFFERS)
  1079. // Initialize it if NULL.
  1080. // Skinning includes readbacks from memory (argh) so don't allocate with PAGE_WRITECOMBINE
  1081. if( instanceVB.isNull() )
  1082. instanceVB.set( GFX, outStride, mVertexFormat, mNumVerts, GFXBufferTypeDynamic );
  1083. // Grow if needed
  1084. if( instanceVB.getPointer()->mNumVerts < mNumVerts )
  1085. instanceVB.resize( mNumVerts );
  1086. // Lock, and skin directly into the final memory destination
  1087. outPtr = (U8 *)instanceVB.lock();
  1088. if(!outPtr) return;
  1089. #endif
  1090. // Set position/normal to zero so we can accumulate
  1091. zero_vert_normal_bulk(mNumVerts, outPtr, outStride);
  1092. // Iterate over transforms, and perform batch transform x skin_vert
  1093. for(Vector<S32>::const_iterator itr = batchData.transformKeys.begin();
  1094. itr != batchData.transformKeys.end(); itr++)
  1095. {
  1096. const S32 boneXfmIdx = *itr;
  1097. const BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(boneXfmIdx);
  1098. const MatrixF &curBoneMat = matrices[boneXfmIdx];
  1099. const S32 numVerts = curTransform.numElements;
  1100. // Bulk transform points/normals by this transform
  1101. m_matF_x_BatchedVertWeightList(curBoneMat, numVerts, curTransform.alignedMem,
  1102. outPtr, outStride);
  1103. }
  1104. #if defined(USE_MEM_VERTEX_BUFFERS)
  1105. instanceVB.unlock();
  1106. #endif
  1107. }
  1108. }
  1109. S32 QSORT_CALLBACK _sort_BatchedVertWeight( const void *a, const void *b )
  1110. {
  1111. // Sort by vertex index
  1112. const TSSkinMesh::BatchData::BatchedVertWeight &_a = *reinterpret_cast<const TSSkinMesh::BatchData::BatchedVertWeight *>(a);
  1113. const TSSkinMesh::BatchData::BatchedVertWeight &_b = *reinterpret_cast<const TSSkinMesh::BatchData::BatchedVertWeight *>(b);
  1114. return ( _a.vidx - _b.vidx );
  1115. }
  1116. // Batch by vertex is useful to emulate the old skinning, or to build batch data
  1117. // sutable for GPU skinning.
  1118. //#define _BATCH_BY_VERTEX
  1119. void TSSkinMesh::createBatchData()
  1120. {
  1121. if(batchDataInitialized)
  1122. return;
  1123. batchDataInitialized = true;
  1124. S32 * curVtx = vertexIndex.begin();
  1125. S32 * curBone = boneIndex.begin();
  1126. F32 * curWeight = weight.begin();
  1127. const S32 * endVtx = vertexIndex.end();
  1128. // Temp vector to build batch operations
  1129. Vector<BatchData::BatchedVertex> batchOperations;
  1130. bool issuedWeightWarning = false;
  1131. // Build the batch operations
  1132. while( curVtx != endVtx )
  1133. {
  1134. const S32 vidx = *curVtx;
  1135. ++curVtx;
  1136. const S32 midx = *curBone;
  1137. ++curBone;
  1138. const F32 w = *curWeight;
  1139. ++curWeight;
  1140. // Ignore empty weights
  1141. if ( vidx < 0 || midx < 0 || w == 0 )
  1142. continue;
  1143. if( !batchOperations.empty() &&
  1144. batchOperations.last().vertexIndex == vidx )
  1145. {
  1146. AssertFatal( batchOperations.last().transformCount > 0, "Not sure how this happened!" );
  1147. S32 opIdx = batchOperations.last().transformCount++;
  1148. // Limit the number of weights per bone (keep the N largest influences)
  1149. if ( opIdx >= TSSkinMesh::BatchData::maxBonePerVert )
  1150. {
  1151. if ( !issuedWeightWarning )
  1152. {
  1153. issuedWeightWarning = true;
  1154. Con::warnf( "At least one vertex has too many bone weights - limiting "
  1155. "to the largest %d influences (see maxBonePerVert in tsMesh.h).",
  1156. TSSkinMesh::BatchData::maxBonePerVert );
  1157. }
  1158. // Too many weights => find and replace the smallest one
  1159. S32 minIndex = 0;
  1160. F32 minWeight = batchOperations.last().transform[0].weight;
  1161. for ( S32 i = 1; i < batchOperations.last().transformCount; i++ )
  1162. {
  1163. if ( batchOperations.last().transform[i].weight < minWeight )
  1164. {
  1165. minWeight = batchOperations.last().transform[i].weight;
  1166. minIndex = i;
  1167. }
  1168. }
  1169. opIdx = minIndex;
  1170. batchOperations.last().transformCount = TSSkinMesh::BatchData::maxBonePerVert;
  1171. }
  1172. batchOperations.last().transform[opIdx].transformIndex = midx;
  1173. batchOperations.last().transform[opIdx].weight = w;
  1174. }
  1175. else
  1176. {
  1177. batchOperations.increment();
  1178. batchOperations.last().vertexIndex = vidx;
  1179. batchOperations.last().transformCount = 1;
  1180. batchOperations.last().transform[0].transformIndex = midx;
  1181. batchOperations.last().transform[0].weight = w;
  1182. }
  1183. //Con::printf( "[%d] transform idx %d, weight %1.5f", vidx, midx, w );
  1184. }
  1185. //Con::printf("End skin update");
  1186. // Normalize vertex weights (force weights for each vert to sum to 1)
  1187. if ( issuedWeightWarning )
  1188. {
  1189. for ( S32 i = 0; i < batchOperations.size(); i++ )
  1190. {
  1191. BatchData::BatchedVertex& batchOp = batchOperations[i];
  1192. // Sum weights for this vertex
  1193. F32 invTotalWeight = 0;
  1194. for ( S32 j = 0; j < batchOp.transformCount; j++ )
  1195. invTotalWeight += batchOp.transform[j].weight;
  1196. // Then normalize the vertex weights
  1197. invTotalWeight = 1.0f / invTotalWeight;
  1198. for ( S32 j = 0; j < batchOp.transformCount; j++ )
  1199. batchOp.transform[j].weight *= invTotalWeight;
  1200. }
  1201. }
  1202. #ifdef _BATCH_BY_VERTEX
  1203. // Copy data to member, and be done
  1204. batchData.vertexBatchOperations.set(batchOperations.address(), batchOperations.size());
  1205. // Convert to batch-by-transform, which is better for CPU skinning,
  1206. // where-as GPU skinning would data for batch-by-vertex operation
  1207. #else
  1208. // Iterate the batch-by-vertex, and populate the batch-by-transform structs
  1209. for( Vector<BatchData::BatchedVertex>::const_iterator itr = batchOperations.begin();
  1210. itr != batchOperations.end(); itr++ )
  1211. {
  1212. const BatchData::BatchedVertex &curTransform = *itr;
  1213. for( S32 i = 0; i < curTransform.transformCount; i++ )
  1214. {
  1215. const BatchData::TransformOp &transformOp = curTransform.transform[i];
  1216. // Find the proper batched transform, and add this vertex/weight to the
  1217. // list of verts affected by the transform
  1218. BatchData::BatchedTransform *bt = batchData.transformBatchOperations.retreive(transformOp.transformIndex);
  1219. if(!bt)
  1220. {
  1221. bt = new BatchData::BatchedTransform;
  1222. batchData.transformBatchOperations.insert(bt, transformOp.transformIndex);
  1223. bt->_tmpVec = new Vector<BatchData::BatchedVertWeight>;
  1224. batchData.transformKeys.push_back(transformOp.transformIndex);
  1225. }
  1226. bt->_tmpVec->increment();
  1227. bt->_tmpVec->last().vert = batchData.initialVerts[curTransform.vertexIndex];
  1228. bt->_tmpVec->last().normal = batchData.initialNorms[curTransform.vertexIndex];
  1229. bt->_tmpVec->last().weight = transformOp.weight;
  1230. bt->_tmpVec->last().vidx = curTransform.vertexIndex;
  1231. }
  1232. }
  1233. // Now iterate the resulting operations and convert the vectors to aligned
  1234. // memory locations
  1235. const S32 numBatchOps = batchData.transformKeys.size();
  1236. for(S32 i = 0; i < numBatchOps; i++)
  1237. {
  1238. BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(batchData.transformKeys[i]);
  1239. const S32 numVerts = curTransform._tmpVec->size();
  1240. // Allocate a chunk of aligned memory and copy in values
  1241. curTransform.numElements = numVerts;
  1242. curTransform.alignedMem = reinterpret_cast<BatchData::BatchedVertWeight *>(dMalloc_aligned(sizeof(BatchData::BatchedVertWeight) * numVerts, 16));
  1243. AssertFatal(curTransform.alignedMem, "Aligned malloc failed! Debug!");
  1244. constructArrayInPlace(curTransform.alignedMem, numVerts);
  1245. dMemcpy(curTransform.alignedMem, curTransform._tmpVec->address(), numVerts * sizeof(BatchData::BatchedVertWeight));
  1246. // Now free the vector memory
  1247. delete curTransform._tmpVec;
  1248. curTransform._tmpVec = NULL;
  1249. }
  1250. // Now sort the batch data so that the skin function writes close to linear output
  1251. for(S32 i = 0; i < numBatchOps; i++)
  1252. {
  1253. BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(batchData.transformKeys[i]);
  1254. dQsort(curTransform.alignedMem, curTransform.numElements, sizeof(BatchData::BatchedVertWeight), _sort_BatchedVertWeight);
  1255. }
  1256. #endif
  1257. }
  1258. void TSSkinMesh::render( TSVertexBufferHandle &instanceVB, GFXPrimitiveBufferHandle &instancePB )
  1259. {
  1260. innerRender( instanceVB, instancePB );
  1261. }
  1262. void TSSkinMesh::render( TSMaterialList *materials,
  1263. const TSRenderState &rdata,
  1264. bool isSkinDirty,
  1265. const Vector<MatrixF> &transforms,
  1266. TSVertexBufferHandle &vertexBuffer,
  1267. GFXPrimitiveBufferHandle &primitiveBuffer )
  1268. {
  1269. PROFILE_SCOPE(TSSkinMesh_render);
  1270. if( mNumVerts == 0 )
  1271. return;
  1272. // Initialize the vertex data if it needs it
  1273. if(!mVertexData.isReady() )
  1274. _convertToAlignedMeshData(mVertexData, batchData.initialVerts, batchData.initialNorms);
  1275. AssertFatal(mVertexData.size() == mNumVerts, "Vert # mismatch");
  1276. // Initialize the skin batch if that isn't ready
  1277. if(!batchDataInitialized)
  1278. createBatchData();
  1279. const bool vertsChanged = vertexBuffer.isNull() || vertexBuffer->mNumVerts != mNumVerts;
  1280. const bool primsChanged = primitiveBuffer.isNull() || primitiveBuffer->mIndexCount != indices.size();
  1281. if ( primsChanged || vertsChanged || isSkinDirty )
  1282. {
  1283. // Perform skinning
  1284. updateSkin( transforms, vertexBuffer, primitiveBuffer );
  1285. // Update GFX vertex buffer
  1286. _createVBIB( vertexBuffer, primitiveBuffer );
  1287. }
  1288. // render...
  1289. innerRender( materials, rdata, vertexBuffer, primitiveBuffer );
  1290. }
  1291. bool TSSkinMesh::buildPolyList( S32 frame, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  1292. {
  1293. // UpdateSkin() here may not be needed...
  1294. // we don't capture skinned
  1295. // verts in the polylist.
  1296. // update verts and normals...
  1297. //if( !smGlowPass && !smRefractPass )
  1298. // updateSkin();
  1299. // render...
  1300. //Parent::buildPolyList( frame,polyList,surfaceKey, materials );
  1301. return false;
  1302. }
  1303. bool TSSkinMesh::castRay( S32 frame, const Point3F &start, const Point3F &end, RayInfo *rayInfo, TSMaterialList *materials )
  1304. {
  1305. TORQUE_UNUSED(frame);
  1306. TORQUE_UNUSED(start);
  1307. TORQUE_UNUSED(end);
  1308. TORQUE_UNUSED(rayInfo);
  1309. TORQUE_UNUSED(materials);
  1310. return false;
  1311. }
  1312. bool TSSkinMesh::buildConvexHull()
  1313. {
  1314. return false; // no error, but we don't do anything either...
  1315. }
  1316. void TSSkinMesh::computeBounds( const MatrixF &transform, Box3F &bounds, S32 frame, Point3F *center, F32 *radius )
  1317. {
  1318. TORQUE_UNUSED(frame);
  1319. if (frame < 0)
  1320. {
  1321. // Use unskinned verts
  1322. TSMesh::computeBounds( batchData.initialVerts.address(), batchData.initialVerts.size(), sizeof(Point3F), transform, bounds, center, radius );
  1323. }
  1324. else
  1325. {
  1326. Point3F *vertStart = reinterpret_cast<Point3F *>(mVertexData.address());
  1327. TSMesh::computeBounds( vertStart, mVertexData.size(), mVertexData.vertSize(), transform, bounds, center, radius );
  1328. }
  1329. }
  1330. //-----------------------------------------------------
  1331. // encoded normals
  1332. //-----------------------------------------------------
  1333. const Point3F TSMesh::smU8ToNormalTable[] =
  1334. {
  1335. Point3F( 0.565061f, -0.270644f, -0.779396f ),
  1336. Point3F( -0.309804f, -0.731114f, 0.607860f ),
  1337. Point3F( -0.867412f, 0.472957f, 0.154619f ),
  1338. Point3F( -0.757488f, 0.498188f, -0.421925f ),
  1339. Point3F( 0.306834f, -0.915340f, 0.260778f ),
  1340. Point3F( 0.098754f, 0.639153f, -0.762713f ),
  1341. Point3F( 0.713706f, -0.558862f, -0.422252f ),
  1342. Point3F( -0.890431f, -0.407603f, -0.202466f ),
  1343. Point3F( 0.848050f, -0.487612f, -0.207475f ),
  1344. Point3F( -0.232226f, 0.776855f, 0.585293f ),
  1345. Point3F( -0.940195f, 0.304490f, -0.152706f ),
  1346. Point3F( 0.602019f, -0.491878f, -0.628991f ),
  1347. Point3F( -0.096835f, -0.494354f, -0.863850f ),
  1348. Point3F( 0.026630f, -0.323659f, -0.945799f ),
  1349. Point3F( 0.019208f, 0.909386f, 0.415510f ),
  1350. Point3F( 0.854440f, 0.491730f, 0.167731f ),
  1351. Point3F( -0.418835f, 0.866521f, -0.271512f ),
  1352. Point3F( 0.465024f, 0.409667f, 0.784809f ),
  1353. Point3F( -0.674391f, -0.691087f, -0.259992f ),
  1354. Point3F( 0.303858f, -0.869270f, -0.389922f ),
  1355. Point3F( 0.991333f, 0.090061f, -0.095640f ),
  1356. Point3F( -0.275924f, -0.369550f, 0.887298f ),
  1357. Point3F( 0.426545f, -0.465962f, 0.775202f ),
  1358. Point3F( -0.482741f, -0.873278f, -0.065920f ),
  1359. Point3F( 0.063616f, 0.932012f, -0.356800f ),
  1360. Point3F( 0.624786f, -0.061315f, 0.778385f ),
  1361. Point3F( -0.530300f, 0.416850f, 0.738253f ),
  1362. Point3F( 0.312144f, -0.757028f, -0.573999f ),
  1363. Point3F( 0.399288f, -0.587091f, -0.704197f ),
  1364. Point3F( -0.132698f, 0.482877f, 0.865576f ),
  1365. Point3F( 0.950966f, 0.306530f, 0.041268f ),
  1366. Point3F( -0.015923f, -0.144300f, 0.989406f ),
  1367. Point3F( -0.407522f, -0.854193f, 0.322925f ),
  1368. Point3F( -0.932398f, 0.220464f, 0.286408f ),
  1369. Point3F( 0.477509f, 0.876580f, 0.059936f ),
  1370. Point3F( 0.337133f, 0.932606f, -0.128796f ),
  1371. Point3F( -0.638117f, 0.199338f, 0.743687f ),
  1372. Point3F( -0.677454f, 0.445349f, 0.585423f ),
  1373. Point3F( -0.446715f, 0.889059f, -0.100099f ),
  1374. Point3F( -0.410024f, 0.909168f, 0.072759f ),
  1375. Point3F( 0.708462f, 0.702103f, -0.071641f ),
  1376. Point3F( -0.048801f, -0.903683f, -0.425411f ),
  1377. Point3F( -0.513681f, -0.646901f, 0.563606f ),
  1378. Point3F( -0.080022f, 0.000676f, -0.996793f ),
  1379. Point3F( 0.066966f, -0.991150f, -0.114615f ),
  1380. Point3F( -0.245220f, 0.639318f, -0.728793f ),
  1381. Point3F( 0.250978f, 0.855979f, 0.452006f ),
  1382. Point3F( -0.123547f, 0.982443f, -0.139791f ),
  1383. Point3F( -0.794825f, 0.030254f, -0.606084f ),
  1384. Point3F( -0.772905f, 0.547941f, 0.319967f ),
  1385. Point3F( 0.916347f, 0.369614f, -0.153928f ),
  1386. Point3F( -0.388203f, 0.105395f, 0.915527f ),
  1387. Point3F( -0.700468f, -0.709334f, 0.078677f ),
  1388. Point3F( -0.816193f, 0.390455f, 0.425880f ),
  1389. Point3F( -0.043007f, 0.769222f, -0.637533f ),
  1390. Point3F( 0.911444f, 0.113150f, 0.395560f ),
  1391. Point3F( 0.845801f, 0.156091f, -0.510153f ),
  1392. Point3F( 0.829801f, -0.029340f, 0.557287f ),
  1393. Point3F( 0.259529f, 0.416263f, 0.871418f ),
  1394. Point3F( 0.231128f, -0.845982f, 0.480515f ),
  1395. Point3F( -0.626203f, -0.646168f, 0.436277f ),
  1396. Point3F( -0.197047f, -0.065791f, 0.978184f ),
  1397. Point3F( -0.255692f, -0.637488f, -0.726794f ),
  1398. Point3F( 0.530662f, -0.844385f, -0.073567f ),
  1399. Point3F( -0.779887f, 0.617067f, -0.104899f ),
  1400. Point3F( 0.739908f, 0.113984f, 0.662982f ),
  1401. Point3F( -0.218801f, 0.930194f, -0.294729f ),
  1402. Point3F( -0.374231f, 0.818666f, 0.435589f ),
  1403. Point3F( -0.720250f, -0.028285f, 0.693137f ),
  1404. Point3F( 0.075389f, 0.415049f, 0.906670f ),
  1405. Point3F( -0.539724f, -0.106620f, 0.835063f ),
  1406. Point3F( -0.452612f, -0.754669f, -0.474991f ),
  1407. Point3F( 0.682822f, 0.581234f, -0.442629f ),
  1408. Point3F( 0.002435f, -0.618462f, -0.785811f ),
  1409. Point3F( -0.397631f, 0.110766f, -0.910835f ),
  1410. Point3F( 0.133935f, -0.985438f, 0.104754f ),
  1411. Point3F( 0.759098f, -0.608004f, 0.232595f ),
  1412. Point3F( -0.825239f, -0.256087f, 0.503388f ),
  1413. Point3F( 0.101693f, -0.565568f, 0.818408f ),
  1414. Point3F( 0.386377f, 0.793546f, -0.470104f ),
  1415. Point3F( -0.520516f, -0.840690f, 0.149346f ),
  1416. Point3F( -0.784549f, -0.479672f, 0.392935f ),
  1417. Point3F( -0.325322f, -0.927581f, -0.183735f ),
  1418. Point3F( -0.069294f, -0.428541f, 0.900861f ),
  1419. Point3F( 0.993354f, -0.115023f, -0.004288f ),
  1420. Point3F( -0.123896f, -0.700568f, 0.702747f ),
  1421. Point3F( -0.438031f, -0.120880f, -0.890795f ),
  1422. Point3F( 0.063314f, 0.813233f, 0.578484f ),
  1423. Point3F( 0.322045f, 0.889086f, -0.325289f ),
  1424. Point3F( -0.133521f, 0.875063f, -0.465228f ),
  1425. Point3F( 0.637155f, 0.564814f, 0.524422f ),
  1426. Point3F( 0.260092f, -0.669353f, 0.695930f ),
  1427. Point3F( 0.953195f, 0.040485f, -0.299634f ),
  1428. Point3F( -0.840665f, -0.076509f, 0.536124f ),
  1429. Point3F( -0.971350f, 0.202093f, 0.125047f ),
  1430. Point3F( -0.804307f, -0.396312f, -0.442749f ),
  1431. Point3F( -0.936746f, 0.069572f, 0.343027f ),
  1432. Point3F( 0.426545f, -0.465962f, 0.775202f ),
  1433. Point3F( 0.794542f, -0.227450f, 0.563000f ),
  1434. Point3F( -0.892172f, 0.091169f, -0.442399f ),
  1435. Point3F( -0.312654f, 0.541264f, 0.780564f ),
  1436. Point3F( 0.590603f, -0.735618f, -0.331743f ),
  1437. Point3F( -0.098040f, -0.986713f, 0.129558f ),
  1438. Point3F( 0.569646f, 0.283078f, -0.771603f ),
  1439. Point3F( 0.431051f, -0.407385f, -0.805129f ),
  1440. Point3F( -0.162087f, -0.938749f, -0.304104f ),
  1441. Point3F( 0.241533f, -0.359509f, 0.901341f ),
  1442. Point3F( -0.576191f, 0.614939f, 0.538380f ),
  1443. Point3F( -0.025110f, 0.085740f, 0.996001f ),
  1444. Point3F( -0.352693f, -0.198168f, 0.914515f ),
  1445. Point3F( -0.604577f, 0.700711f, 0.378802f ),
  1446. Point3F( 0.465024f, 0.409667f, 0.784809f ),
  1447. Point3F( -0.254684f, -0.030474f, -0.966544f ),
  1448. Point3F( -0.604789f, 0.791809f, 0.085259f ),
  1449. Point3F( -0.705147f, -0.399298f, 0.585943f ),
  1450. Point3F( 0.185691f, 0.017236f, -0.982457f ),
  1451. Point3F( 0.044588f, 0.973094f, 0.226052f ),
  1452. Point3F( -0.405463f, 0.642367f, 0.650357f ),
  1453. Point3F( -0.563959f, 0.599136f, -0.568319f ),
  1454. Point3F( 0.367162f, -0.072253f, -0.927347f ),
  1455. Point3F( 0.960429f, -0.213570f, -0.178783f ),
  1456. Point3F( -0.192629f, 0.906005f, 0.376893f ),
  1457. Point3F( -0.199718f, -0.359865f, -0.911378f ),
  1458. Point3F( 0.485072f, 0.121233f, -0.866030f ),
  1459. Point3F( 0.467163f, -0.874294f, 0.131792f ),
  1460. Point3F( -0.638953f, -0.716603f, 0.279677f ),
  1461. Point3F( -0.622710f, 0.047813f, -0.780990f ),
  1462. Point3F( 0.828724f, -0.054433f, -0.557004f ),
  1463. Point3F( 0.130241f, 0.991080f, 0.028245f ),
  1464. Point3F( 0.310995f, -0.950076f, -0.025242f ),
  1465. Point3F( 0.818118f, 0.275336f, 0.504850f ),
  1466. Point3F( 0.676328f, 0.387023f, 0.626733f ),
  1467. Point3F( -0.100433f, 0.495114f, -0.863004f ),
  1468. Point3F( -0.949609f, -0.240681f, -0.200786f ),
  1469. Point3F( -0.102610f, 0.261831f, -0.959644f ),
  1470. Point3F( -0.845732f, -0.493136f, 0.203850f ),
  1471. Point3F( 0.672617f, -0.738838f, 0.041290f ),
  1472. Point3F( 0.380465f, 0.875938f, 0.296613f ),
  1473. Point3F( -0.811223f, 0.262027f, -0.522742f ),
  1474. Point3F( -0.074423f, -0.775670f, -0.626736f ),
  1475. Point3F( -0.286499f, 0.755850f, -0.588735f ),
  1476. Point3F( 0.291182f, -0.276189f, -0.915933f ),
  1477. Point3F( -0.638117f, 0.199338f, 0.743687f ),
  1478. Point3F( 0.439922f, -0.864433f, -0.243359f ),
  1479. Point3F( 0.177649f, 0.206919f, 0.962094f ),
  1480. Point3F( 0.277107f, 0.948521f, 0.153361f ),
  1481. Point3F( 0.507629f, 0.661918f, -0.551523f ),
  1482. Point3F( -0.503110f, -0.579308f, -0.641313f ),
  1483. Point3F( 0.600522f, 0.736495f, -0.311364f ),
  1484. Point3F( -0.691096f, -0.715301f, -0.103592f ),
  1485. Point3F( -0.041083f, -0.858497f, 0.511171f ),
  1486. Point3F( 0.207773f, -0.480062f, -0.852274f ),
  1487. Point3F( 0.795719f, 0.464614f, 0.388543f ),
  1488. Point3F( -0.100433f, 0.495114f, -0.863004f ),
  1489. Point3F( 0.703249f, 0.065157f, -0.707951f ),
  1490. Point3F( -0.324171f, -0.941112f, 0.096024f ),
  1491. Point3F( -0.134933f, -0.940212f, 0.312722f ),
  1492. Point3F( -0.438240f, 0.752088f, -0.492249f ),
  1493. Point3F( 0.964762f, -0.198855f, 0.172311f ),
  1494. Point3F( -0.831799f, 0.196807f, 0.519015f ),
  1495. Point3F( -0.508008f, 0.819902f, 0.263986f ),
  1496. Point3F( 0.471075f, -0.001146f, 0.882092f ),
  1497. Point3F( 0.919512f, 0.246162f, -0.306435f ),
  1498. Point3F( -0.960050f, 0.279828f, -0.001187f ),
  1499. Point3F( 0.110232f, -0.847535f, -0.519165f ),
  1500. Point3F( 0.208229f, 0.697360f, 0.685806f ),
  1501. Point3F( -0.199680f, -0.560621f, 0.803637f ),
  1502. Point3F( 0.170135f, -0.679985f, -0.713214f ),
  1503. Point3F( 0.758371f, -0.494907f, 0.424195f ),
  1504. Point3F( 0.077734f, -0.755978f, 0.649965f ),
  1505. Point3F( 0.612831f, -0.672475f, 0.414987f ),
  1506. Point3F( 0.142776f, 0.836698f, -0.528726f ),
  1507. Point3F( -0.765185f, 0.635778f, 0.101382f ),
  1508. Point3F( 0.669873f, -0.419737f, 0.612447f ),
  1509. Point3F( 0.593549f, 0.194879f, 0.780847f ),
  1510. Point3F( 0.646930f, 0.752173f, 0.125368f ),
  1511. Point3F( 0.837721f, 0.545266f, -0.030127f ),
  1512. Point3F( 0.541505f, 0.768070f, 0.341820f ),
  1513. Point3F( 0.760679f, -0.365715f, -0.536301f ),
  1514. Point3F( 0.381516f, 0.640377f, 0.666605f ),
  1515. Point3F( 0.565794f, -0.072415f, -0.821361f ),
  1516. Point3F( -0.466072f, -0.401588f, 0.788356f ),
  1517. Point3F( 0.987146f, 0.096290f, 0.127560f ),
  1518. Point3F( 0.509709f, -0.688886f, -0.515396f ),
  1519. Point3F( -0.135132f, -0.988046f, -0.074192f ),
  1520. Point3F( 0.600499f, 0.476471f, -0.642166f ),
  1521. Point3F( -0.732326f, -0.275320f, -0.622815f ),
  1522. Point3F( -0.881141f, -0.470404f, 0.048078f ),
  1523. Point3F( 0.051548f, 0.601042f, 0.797553f ),
  1524. Point3F( 0.402027f, -0.763183f, 0.505891f ),
  1525. Point3F( 0.404233f, -0.208288f, 0.890624f ),
  1526. Point3F( -0.311793f, 0.343843f, 0.885752f ),
  1527. Point3F( 0.098132f, -0.937014f, 0.335223f ),
  1528. Point3F( 0.537158f, 0.830585f, -0.146936f ),
  1529. Point3F( 0.725277f, 0.298172f, -0.620538f ),
  1530. Point3F( -0.882025f, 0.342976f, -0.323110f ),
  1531. Point3F( -0.668829f, 0.424296f, -0.610443f ),
  1532. Point3F( -0.408835f, -0.476442f, -0.778368f ),
  1533. Point3F( 0.809472f, 0.397249f, -0.432375f ),
  1534. Point3F( -0.909184f, -0.205938f, -0.361903f ),
  1535. Point3F( 0.866930f, -0.347934f, -0.356895f ),
  1536. Point3F( 0.911660f, -0.141281f, -0.385897f ),
  1537. Point3F( -0.431404f, -0.844074f, -0.318480f ),
  1538. Point3F( -0.950593f, -0.073496f, 0.301614f ),
  1539. Point3F( -0.719716f, 0.626915f, -0.298305f ),
  1540. Point3F( -0.779887f, 0.617067f, -0.104899f ),
  1541. Point3F( -0.475899f, -0.542630f, 0.692151f ),
  1542. Point3F( 0.081952f, -0.157248f, -0.984153f ),
  1543. Point3F( 0.923990f, -0.381662f, -0.024025f ),
  1544. Point3F( -0.957998f, 0.120979f, -0.260008f ),
  1545. Point3F( 0.306601f, 0.227975f, -0.924134f ),
  1546. Point3F( -0.141244f, 0.989182f, 0.039601f ),
  1547. Point3F( 0.077097f, 0.186288f, -0.979466f ),
  1548. Point3F( -0.630407f, -0.259801f, 0.731499f ),
  1549. Point3F( 0.718150f, 0.637408f, 0.279233f ),
  1550. Point3F( 0.340946f, 0.110494f, 0.933567f ),
  1551. Point3F( -0.396671f, 0.503020f, -0.767869f ),
  1552. Point3F( 0.636943f, -0.245005f, 0.730942f ),
  1553. Point3F( -0.849605f, -0.518660f, -0.095724f ),
  1554. Point3F( -0.388203f, 0.105395f, 0.915527f ),
  1555. Point3F( -0.280671f, -0.776541f, -0.564099f ),
  1556. Point3F( -0.601680f, 0.215451f, -0.769131f ),
  1557. Point3F( -0.660112f, -0.632371f, -0.405412f ),
  1558. Point3F( 0.921096f, 0.284072f, 0.266242f ),
  1559. Point3F( 0.074850f, -0.300846f, 0.950731f ),
  1560. Point3F( 0.943952f, -0.067062f, 0.323198f ),
  1561. Point3F( -0.917838f, -0.254589f, 0.304561f ),
  1562. Point3F( 0.889843f, -0.409008f, 0.202219f ),
  1563. Point3F( -0.565849f, 0.753721f, -0.334246f ),
  1564. Point3F( 0.791460f, 0.555918f, -0.254060f ),
  1565. Point3F( 0.261936f, 0.703590f, -0.660568f ),
  1566. Point3F( -0.234406f, 0.952084f, 0.196444f ),
  1567. Point3F( 0.111205f, 0.979492f, -0.168014f ),
  1568. Point3F( -0.869844f, -0.109095f, -0.481113f ),
  1569. Point3F( -0.337728f, -0.269701f, -0.901777f ),
  1570. Point3F( 0.366793f, 0.408875f, -0.835634f ),
  1571. Point3F( -0.098749f, 0.261316f, 0.960189f ),
  1572. Point3F( -0.272379f, -0.847100f, 0.456324f ),
  1573. Point3F( -0.319506f, 0.287444f, -0.902935f ),
  1574. Point3F( 0.873383f, -0.294109f, 0.388203f ),
  1575. Point3F( -0.088950f, 0.710450f, 0.698104f ),
  1576. Point3F( 0.551238f, -0.786552f, 0.278340f ),
  1577. Point3F( 0.724436f, -0.663575f, -0.186712f ),
  1578. Point3F( 0.529741f, -0.606539f, 0.592861f ),
  1579. Point3F( -0.949743f, -0.282514f, 0.134809f ),
  1580. Point3F( 0.155047f, 0.419442f, -0.894443f ),
  1581. Point3F( -0.562653f, -0.329139f, -0.758346f ),
  1582. Point3F( 0.816407f, -0.576953f, 0.024576f ),
  1583. Point3F( 0.178550f, -0.950242f, -0.255266f ),
  1584. Point3F( 0.479571f, 0.706691f, 0.520192f ),
  1585. Point3F( 0.391687f, 0.559884f, -0.730145f ),
  1586. Point3F( 0.724872f, -0.205570f, -0.657496f ),
  1587. Point3F( -0.663196f, -0.517587f, -0.540624f ),
  1588. Point3F( -0.660054f, -0.122486f, -0.741165f ),
  1589. Point3F( -0.531989f, 0.374711f, -0.759328f ),
  1590. Point3F( 0.194979f, -0.059120f, 0.979024f )
  1591. };
  1592. U8 TSMesh::encodeNormal( const Point3F &normal )
  1593. {
  1594. U8 bestIndex = 0;
  1595. F32 bestDot = -10E30f;
  1596. for ( U32 i = 0; i < 256; i++ )
  1597. {
  1598. F32 dot = mDot( normal, smU8ToNormalTable[i] );
  1599. if ( dot > bestDot )
  1600. {
  1601. bestIndex = i;
  1602. bestDot = dot;
  1603. }
  1604. }
  1605. return bestIndex;
  1606. }
  1607. //-----------------------------------------------------
  1608. // TSMesh assemble from/ dissemble to memory buffer
  1609. //-----------------------------------------------------
  1610. #define tsalloc TSShape::smTSAlloc
  1611. TSMesh* TSMesh::assembleMesh( U32 meshType, bool skip )
  1612. {
  1613. static TSMesh tempStandardMesh;
  1614. static TSSkinMesh tempSkinMesh;
  1615. static TSDecalMesh tempDecalMesh;
  1616. static TSSortedMesh tempSortedMesh;
  1617. bool justSize = skip || !tsalloc.allocShape32(0); // if this returns NULL, we're just sizing memory block
  1618. // a little funny business because we pretend decals are derived from meshes
  1619. S32 * ret = NULL;
  1620. TSMesh * mesh = NULL;
  1621. TSDecalMesh * decal = NULL;
  1622. if ( justSize )
  1623. {
  1624. switch ( meshType )
  1625. {
  1626. case StandardMeshType :
  1627. {
  1628. ret = (S32*)&tempStandardMesh;
  1629. mesh = &tempStandardMesh;
  1630. tsalloc.allocShape32( sizeof(TSMesh) >> 2 );
  1631. break;
  1632. }
  1633. case SkinMeshType :
  1634. {
  1635. ret = (S32*)&tempSkinMesh;
  1636. mesh = &tempSkinMesh;
  1637. tsalloc.allocShape32( sizeof(TSSkinMesh) >> 2 );
  1638. break;
  1639. }
  1640. case DecalMeshType :
  1641. {
  1642. ret = (S32*)&tempDecalMesh;
  1643. decal = &tempDecalMesh;
  1644. tsalloc.allocShape32( sizeof(TSDecalMesh) >> 2 );
  1645. break;
  1646. }
  1647. case SortedMeshType :
  1648. {
  1649. ret = (S32*)&tempSortedMesh;
  1650. mesh = &tempSortedMesh;
  1651. tsalloc.allocShape32( sizeof(TSSortedMesh) >> 2 );
  1652. break;
  1653. }
  1654. }
  1655. }
  1656. else
  1657. {
  1658. switch ( meshType )
  1659. {
  1660. case StandardMeshType :
  1661. {
  1662. ret = tsalloc.allocShape32( sizeof(TSMesh) >> 2 );
  1663. constructInPlace( (TSMesh*)ret );
  1664. mesh = (TSMesh*)ret;
  1665. break;
  1666. }
  1667. case SkinMeshType :
  1668. {
  1669. ret = tsalloc.allocShape32( sizeof(TSSkinMesh) >> 2 );
  1670. constructInPlace( (TSSkinMesh*)ret );
  1671. mesh = (TSSkinMesh*)ret;
  1672. break;
  1673. }
  1674. case DecalMeshType :
  1675. {
  1676. ret = tsalloc.allocShape32( sizeof(TSDecalMesh) >> 2 );
  1677. constructInPlace((TSDecalMesh*)ret);
  1678. decal = (TSDecalMesh*)ret;
  1679. break;
  1680. }
  1681. case SortedMeshType :
  1682. {
  1683. ret = tsalloc.allocShape32( sizeof(TSSortedMesh) >> 2 );
  1684. constructInPlace( (TSSortedMesh*)ret );
  1685. mesh = (TSSortedMesh*)ret;
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. tsalloc.setSkipMode( skip );
  1691. if ( mesh )
  1692. mesh->assemble( skip );
  1693. if ( decal )
  1694. decal->assemble( skip );
  1695. tsalloc.setSkipMode( false );
  1696. return (TSMesh*)ret;
  1697. }
  1698. void TSMesh::convertToTris( const TSDrawPrimitive *primitivesIn,
  1699. const S32 *indicesIn,
  1700. S32 numPrimIn,
  1701. S32 &numPrimOut,
  1702. S32 &numIndicesOut,
  1703. TSDrawPrimitive *primitivesOut,
  1704. S32 *indicesOut ) const
  1705. {
  1706. S32 prevMaterial = -99999;
  1707. TSDrawPrimitive * newDraw = NULL;
  1708. numPrimOut = 0;
  1709. numIndicesOut = 0;
  1710. for ( S32 i = 0; i < numPrimIn; i++ )
  1711. {
  1712. S32 newMat = primitivesIn[i].matIndex;
  1713. newMat &= ~TSDrawPrimitive::TypeMask;
  1714. U32 start = primitivesIn[i].start;
  1715. U32 prevStart = (i > 0) ? primitivesIn[i-1].start : start;
  1716. U32 numElements = primitivesIn[i].numElements;
  1717. // Add a new primitive if changing materials, or if this primitive
  1718. // indexes vertices in a different 16-bit range
  1719. if ( ( newMat != prevMaterial ) ||
  1720. ((indicesIn[prevStart] ^ indicesIn[start]) & 0xFFFF0000) )
  1721. {
  1722. if ( primitivesOut )
  1723. {
  1724. newDraw = &primitivesOut[numPrimOut];
  1725. newDraw->start = numIndicesOut;
  1726. newDraw->numElements = 0;
  1727. newDraw->matIndex = newMat | TSDrawPrimitive::Triangles;
  1728. }
  1729. numPrimOut++;
  1730. prevMaterial = newMat;
  1731. }
  1732. // gonna depend on what kind of primitive it is...
  1733. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  1734. {
  1735. for ( S32 j = 0; j < numElements; j += 3 )
  1736. {
  1737. if ( indicesOut )
  1738. {
  1739. indicesOut[numIndicesOut + 0] = indicesIn[start + j + 0];
  1740. indicesOut[numIndicesOut + 1] = indicesIn[start + j + 1];
  1741. indicesOut[numIndicesOut + 2] = indicesIn[start + j + 2];
  1742. }
  1743. if ( newDraw )
  1744. newDraw->numElements += 3;
  1745. numIndicesOut += 3;
  1746. }
  1747. }
  1748. else
  1749. {
  1750. U32 idx0 = indicesIn[start + 0];
  1751. U32 idx1;
  1752. U32 idx2 = indicesIn[start + 1];
  1753. U32 * nextIdx = &idx1;
  1754. for ( S32 j = 2; j < numElements; j++ )
  1755. {
  1756. *nextIdx = idx2;
  1757. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1758. idx2 = indicesIn[start + j];
  1759. if ( idx0 == idx1 || idx1 == idx2 || idx2 == idx0 )
  1760. continue;
  1761. if ( indicesOut )
  1762. {
  1763. indicesOut[numIndicesOut+0] = idx0;
  1764. indicesOut[numIndicesOut+1] = idx1;
  1765. indicesOut[numIndicesOut+2] = idx2;
  1766. }
  1767. if ( newDraw )
  1768. newDraw->numElements += 3;
  1769. numIndicesOut += 3;
  1770. }
  1771. }
  1772. }
  1773. }
  1774. void unwindStrip( const S32 * indices, S32 numElements, Vector<S32> &triIndices )
  1775. {
  1776. U32 idx0 = indices[0];
  1777. U32 idx1;
  1778. U32 idx2 = indices[1];
  1779. U32 * nextIdx = &idx1;
  1780. for ( S32 j = 2; j < numElements; j++ )
  1781. {
  1782. *nextIdx = idx2;
  1783. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1784. idx2 = indices[j];
  1785. if ( idx0 == idx1 || idx1 == idx2 || idx2 == idx0 )
  1786. continue;
  1787. triIndices.push_back( idx0 );
  1788. triIndices.push_back( idx1 );
  1789. triIndices.push_back( idx2 );
  1790. }
  1791. }
  1792. void TSMesh::convertToSingleStrip( const TSDrawPrimitive *primitivesIn,
  1793. const S32 *indicesIn,
  1794. S32 numPrimIn,
  1795. S32 &numPrimOut,
  1796. S32 &numIndicesOut,
  1797. TSDrawPrimitive *primitivesOut,
  1798. S32 *indicesOut ) const
  1799. {
  1800. S32 prevMaterial = -99999;
  1801. TSDrawPrimitive * newDraw = NULL;
  1802. TSDrawPrimitive * newTris = NULL;
  1803. Vector<S32> triIndices;
  1804. S32 curDrawOut = 0;
  1805. numPrimOut = 0;
  1806. numIndicesOut = 0;
  1807. for ( S32 i = 0; i < numPrimIn; i++ )
  1808. {
  1809. S32 newMat = primitivesIn[i].matIndex;
  1810. U32 start = primitivesIn[i].start;
  1811. U32 prevStart = (i > 0) ? primitivesIn[i-1].start : start;
  1812. U32 numElements = primitivesIn[i].numElements;
  1813. // Add a new primitive if changing materials, or if this primitive
  1814. // indexes vertices in a different 16-bit range
  1815. if ( ( newMat != prevMaterial ) ||
  1816. ((indicesIn[prevStart] ^ indicesIn[start]) & 0xFFFF0000) )
  1817. {
  1818. // before adding the new primitive, transfer triangle indices
  1819. if ( triIndices.size() )
  1820. {
  1821. if ( newTris && indicesOut )
  1822. {
  1823. newTris->start = numIndicesOut;
  1824. newTris->numElements = triIndices.size();
  1825. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  1826. }
  1827. numIndicesOut += triIndices.size();
  1828. triIndices.clear();
  1829. newTris = NULL;
  1830. }
  1831. if ( primitivesOut )
  1832. {
  1833. newDraw = &primitivesOut[numPrimOut];
  1834. newDraw->start = numIndicesOut;
  1835. newDraw->numElements = 0;
  1836. newDraw->matIndex = newMat;
  1837. }
  1838. numPrimOut++;
  1839. curDrawOut = 0;
  1840. prevMaterial = newMat;
  1841. }
  1842. // gonna depend on what kind of primitive it is...
  1843. // from above we know it's the same kind as the one we're building...
  1844. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  1845. {
  1846. // triangles primitive...add to it
  1847. for ( S32 j = 0; j < numElements; j += 3 )
  1848. {
  1849. if ( indicesOut )
  1850. {
  1851. indicesOut[numIndicesOut + 0] = indicesIn[start + j + 0];
  1852. indicesOut[numIndicesOut + 1] = indicesIn[start + j + 1];
  1853. indicesOut[numIndicesOut + 2] = indicesIn[start + j + 2];
  1854. }
  1855. if ( newDraw )
  1856. newDraw->numElements += 3;
  1857. numIndicesOut += 3;
  1858. }
  1859. }
  1860. else
  1861. {
  1862. // strip primitive...
  1863. // if numElements less than smSmallestStripSize, add to triangles...
  1864. if ( numElements < smMinStripSize + 2 )
  1865. {
  1866. // put triangle indices aside until material changes...
  1867. if ( triIndices.empty() )
  1868. {
  1869. // set up for new triangle primitive and add it if we are copying data right now
  1870. if ( primitivesOut )
  1871. {
  1872. newTris = &primitivesOut[numPrimOut];
  1873. newTris->matIndex = newMat;
  1874. newTris->matIndex &= ~(TSDrawPrimitive::Triangles|TSDrawPrimitive::Strip);
  1875. newTris->matIndex |= TSDrawPrimitive::Triangles;
  1876. }
  1877. numPrimOut++;
  1878. }
  1879. unwindStrip( indicesIn + start, numElements, triIndices );
  1880. }
  1881. else
  1882. {
  1883. // strip primitive...add to it
  1884. if ( indicesOut )
  1885. {
  1886. if ( curDrawOut & 1 )
  1887. {
  1888. indicesOut[numIndicesOut + 0] = indicesOut[numIndicesOut - 1];
  1889. indicesOut[numIndicesOut + 1] = indicesOut[numIndicesOut - 1];
  1890. indicesOut[numIndicesOut + 2] = indicesIn[start];
  1891. dMemcpy(indicesOut+numIndicesOut+3,indicesIn+start,numElements*sizeof(U32));
  1892. }
  1893. else if ( curDrawOut )
  1894. {
  1895. indicesOut[numIndicesOut + 0] = indicesOut[numIndicesOut - 1];
  1896. indicesOut[numIndicesOut + 1] = indicesIn[start];
  1897. dMemcpy(indicesOut+numIndicesOut+2,indicesIn+start,numElements*sizeof(U32));
  1898. }
  1899. else
  1900. dMemcpy(indicesOut+numIndicesOut,indicesIn+start,numElements*sizeof(U32));
  1901. }
  1902. S32 added = numElements;
  1903. added += curDrawOut ? (curDrawOut&1 ? 3 : 2) : 0;
  1904. if ( newDraw )
  1905. newDraw->numElements += added;
  1906. numIndicesOut += added;
  1907. curDrawOut += added;
  1908. }
  1909. }
  1910. }
  1911. // spit out tris before leaving
  1912. // before adding the new primitive, transfer triangle indices
  1913. if ( triIndices.size() )
  1914. {
  1915. if ( newTris && indicesOut )
  1916. {
  1917. newTris->start = numIndicesOut;
  1918. newTris->numElements = triIndices.size();
  1919. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  1920. }
  1921. numIndicesOut += triIndices.size();
  1922. triIndices.clear();
  1923. newTris = NULL;
  1924. }
  1925. }
  1926. // this method does none of the converting that the above methods do, except that small strips are converted
  1927. // to triangle lists...
  1928. void TSMesh::leaveAsMultipleStrips( const TSDrawPrimitive *primitivesIn,
  1929. const S32 *indicesIn,
  1930. S32 numPrimIn,
  1931. S32 &numPrimOut,
  1932. S32 &numIndicesOut,
  1933. TSDrawPrimitive *primitivesOut,
  1934. S32 *indicesOut ) const
  1935. {
  1936. S32 prevMaterial = -99999;
  1937. TSDrawPrimitive * newDraw = NULL;
  1938. Vector<S32> triIndices;
  1939. numPrimOut = 0;
  1940. numIndicesOut = 0;
  1941. for ( S32 i = 0; i < numPrimIn; i++ )
  1942. {
  1943. S32 newMat = primitivesIn[i].matIndex;
  1944. U32 start = primitivesIn[i].start;
  1945. U32 prevStart = (i > 0) ? primitivesIn[i-1].start : start;
  1946. U32 numElements = primitivesIn[i].numElements;
  1947. // Add a new primitive if changing materials, or if this primitive
  1948. // indexes vertices in a different 16-bit range
  1949. if ( triIndices.size() &&
  1950. (( newMat != prevMaterial ) ||
  1951. ((indicesIn[prevStart] ^ indicesIn[start]) & 0xFFFF0000) ))
  1952. {
  1953. // material just changed and we have triangles lying around
  1954. // add primitive and indices for triangles and clear triIndices
  1955. if ( indicesOut )
  1956. {
  1957. TSDrawPrimitive * newTris = &primitivesOut[numPrimOut];
  1958. newTris->matIndex = prevMaterial;
  1959. newTris->matIndex &= ~(TSDrawPrimitive::Triangles|TSDrawPrimitive::Strip);
  1960. newTris->matIndex |= TSDrawPrimitive::Triangles;
  1961. newTris->start = numIndicesOut;
  1962. newTris->numElements = triIndices.size();
  1963. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  1964. }
  1965. numPrimOut++;
  1966. numIndicesOut += triIndices.size();
  1967. triIndices.clear();
  1968. }
  1969. // this is a little convoluted because this code was adapted from convertToSingleStrip
  1970. // but we will need a new primitive only if it is a triangle primitive coming in
  1971. // or we have more elements than the min strip size...
  1972. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles || numElements>=smMinStripSize+2)
  1973. {
  1974. if ( primitivesOut )
  1975. {
  1976. newDraw = &primitivesOut[numPrimOut];
  1977. newDraw->start = numIndicesOut;
  1978. newDraw->numElements = 0;
  1979. newDraw->matIndex = newMat;
  1980. }
  1981. numPrimOut++;
  1982. }
  1983. prevMaterial = newMat;
  1984. // gonna depend on what kind of primitive it is...
  1985. // from above we know it's the same kind as the one we're building...
  1986. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  1987. {
  1988. // triangles primitive...add to it
  1989. for ( S32 j = 0; j < numElements; j += 3 )
  1990. {
  1991. if ( indicesOut )
  1992. {
  1993. indicesOut[numIndicesOut + 0] = indicesIn[start + j + 0];
  1994. indicesOut[numIndicesOut + 1] = indicesIn[start + j + 1];
  1995. indicesOut[numIndicesOut + 2] = indicesIn[start + j + 2];
  1996. }
  1997. if ( newDraw )
  1998. newDraw->numElements += 3;
  1999. numIndicesOut += 3;
  2000. }
  2001. }
  2002. else
  2003. {
  2004. // strip primitive...
  2005. // if numElements less than smSmallestStripSize, add to triangles...
  2006. if ( numElements < smMinStripSize + 2 )
  2007. // put triangle indices aside until material changes...
  2008. unwindStrip( indicesIn + start, numElements, triIndices );
  2009. else
  2010. {
  2011. // strip primitive...add to it
  2012. if ( indicesOut )
  2013. dMemcpy(indicesOut+numIndicesOut,indicesIn+start,numElements*sizeof(U32));
  2014. if ( newDraw )
  2015. newDraw->numElements = numElements;
  2016. numIndicesOut += numElements;
  2017. }
  2018. }
  2019. }
  2020. // spit out tris before leaving
  2021. if ( triIndices.size() )
  2022. {
  2023. // material just changed and we have triangles lying around
  2024. // add primitive and indices for triangles and clear triIndices
  2025. if ( indicesOut )
  2026. {
  2027. TSDrawPrimitive *newTris = &primitivesOut[numPrimOut];
  2028. newTris->matIndex = prevMaterial;
  2029. newTris->matIndex &= ~(TSDrawPrimitive::Triangles|TSDrawPrimitive::Strip);
  2030. newTris->matIndex |= TSDrawPrimitive::Triangles;
  2031. newTris->start = numIndicesOut;
  2032. newTris->numElements = triIndices.size();
  2033. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  2034. }
  2035. numPrimOut++;
  2036. numIndicesOut += triIndices.size();
  2037. triIndices.clear();
  2038. }
  2039. }
  2040. // This method retrieves data that is shared (or possibly shared) between different meshes.
  2041. // This adds an extra step to the copying of data from the memory buffer to the shape data buffer.
  2042. // If we have no parentMesh, then we either return a pointer to the data in the memory buffer
  2043. // (in the case that we skip this mesh) or copy the data into the shape data buffer and return
  2044. // that pointer (in the case that we don't skip this mesh).
  2045. // If we do have a parent mesh, then we return a pointer to the data in the shape buffer,
  2046. // copying the data in there ourselves if our parent didn't already do it (i.e., if it was skipped).
  2047. S32 * TSMesh::getSharedData32( S32 parentMesh, S32 size, S32 **source, bool skip )
  2048. {
  2049. S32 * ptr;
  2050. if( parentMesh < 0 )
  2051. ptr = skip ? tsalloc.getPointer32( size ) : tsalloc.copyToShape32( size );
  2052. else
  2053. {
  2054. ptr = source[parentMesh];
  2055. // if we skipped the previous mesh (and we're not skipping this one) then
  2056. // we still need to copy points into the shape...
  2057. if ( !smDataCopied[parentMesh] && !skip )
  2058. {
  2059. S32 * tmp = ptr;
  2060. ptr = tsalloc.allocShape32( size );
  2061. if ( ptr && tmp )
  2062. dMemcpy(ptr, tmp, size * sizeof(S32) );
  2063. }
  2064. }
  2065. return ptr;
  2066. }
  2067. S8 * TSMesh::getSharedData8( S32 parentMesh, S32 size, S8 **source, bool skip )
  2068. {
  2069. S8 * ptr;
  2070. if( parentMesh < 0 )
  2071. ptr = skip ? tsalloc.getPointer8( size ) : tsalloc.copyToShape8( size );
  2072. else
  2073. {
  2074. ptr = source[parentMesh];
  2075. // if we skipped the previous mesh (and we're not skipping this one) then
  2076. // we still need to copy points into the shape...
  2077. if ( !smDataCopied[parentMesh] && !skip )
  2078. {
  2079. S8 * tmp = ptr;
  2080. ptr = tsalloc.allocShape8( size );
  2081. if ( ptr && tmp )
  2082. dMemcpy( ptr, tmp, size * sizeof(S32) );
  2083. }
  2084. }
  2085. return ptr;
  2086. }
  2087. void TSMesh::createVBIB()
  2088. {
  2089. AssertFatal( getMeshType() != SkinMeshType, "TSMesh::createVBIB() - Invalid call for skinned mesh type!" );
  2090. _createVBIB( mVB, mPB );
  2091. }
  2092. void TSMesh::_createVBIB( TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb )
  2093. {
  2094. AssertFatal(mVertexData.isReady(), "Call convertToAlignedMeshData() before calling _createVBIB()");
  2095. if ( mNumVerts == 0 || !GFXDevice::devicePresent() )
  2096. return;
  2097. PROFILE_SCOPE( TSMesh_CreateVBIB );
  2098. // Number of verts can change in LOD skinned mesh
  2099. const bool vertsChanged = ( vb && vb->mNumVerts < mNumVerts );
  2100. #if defined(USE_MEM_VERTEX_BUFFERS)
  2101. if(!mDynamic)
  2102. {
  2103. #endif
  2104. // Create the vertex buffer
  2105. if( vertsChanged || vb == NULL )
  2106. vb.set( GFX, mVertSize, mVertexFormat, mNumVerts, mDynamic ?
  2107. #if defined(TORQUE_OS_XENON)
  2108. // Skinned meshes still will occasionally re-skin more than once per frame.
  2109. // This cannot happen on the Xbox360. Until this issue is resolved, use
  2110. // type volatile instead. [1/27/2010 Pat]
  2111. GFXBufferTypeVolatile : GFXBufferTypeStatic );
  2112. #else
  2113. GFXBufferTypeDynamic : GFXBufferTypeStatic );
  2114. #endif
  2115. // Copy from aligned memory right into GPU memory
  2116. U8 *vertData = (U8*)vb.lock();
  2117. if(!vertData) return;
  2118. #if defined(TORQUE_OS_XENON)
  2119. XMemCpyStreaming_WriteCombined( vertData, mVertexData.address(), mVertexData.mem_size() );
  2120. #else
  2121. dMemcpy( vertData, mVertexData.address(), mVertexData.mem_size() );
  2122. #endif
  2123. vb.unlock();
  2124. #if defined(USE_MEM_VERTEX_BUFFERS)
  2125. }
  2126. #endif
  2127. const bool primsChanged = ( pb.isValid() && pb->mIndexCount != indices.size() );
  2128. if( primsChanged || pb.isNull() )
  2129. {
  2130. // go through and create PrimitiveInfo array
  2131. Vector <GFXPrimitive> piArray;
  2132. GFXPrimitive pInfo;
  2133. U32 primitivesSize = primitives.size();
  2134. for ( U32 i = 0; i < primitivesSize; i++ )
  2135. {
  2136. const TSDrawPrimitive & draw = primitives[i];
  2137. GFXPrimitiveType drawType = getDrawType( draw.matIndex >> 30 );
  2138. switch( drawType )
  2139. {
  2140. case GFXTriangleList:
  2141. pInfo.type = drawType;
  2142. pInfo.numPrimitives = draw.numElements / 3;
  2143. pInfo.startIndex = draw.start;
  2144. // Use the first index to determine which 16-bit address space we are operating in
  2145. pInfo.startVertex = indices[draw.start] & 0xFFFF0000;
  2146. pInfo.minIndex = pInfo.startVertex;
  2147. pInfo.numVertices = getMin((U32)0x10000, mNumVerts - pInfo.startVertex);
  2148. break;
  2149. case GFXTriangleStrip:
  2150. case GFXTriangleFan:
  2151. pInfo.type = drawType;
  2152. pInfo.numPrimitives = draw.numElements - 2;
  2153. pInfo.startIndex = draw.start;
  2154. // Use the first index to determine which 16-bit address space we are operating in
  2155. pInfo.startVertex = indices[draw.start] & 0xFFFF0000;
  2156. pInfo.minIndex = pInfo.startVertex;
  2157. pInfo.numVertices = getMin((U32)0x10000, mNumVerts - pInfo.startVertex);
  2158. break;
  2159. default:
  2160. AssertFatal( false, "WTF?!" );
  2161. }
  2162. piArray.push_back( pInfo );
  2163. }
  2164. pb.set( GFX, indices.size(), piArray.size(), GFXBufferTypeStatic );
  2165. U16 *ibIndices = NULL;
  2166. GFXPrimitive *piInput = NULL;
  2167. pb.lock( &ibIndices, &piInput );
  2168. dCopyArray( ibIndices, indices.address(), indices.size() );
  2169. dMemcpy( piInput, piArray.address(), piArray.size() * sizeof(GFXPrimitive) );
  2170. pb.unlock();
  2171. }
  2172. }
  2173. void TSMesh::assemble( bool skip )
  2174. {
  2175. tsalloc.checkGuard();
  2176. numFrames = tsalloc.get32();
  2177. numMatFrames = tsalloc.get32();
  2178. parentMesh = tsalloc.get32();
  2179. tsalloc.get32( (S32*)&mBounds, 6 );
  2180. tsalloc.get32( (S32*)&mCenter, 3 );
  2181. mRadius = (F32)tsalloc.get32();
  2182. S32 numVerts = tsalloc.get32();
  2183. S32 *ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smVertsList.address(), skip );
  2184. verts.set( (Point3F*)ptr32, numVerts );
  2185. S32 numTVerts = tsalloc.get32();
  2186. ptr32 = getSharedData32( parentMesh, 2 * numTVerts, (S32**)smTVertsList.address(), skip );
  2187. tverts.set( (Point2F*)ptr32, numTVerts );
  2188. if ( TSShape::smReadVersion > 25 )
  2189. {
  2190. numTVerts = tsalloc.get32();
  2191. ptr32 = getSharedData32( parentMesh, 2 * numTVerts, (S32**)smTVerts2List.address(), skip );
  2192. tverts2.set( (Point2F*)ptr32, numTVerts );
  2193. S32 numVColors = tsalloc.get32();
  2194. ptr32 = getSharedData32( parentMesh, numVColors, (S32**)smColorsList.address(), skip );
  2195. colors.set( (ColorI*)ptr32, numVColors );
  2196. }
  2197. S8 *ptr8;
  2198. if ( TSShape::smReadVersion > 21 && TSMesh::smUseEncodedNormals)
  2199. {
  2200. // we have encoded normals and we want to use them...
  2201. if ( parentMesh < 0 )
  2202. tsalloc.getPointer32( numVerts * 3 ); // advance past norms, don't use
  2203. norms.set( NULL, 0 );
  2204. ptr8 = getSharedData8( parentMesh, numVerts, (S8**)smEncodedNormsList.address(), skip );
  2205. encodedNorms.set( ptr8, numVerts );
  2206. }
  2207. else if ( TSShape::smReadVersion > 21 )
  2208. {
  2209. // we have encoded normals but we don't want to use them...
  2210. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2211. norms.set( (Point3F*)ptr32, numVerts );
  2212. if ( parentMesh < 0 )
  2213. tsalloc.getPointer8( numVerts ); // advance past encoded normls, don't use
  2214. encodedNorms.set( NULL, 0 );
  2215. }
  2216. else
  2217. {
  2218. // no encoded normals...
  2219. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2220. norms.set( (Point3F*)ptr32, numVerts );
  2221. encodedNorms.set( NULL, 0 );
  2222. }
  2223. // copy the primitives and indices...how we do this depends on what
  2224. // form we want them in when copied...just get pointers to data for now
  2225. S32 szPrimIn, szIndIn;
  2226. TSDrawPrimitive *primIn;
  2227. S32 *indIn;
  2228. bool deleteInputArrays = false;
  2229. if (TSShape::smReadVersion > 25)
  2230. {
  2231. // mesh primitives (start, numElements) and indices are stored as 32 bit values
  2232. szPrimIn = tsalloc.get32();
  2233. primIn = (TSDrawPrimitive*)tsalloc.getPointer32(szPrimIn*3);
  2234. szIndIn = tsalloc.get32();
  2235. indIn = tsalloc.getPointer32(szIndIn);
  2236. }
  2237. else
  2238. {
  2239. // mesh primitives (start, numElements) indices are stored as 16 bit values
  2240. szPrimIn = tsalloc.get32();
  2241. S16 *prim16 = tsalloc.getPointer16(szPrimIn*2); // primitive: start, numElements
  2242. S32 *prim32 = tsalloc.getPointer32(szPrimIn); // primitive: matIndex
  2243. szIndIn = tsalloc.get32();
  2244. // warn about non-addressable indices
  2245. if ( !skip && szIndIn >= 0x10000 )
  2246. {
  2247. Con::warnf("Mesh contains non-addressable indices, and may not render "
  2248. "correctly. Either split this mesh into pieces of no more than 65k "
  2249. "unique verts prior to export, or use COLLADA.");
  2250. }
  2251. S16 *ind16 = tsalloc.getPointer16(szIndIn);
  2252. // need to copy to temporary arrays
  2253. deleteInputArrays = true;
  2254. primIn = new TSDrawPrimitive[szPrimIn];
  2255. for (S32 i = 0; i < szPrimIn; i++)
  2256. {
  2257. primIn[i].start = prim16[i*2];
  2258. primIn[i].numElements = prim16[i*2+1];
  2259. primIn[i].matIndex = prim32[i];
  2260. }
  2261. indIn = new S32[szIndIn];
  2262. dCopyArray(indIn, ind16, szIndIn);
  2263. }
  2264. // count the number of output primitives and indices
  2265. S32 szPrimOut = szPrimIn, szIndOut = szIndIn;
  2266. if (smUseTriangles)
  2267. convertToTris(primIn, indIn, szPrimIn, szPrimOut, szIndOut, NULL, NULL);
  2268. else if (smUseOneStrip)
  2269. convertToSingleStrip(primIn, indIn, szPrimIn, szPrimOut, szIndOut, NULL, NULL);
  2270. else
  2271. leaveAsMultipleStrips(primIn, indIn, szPrimIn, szPrimOut, szIndOut, NULL, NULL);
  2272. // allocate enough space for the new primitives and indices (all 32 bits)
  2273. TSDrawPrimitive *primOut = (TSDrawPrimitive*)tsalloc.allocShape32(3*szPrimOut);
  2274. S32 *indOut = tsalloc.allocShape32(szIndOut);
  2275. // copy output primitives and indices
  2276. S32 chkPrim = szPrimOut, chkInd = szIndOut;
  2277. if (smUseTriangles)
  2278. convertToTris(primIn, indIn, szPrimIn, chkPrim, chkInd, primOut, indOut);
  2279. else if (smUseOneStrip)
  2280. convertToSingleStrip(primIn, indIn, szPrimIn, chkPrim, chkInd, primOut, indOut);
  2281. else
  2282. leaveAsMultipleStrips(primIn, indIn, szPrimIn, chkPrim, chkInd, primOut, indOut);
  2283. AssertFatal(chkPrim==szPrimOut && chkInd==szIndOut,"TSMesh::primitive conversion");
  2284. // store output
  2285. primitives.set(primOut, szPrimOut);
  2286. indices.set(indOut, szIndOut);
  2287. // delete temporary arrays if necessary
  2288. if (deleteInputArrays)
  2289. {
  2290. delete [] primIn;
  2291. delete [] indIn;
  2292. }
  2293. S32 sz = tsalloc.get32();
  2294. tsalloc.getPointer16( sz ); // skip deprecated merge indices
  2295. tsalloc.align32();
  2296. vertsPerFrame = tsalloc.get32();
  2297. U32 flags = (U32)tsalloc.get32();
  2298. if ( encodedNorms.size() )
  2299. flags |= UseEncodedNormals;
  2300. setFlags( flags );
  2301. tsalloc.checkGuard();
  2302. if ( tsalloc.allocShape32( 0 ) && TSShape::smReadVersion < 19 )
  2303. computeBounds(); // only do this if we copied the data...
  2304. if(getMeshType() != SkinMeshType)
  2305. createTangents(verts, norms);
  2306. }
  2307. void TSMesh::disassemble()
  2308. {
  2309. tsalloc.setGuard();
  2310. tsalloc.set32( numFrames );
  2311. tsalloc.set32( numMatFrames );
  2312. tsalloc.set32( parentMesh );
  2313. tsalloc.copyToBuffer32( (S32*)&mBounds, 6 );
  2314. tsalloc.copyToBuffer32( (S32*)&mCenter, 3 );
  2315. tsalloc.set32( (S32)mRadius );
  2316. // Re-create the vectors
  2317. if(mVertexData.isReady())
  2318. {
  2319. verts.setSize(mNumVerts);
  2320. tverts.setSize(mNumVerts);
  2321. norms.setSize(mNumVerts);
  2322. if(mHasColor)
  2323. colors.setSize(mNumVerts);
  2324. if(mHasTVert2)
  2325. tverts2.setSize(mNumVerts);
  2326. // Fill arrays
  2327. for(U32 i = 0; i < mNumVerts; i++)
  2328. {
  2329. const __TSMeshVertexBase &cv = mVertexData[i];
  2330. verts[i] = cv.vert();
  2331. tverts[i] = cv.tvert();
  2332. norms[i] = cv.normal();
  2333. if(mHasColor)
  2334. cv.color().getColor(&colors[i]);
  2335. if(mHasTVert2)
  2336. tverts2[i] = cv.tvert2();
  2337. }
  2338. }
  2339. // verts...
  2340. tsalloc.set32( verts.size() );
  2341. if ( parentMesh < 0 )
  2342. tsalloc.copyToBuffer32( (S32*)verts.address(), 3 * verts.size() ); // if no parent mesh, then save off our verts
  2343. // tverts...
  2344. tsalloc.set32( tverts.size() );
  2345. if ( parentMesh < 0 )
  2346. tsalloc.copyToBuffer32( (S32*)tverts.address(), 2 * tverts.size() ); // if no parent mesh, then save off our tverts
  2347. if (TSShape::smVersion > 25)
  2348. {
  2349. // tverts2...
  2350. tsalloc.set32( tverts2.size() );
  2351. if ( parentMesh < 0 )
  2352. tsalloc.copyToBuffer32( (S32*)tverts2.address(), 2 * tverts2.size() ); // if no parent mesh, then save off our tverts
  2353. // colors
  2354. tsalloc.set32( colors.size() );
  2355. if ( parentMesh < 0 )
  2356. tsalloc.copyToBuffer32( (S32*)colors.address(), colors.size() ); // if no parent mesh, then save off our tverts
  2357. }
  2358. // norms...
  2359. if ( parentMesh < 0 ) // if no parent mesh, then save off our norms
  2360. tsalloc.copyToBuffer32( (S32*)norms.address(), 3 * norms.size() ); // norms.size()==verts.size() or error...
  2361. // encoded norms...
  2362. if ( parentMesh < 0 )
  2363. {
  2364. // if no parent mesh, compute encoded normals and copy over
  2365. for ( S32 i = 0; i < norms.size(); i++ )
  2366. {
  2367. U8 normIdx = encodedNorms.size() ? encodedNorms[i] : encodeNormal( norms[i] );
  2368. tsalloc.copyToBuffer8( (S8*)&normIdx, 1 );
  2369. }
  2370. }
  2371. // optimize triangle draw order during disassemble
  2372. {
  2373. FrameTemp<TriListOpt::IndexType> tmpIdxs(indices.size());
  2374. for ( S32 i = 0; i < primitives.size(); i++ )
  2375. {
  2376. const TSDrawPrimitive& prim = primitives[i];
  2377. // only optimize triangle lists (strips and fans are assumed to be already optimized)
  2378. if ( (prim.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  2379. {
  2380. TriListOpt::OptimizeTriangleOrdering(verts.size(), prim.numElements,
  2381. indices.address() + prim.start, tmpIdxs.address());
  2382. dCopyArray(indices.address() + prim.start, tmpIdxs.address(),
  2383. prim.numElements);
  2384. }
  2385. }
  2386. }
  2387. if (TSShape::smVersion > 25)
  2388. {
  2389. // primitives...
  2390. tsalloc.set32( primitives.size() );
  2391. tsalloc.copyToBuffer32((S32*)primitives.address(),3*primitives.size());
  2392. // indices...
  2393. tsalloc.set32(indices.size());
  2394. tsalloc.copyToBuffer32((S32*)indices.address(),indices.size());
  2395. }
  2396. else
  2397. {
  2398. // primitives
  2399. tsalloc.set32( primitives.size() );
  2400. for (S32 i=0; i<primitives.size(); i++)
  2401. {
  2402. S16 start = (S16)primitives[i].start;
  2403. S16 numElements = (S16)primitives[i].numElements;
  2404. tsalloc.copyToBuffer16(&start, 1);
  2405. tsalloc.copyToBuffer16(&numElements, 1);
  2406. tsalloc.copyToBuffer32(&(primitives[i].matIndex), 1);
  2407. }
  2408. // indices
  2409. tsalloc.set32(indices.size());
  2410. Vector<S16> s16_indices(indices.size());
  2411. for (S32 i=0; i<indices.size(); i++)
  2412. s16_indices.push_back((S16)indices[i]);
  2413. tsalloc.copyToBuffer16(s16_indices.address(), s16_indices.size());
  2414. }
  2415. // merge indices...DEPRECATED
  2416. tsalloc.set32( 0 );
  2417. // small stuff...
  2418. tsalloc.set32( vertsPerFrame );
  2419. tsalloc.set32( getFlags() );
  2420. tsalloc.setGuard();
  2421. }
  2422. //-----------------------------------------------------------------------------
  2423. // TSSkinMesh assemble from/ dissemble to memory buffer
  2424. //-----------------------------------------------------------------------------
  2425. void TSSkinMesh::assemble( bool skip )
  2426. {
  2427. // avoid a crash on computeBounds...
  2428. batchData.initialVerts.set( NULL, 0 );
  2429. TSMesh::assemble( skip );
  2430. S32 sz = tsalloc.get32();
  2431. S32 numVerts = sz;
  2432. S32 * ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smVertsList.address(), skip );
  2433. batchData.initialVerts.set( (Point3F*)ptr32, sz );
  2434. S8 * ptr8;
  2435. if ( TSShape::smReadVersion>21 && TSMesh::smUseEncodedNormals )
  2436. {
  2437. // we have encoded normals and we want to use them...
  2438. if ( parentMesh < 0 )
  2439. tsalloc.getPointer32( numVerts * 3 ); // advance past norms, don't use
  2440. batchData.initialNorms.set( NULL, 0 );
  2441. ptr8 = getSharedData8( parentMesh, numVerts, (S8**)smEncodedNormsList.address(), skip );
  2442. encodedNorms.set( ptr8, numVerts );
  2443. // Note: we don't set the encoded normals flag because we handle them in updateSkin and
  2444. // hide the fact that we are using them from base class (TSMesh)
  2445. }
  2446. else if ( TSShape::smReadVersion > 21 )
  2447. {
  2448. // we have encoded normals but we don't want to use them...
  2449. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2450. batchData.initialNorms.set( (Point3F*)ptr32, numVerts );
  2451. if ( parentMesh < 0 )
  2452. tsalloc.getPointer8( numVerts ); // advance past encoded normls, don't use
  2453. encodedNorms.set( NULL, 0 );
  2454. }
  2455. else
  2456. {
  2457. // no encoded normals...
  2458. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2459. batchData.initialNorms.set( (Point3F*)ptr32, numVerts );
  2460. encodedNorms.set( NULL, 0 );
  2461. }
  2462. sz = tsalloc.get32();
  2463. ptr32 = getSharedData32( parentMesh, 16 * sz, (S32**)smInitTransformList.address(), skip );
  2464. batchData.initialTransforms.set( ptr32, sz );
  2465. sz = tsalloc.get32();
  2466. ptr32 = getSharedData32( parentMesh, sz, (S32**)smVertexIndexList.address(), skip );
  2467. vertexIndex.set( ptr32, sz );
  2468. ptr32 = getSharedData32( parentMesh, sz, (S32**)smBoneIndexList.address(), skip );
  2469. boneIndex.set( ptr32, sz );
  2470. ptr32 = getSharedData32( parentMesh, sz, (S32**)smWeightList.address(), skip );
  2471. weight.set( (F32*)ptr32, sz );
  2472. sz = tsalloc.get32();
  2473. ptr32 = getSharedData32( parentMesh, sz, (S32**)smNodeIndexList.address(), skip );
  2474. batchData.nodeIndex.set( ptr32, sz );
  2475. tsalloc.checkGuard();
  2476. if ( tsalloc.allocShape32( 0 ) && TSShape::smReadVersion < 19 )
  2477. TSMesh::computeBounds(); // only do this if we copied the data...
  2478. createTangents(batchData.initialVerts, batchData.initialNorms);
  2479. }
  2480. //-----------------------------------------------------------------------------
  2481. // disassemble
  2482. //-----------------------------------------------------------------------------
  2483. void TSSkinMesh::disassemble()
  2484. {
  2485. TSMesh::disassemble();
  2486. tsalloc.set32( batchData.initialVerts.size() );
  2487. // if we have no parent mesh, then save off our verts & norms
  2488. if ( parentMesh < 0 )
  2489. {
  2490. tsalloc.copyToBuffer32( (S32*)batchData.initialVerts.address(), 3 * batchData.initialVerts.size() );
  2491. // no longer do this here...let tsmesh handle this
  2492. tsalloc.copyToBuffer32( (S32*)batchData.initialNorms.address(), 3 * batchData.initialNorms.size() );
  2493. // if no parent mesh, compute encoded normals and copy over
  2494. for ( S32 i = 0; i < batchData.initialNorms.size(); i++ )
  2495. {
  2496. U8 normIdx = encodedNorms.size() ? encodedNorms[i] : encodeNormal( batchData.initialNorms[i] );
  2497. tsalloc.copyToBuffer8( (S8*)&normIdx, 1 );
  2498. }
  2499. }
  2500. tsalloc.set32( batchData.initialTransforms.size() );
  2501. if ( parentMesh < 0 )
  2502. tsalloc.copyToBuffer32( (S32*)batchData.initialTransforms.address(), batchData.initialTransforms.size() * 16 );
  2503. tsalloc.set32( vertexIndex.size() );
  2504. if ( parentMesh < 0 )
  2505. {
  2506. tsalloc.copyToBuffer32( (S32*)vertexIndex.address(), vertexIndex.size() );
  2507. tsalloc.copyToBuffer32( (S32*)boneIndex.address(), boneIndex.size() );
  2508. tsalloc.copyToBuffer32( (S32*)weight.address(), weight.size() );
  2509. }
  2510. tsalloc.set32( batchData.nodeIndex.size() );
  2511. if ( parentMesh < 0 )
  2512. tsalloc.copyToBuffer32( (S32*)batchData.nodeIndex.address(), batchData.nodeIndex.size() );
  2513. tsalloc.setGuard();
  2514. }
  2515. TSSkinMesh::TSSkinMesh()
  2516. {
  2517. meshType = SkinMeshType;
  2518. mDynamic = true;
  2519. batchDataInitialized = false;
  2520. }
  2521. //-----------------------------------------------------------------------------
  2522. // find tangent vector
  2523. //-----------------------------------------------------------------------------
  2524. inline void TSMesh::findTangent( U32 index1,
  2525. U32 index2,
  2526. U32 index3,
  2527. Point3F *tan0,
  2528. Point3F *tan1,
  2529. const Vector<Point3F> &_verts)
  2530. {
  2531. const Point3F &v1 = _verts[index1];
  2532. const Point3F &v2 = _verts[index2];
  2533. const Point3F &v3 = _verts[index3];
  2534. const Point2F &w1 = tverts[index1];
  2535. const Point2F &w2 = tverts[index2];
  2536. const Point2F &w3 = tverts[index3];
  2537. F32 x1 = v2.x - v1.x;
  2538. F32 x2 = v3.x - v1.x;
  2539. F32 y1 = v2.y - v1.y;
  2540. F32 y2 = v3.y - v1.y;
  2541. F32 z1 = v2.z - v1.z;
  2542. F32 z2 = v3.z - v1.z;
  2543. F32 s1 = w2.x - w1.x;
  2544. F32 s2 = w3.x - w1.x;
  2545. F32 t1 = w2.y - w1.y;
  2546. F32 t2 = w3.y - w1.y;
  2547. F32 denom = (s1 * t2 - s2 * t1);
  2548. if( mFabs( denom ) < 0.0001f )
  2549. {
  2550. // handle degenerate triangles from strips
  2551. if (denom<0) denom = -0.0001f;
  2552. else denom = 0.0001f;
  2553. }
  2554. F32 r = 1.0f / denom;
  2555. Point3F sdir( (t2 * x1 - t1 * x2) * r,
  2556. (t2 * y1 - t1 * y2) * r,
  2557. (t2 * z1 - t1 * z2) * r );
  2558. Point3F tdir( (s1 * x2 - s2 * x1) * r,
  2559. (s1 * y2 - s2 * y1) * r,
  2560. (s1 * z2 - s2 * z1) * r );
  2561. tan0[index1] += sdir;
  2562. tan1[index1] += tdir;
  2563. tan0[index2] += sdir;
  2564. tan1[index2] += tdir;
  2565. tan0[index3] += sdir;
  2566. tan1[index3] += tdir;
  2567. }
  2568. //-----------------------------------------------------------------------------
  2569. // create array of tangent vectors
  2570. //-----------------------------------------------------------------------------
  2571. void TSMesh::createTangents(const Vector<Point3F> &_verts, const Vector<Point3F> &_norms)
  2572. {
  2573. U32 numVerts = _verts.size();
  2574. U32 numNorms = _norms.size();
  2575. if ( numVerts <= 0 || numNorms <= 0 )
  2576. return;
  2577. if( numVerts != numNorms)
  2578. return;
  2579. Vector<Point3F> tan0;
  2580. tan0.setSize( numVerts * 2 );
  2581. Point3F *tan1 = tan0.address() + numVerts;
  2582. dMemset( tan0.address(), 0, sizeof(Point3F) * 2 * numVerts );
  2583. U32 numPrimatives = primitives.size();
  2584. for (S32 i = 0; i < numPrimatives; i++ )
  2585. {
  2586. const TSDrawPrimitive & draw = primitives[i];
  2587. GFXPrimitiveType drawType = getDrawType( draw.matIndex >> 30 );
  2588. U32 p1Index = 0;
  2589. U32 p2Index = 0;
  2590. U32 *baseIdx = &indices[draw.start];
  2591. const U32 numElements = (U32)draw.numElements;
  2592. switch( drawType )
  2593. {
  2594. case GFXTriangleList:
  2595. {
  2596. for( U32 j = 0; j < numElements; j += 3 )
  2597. findTangent( baseIdx[j], baseIdx[j + 1], baseIdx[j + 2], tan0.address(), tan1, _verts );
  2598. break;
  2599. }
  2600. case GFXTriangleStrip:
  2601. {
  2602. p1Index = baseIdx[0];
  2603. p2Index = baseIdx[1];
  2604. for( U32 j = 2; j < numElements; j++ )
  2605. {
  2606. findTangent( p1Index, p2Index, baseIdx[j], tan0.address(), tan1, _verts );
  2607. p1Index = p2Index;
  2608. p2Index = baseIdx[j];
  2609. }
  2610. break;
  2611. }
  2612. case GFXTriangleFan:
  2613. {
  2614. p1Index = baseIdx[0];
  2615. p2Index = baseIdx[1];
  2616. for( U32 j = 2; j < numElements; j++ )
  2617. {
  2618. findTangent( p1Index, p2Index, baseIdx[j], tan0.address(), tan1, _verts );
  2619. p2Index = baseIdx[j];
  2620. }
  2621. break;
  2622. }
  2623. default:
  2624. AssertFatal( false, "TSMesh::createTangents: unknown primitive type!" );
  2625. }
  2626. }
  2627. tangents.setSize( numVerts );
  2628. // fill out final info from accumulated basis data
  2629. for( U32 i = 0; i < numVerts; i++ )
  2630. {
  2631. const Point3F &n = _norms[i];
  2632. const Point3F &t = tan0[i];
  2633. const Point3F &b = tan1[i];
  2634. Point3F tempPt = t - n * mDot( n, t );
  2635. tempPt.normalize();
  2636. tangents[i] = tempPt;
  2637. Point3F cp;
  2638. mCross( n, t, &cp );
  2639. tangents[i].w = (mDot( cp, b ) < 0.0f) ? -1.0f : 1.0f;
  2640. }
  2641. }
  2642. void TSMesh::convertToAlignedMeshData()
  2643. {
  2644. if(!mVertexData.isReady())
  2645. _convertToAlignedMeshData(mVertexData, verts, norms);
  2646. }
  2647. void TSSkinMesh::convertToAlignedMeshData()
  2648. {
  2649. if(!mVertexData.isReady())
  2650. _convertToAlignedMeshData(mVertexData, batchData.initialVerts, batchData.initialNorms);
  2651. }
  2652. void TSMesh::_convertToAlignedMeshData( TSMeshVertexArray &vertexData, const Vector<Point3F> &_verts, const Vector<Point3F> &_norms )
  2653. {
  2654. // If mVertexData is ready, and the input array is different than mVertexData
  2655. // use mVertexData to quickly initialize the input array
  2656. if(mVertexData.isReady() && vertexData.address() != mVertexData.address())
  2657. {
  2658. AssertFatal(mVertexData.size() == mNumVerts, "Vertex data length mismatch; no idea how this happened.");
  2659. // There doesn't seem to be an _mm_realloc, even though there is an _aligned_realloc
  2660. // We really shouldn't be re-allocating anyway. Should TSShapeInstance be
  2661. // storing an array of the data structures? That would certainly bloat memory.
  2662. void *aligned_mem = dMalloc_aligned(mVertSize * mNumVerts, 16);
  2663. AssertFatal(aligned_mem, "Aligned malloc failed! Debug!");
  2664. vertexData.set(aligned_mem, mVertSize, mNumVerts);
  2665. vertexData.setReady(true);
  2666. #if defined(TORQUE_OS_XENON)
  2667. XMemCpyStreaming(vertexData.address(), mVertexData.address(), vertexData.mem_size() );
  2668. #else
  2669. dMemcpy(vertexData.address(), mVertexData.address(), vertexData.mem_size());
  2670. #endif
  2671. return;
  2672. }
  2673. AssertFatal(!vertexData.isReady(), "Mesh already converted to aligned data! Re-check code!");
  2674. AssertFatal(_verts.size() == _norms.size() &&
  2675. _verts.size() == tangents.size(),
  2676. "Vectors: verts, norms, tangents must all be the same size");
  2677. mNumVerts = _verts.size();
  2678. // Initialize the vertex data
  2679. vertexData.set(NULL, 0, 0);
  2680. vertexData.setReady(true);
  2681. if(mNumVerts == 0)
  2682. return;
  2683. mHasColor = !colors.empty();
  2684. AssertFatal(!mHasColor || colors.size() == _verts.size(), "Vector of color elements should be the same size as other vectors");
  2685. mHasTVert2 = !tverts2.empty();
  2686. AssertFatal(!mHasTVert2 || tverts2.size() == _verts.size(), "Vector of tvert2 elements should be the same size as other vectors");
  2687. // Create the proper array type
  2688. void *aligned_mem = dMalloc_aligned(mVertSize * mNumVerts, 16);
  2689. AssertFatal(aligned_mem, "Aligned malloc failed! Debug!");
  2690. dMemset(aligned_mem, 0, mNumVerts * mVertSize);
  2691. vertexData.set(aligned_mem, mVertSize, mNumVerts);
  2692. for(U32 i = 0; i < mNumVerts; i++)
  2693. {
  2694. __TSMeshVertexBase &v = vertexData[i];
  2695. v.vert(_verts[i]);
  2696. v.normal(_norms[i]);
  2697. v.tangent(tangents[i]);
  2698. if(i < tverts.size())
  2699. v.tvert(tverts[i]);
  2700. if(mHasTVert2 && i < tverts2.size())
  2701. v.tvert2(tverts2[i]);
  2702. if(mHasColor && i < colors.size())
  2703. v.color(colors[i]);
  2704. }
  2705. // Now that the data is in the aligned struct, free the Vector memory
  2706. verts.free_memory();
  2707. norms.free_memory();
  2708. tangents.free_memory();
  2709. tverts.free_memory();
  2710. tverts2.free_memory();
  2711. colors.free_memory();
  2712. }