tsMesh.cpp 108 KB

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