tsShapeInstance.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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/tsShapeInstance.h"
  24. #include "ts/tsLastDetail.h"
  25. #include "ts/tsMaterialList.h"
  26. #include "console/consoleTypes.h"
  27. #include "ts/tsDecal.h"
  28. #include "platform/profiler.h"
  29. #include "core/frameAllocator.h"
  30. #include "gfx/gfxDevice.h"
  31. #include "materials/materialManager.h"
  32. #include "materials/materialFeatureTypes.h"
  33. #include "materials/sceneData.h"
  34. #include "materials/matInstance.h"
  35. #include "scene/sceneRenderState.h"
  36. #include "gfx/primBuilder.h"
  37. #include "gfx/gfxDrawUtil.h"
  38. #include "core/module.h"
  39. MODULE_BEGIN( TSShapeInstance )
  40. MODULE_INIT
  41. {
  42. Con::addVariable("$pref::TS::detailAdjust", TypeF32, &TSShapeInstance::smDetailAdjust,
  43. "@brief User perference for scaling the TSShape level of detail.\n"
  44. "The smaller the value the closer the camera must get to see the "
  45. "highest LOD. This setting can have a huge impact on performance in "
  46. "mesh heavy scenes. The default value is 1.\n"
  47. "@ingroup Rendering\n" );
  48. Con::addVariable("$pref::TS::skipLoadDLs", TypeS32, &TSShape::smNumSkipLoadDetails,
  49. "@brief User perference which causes TSShapes to skip loading higher lods.\n"
  50. "This potentialy reduces the GPU resources and materials generated as well as "
  51. "limits the LODs rendered. The default value is 0.\n"
  52. "@see $pref::TS::skipRenderDLs\n"
  53. "@ingroup Rendering\n" );
  54. Con::addVariable("$pref::TS::skipRenderDLs", TypeS32, &TSShapeInstance::smNumSkipRenderDetails,
  55. "@brief User perference which causes TSShapes to skip rendering higher lods.\n"
  56. "This will reduce the number of draw calls and triangles rendered and improve "
  57. "rendering performance when proper LODs have been created for your models. "
  58. "The default value is 0.\n"
  59. "@see $pref::TS::skipLoadDLs\n"
  60. "@ingroup Rendering\n" );
  61. Con::addVariable("$pref::TS::smallestVisiblePixelSize", TypeF32, &TSShapeInstance::smSmallestVisiblePixelSize,
  62. "@brief User perference which sets the smallest pixel size at which TSShapes will skip rendering.\n"
  63. "This will force all shapes to stop rendering when they get smaller than this size. "
  64. "The default value is -1 which disables it.\n"
  65. "@ingroup Rendering\n" );
  66. Con::addVariable("$pref::TS::maxInstancingVerts", TypeS32, &TSMesh::smMaxInstancingVerts,
  67. "@brief Enables mesh instancing on non-skin meshes that have less that this count of verts.\n"
  68. "The default value is 200. Higher values can degrade performance.\n"
  69. "@ingroup Rendering\n" );
  70. }
  71. MODULE_END;
  72. F32 TSShapeInstance::smDetailAdjust = 1.0f;
  73. F32 TSShapeInstance::smSmallestVisiblePixelSize = -1.0f;
  74. S32 TSShapeInstance::smNumSkipRenderDetails = 0;
  75. F32 TSShapeInstance::smLastScreenErrorTolerance = 0.0f;
  76. F32 TSShapeInstance::smLastScaledDistance = 0.0f;
  77. F32 TSShapeInstance::smLastPixelSize = 0.0f;
  78. Vector<QuatF> TSShapeInstance::smNodeCurrentRotations(__FILE__, __LINE__);
  79. Vector<Point3F> TSShapeInstance::smNodeCurrentTranslations(__FILE__, __LINE__);
  80. Vector<F32> TSShapeInstance::smNodeCurrentUniformScales(__FILE__, __LINE__);
  81. Vector<Point3F> TSShapeInstance::smNodeCurrentAlignedScales(__FILE__, __LINE__);
  82. Vector<TSScale> TSShapeInstance::smNodeCurrentArbitraryScales(__FILE__, __LINE__);
  83. Vector<MatrixF> TSShapeInstance::smNodeLocalTransforms(__FILE__, __LINE__);
  84. TSIntegerSet TSShapeInstance::smNodeLocalTransformDirty;
  85. Vector<TSThread*> TSShapeInstance::smRotationThreads(__FILE__, __LINE__);
  86. Vector<TSThread*> TSShapeInstance::smTranslationThreads(__FILE__, __LINE__);
  87. Vector<TSThread*> TSShapeInstance::smScaleThreads(__FILE__, __LINE__);
  88. //-------------------------------------------------------------------------------------
  89. // constructors, destructors, initialization
  90. //-------------------------------------------------------------------------------------
  91. TSShapeInstance::TSShapeInstance( const Resource<TSShape> &shape, bool loadMaterials )
  92. {
  93. VECTOR_SET_ASSOCIATION(mMeshObjects);
  94. VECTOR_SET_ASSOCIATION(mNodeTransforms);
  95. VECTOR_SET_ASSOCIATION(mNodeReferenceRotations);
  96. VECTOR_SET_ASSOCIATION(mNodeReferenceTranslations);
  97. VECTOR_SET_ASSOCIATION(mNodeReferenceUniformScales);
  98. VECTOR_SET_ASSOCIATION(mNodeReferenceScaleFactors);
  99. VECTOR_SET_ASSOCIATION(mNodeReferenceArbitraryScaleRots);
  100. VECTOR_SET_ASSOCIATION(mThreadList);
  101. VECTOR_SET_ASSOCIATION(mTransitionThreads);
  102. mShapeResource = shape;
  103. mShape = mShapeResource;
  104. buildInstanceData( mShape, loadMaterials );
  105. }
  106. TSShapeInstance::TSShapeInstance( TSShape *shape, bool loadMaterials )
  107. {
  108. VECTOR_SET_ASSOCIATION(mMeshObjects);
  109. VECTOR_SET_ASSOCIATION(mNodeTransforms);
  110. VECTOR_SET_ASSOCIATION(mNodeReferenceRotations);
  111. VECTOR_SET_ASSOCIATION(mNodeReferenceTranslations);
  112. VECTOR_SET_ASSOCIATION(mNodeReferenceUniformScales);
  113. VECTOR_SET_ASSOCIATION(mNodeReferenceScaleFactors);
  114. VECTOR_SET_ASSOCIATION(mNodeReferenceArbitraryScaleRots);
  115. VECTOR_SET_ASSOCIATION(mThreadList);
  116. VECTOR_SET_ASSOCIATION(mTransitionThreads);
  117. mShapeResource = NULL;
  118. mShape = shape;
  119. buildInstanceData( mShape, loadMaterials );
  120. }
  121. TSShapeInstance::~TSShapeInstance()
  122. {
  123. mMeshObjects.clear();
  124. while (mThreadList.size())
  125. destroyThread(mThreadList.last());
  126. setMaterialList(NULL);
  127. delete [] mDirtyFlags;
  128. }
  129. void TSShapeInstance::buildInstanceData(TSShape * _shape, bool loadMaterials)
  130. {
  131. mShape = _shape;
  132. debrisRefCount = 0;
  133. mCurrentDetailLevel = 0;
  134. mCurrentIntraDetailLevel = 1.0f;
  135. // all triggers off at start
  136. mTriggerStates = 0;
  137. //
  138. mAlphaAlways = false;
  139. mAlphaAlwaysValue = 1.0f;
  140. // material list...
  141. mMaterialList = NULL;
  142. mOwnMaterialList = false;
  143. //
  144. mData = 0;
  145. mScaleCurrentlyAnimated = false;
  146. if(loadMaterials)
  147. setMaterialList(mShape->materialList);
  148. // set up node data
  149. initNodeTransforms();
  150. // add objects to trees
  151. initMeshObjects();
  152. // set up subtree data
  153. S32 ss = mShape->subShapeFirstNode.size(); // we have this many subtrees
  154. mDirtyFlags = new U32[ss];
  155. mGroundThread = NULL;
  156. mCurrentDetailLevel = 0;
  157. animateSubtrees();
  158. // Construct billboards if not done already
  159. if ( loadMaterials && mShapeResource && GFXDevice::devicePresent() )
  160. mShape->setupBillboardDetails( mShapeResource.getPath().getFullPath() );
  161. }
  162. void TSShapeInstance::initNodeTransforms()
  163. {
  164. // set up node data
  165. S32 numNodes = mShape->nodes.size();
  166. mNodeTransforms.setSize(numNodes);
  167. }
  168. void TSShapeInstance::initMeshObjects()
  169. {
  170. // add objects to trees
  171. S32 numObjects = mShape->objects.size();
  172. mMeshObjects.setSize(numObjects);
  173. for (S32 i=0; i<numObjects; i++)
  174. {
  175. const TSObject * obj = &mShape->objects[i];
  176. MeshObjectInstance * objInst = &mMeshObjects[i];
  177. // hook up the object to it's node and transforms.
  178. objInst->mTransforms = &mNodeTransforms;
  179. objInst->nodeIndex = obj->nodeIndex;
  180. // set up list of meshes
  181. if (obj->numMeshes)
  182. objInst->meshList = &mShape->meshes[obj->startMeshIndex];
  183. else
  184. objInst->meshList = NULL;
  185. objInst->object = obj;
  186. objInst->forceHidden = false;
  187. }
  188. }
  189. void TSShapeInstance::setMaterialList( TSMaterialList *matList )
  190. {
  191. // get rid of old list
  192. if ( mOwnMaterialList )
  193. delete mMaterialList;
  194. mMaterialList = matList;
  195. mOwnMaterialList = false;
  196. // If the material list is already be mapped then
  197. // don't bother doing the initializing a second time.
  198. // Note: only check the last material instance as this will catch both
  199. // uninitialised lists, as well as initialised lists that have had new
  200. // materials appended
  201. if ( mMaterialList && !mMaterialList->getMaterialInst( mMaterialList->size()-1 ) )
  202. {
  203. mMaterialList->setTextureLookupPath( mShapeResource.getPath().getPath() );
  204. mMaterialList->mapMaterials();
  205. Material::sAllowTextureTargetAssignment = true;
  206. initMaterialList();
  207. Material::sAllowTextureTargetAssignment = false;
  208. }
  209. }
  210. void TSShapeInstance::cloneMaterialList( const FeatureSet *features )
  211. {
  212. if ( mOwnMaterialList )
  213. return;
  214. Material::sAllowTextureTargetAssignment = true;
  215. mMaterialList = new TSMaterialList(mMaterialList);
  216. initMaterialList( features );
  217. Material::sAllowTextureTargetAssignment = false;
  218. mOwnMaterialList = true;
  219. }
  220. void TSShapeInstance::initMaterialList( const FeatureSet *features )
  221. {
  222. // If we don't have features then use the default.
  223. if ( !features )
  224. features = &MATMGR->getDefaultFeatures();
  225. // Initialize the materials.
  226. mMaterialList->initMatInstances( *features, mShape->getVertexFormat() );
  227. // TODO: It would be good to go thru all the meshes and
  228. // pre-create all the active material hooks for shadows,
  229. // reflections, and instancing. This would keep these
  230. // hiccups from happening at runtime.
  231. }
  232. void TSShapeInstance::reSkin( String newBaseName, String oldBaseName )
  233. {
  234. if( newBaseName.isEmpty() )
  235. newBaseName = "base";
  236. if( oldBaseName.isEmpty() )
  237. oldBaseName = "base";
  238. if ( newBaseName.equal( oldBaseName, String::NoCase ) )
  239. return;
  240. const U32 oldBaseNameLength = oldBaseName.length();
  241. // Make our own copy of the materials list from the resource if necessary
  242. if (ownMaterialList() == false)
  243. cloneMaterialList();
  244. TSMaterialList* pMatList = getMaterialList();
  245. pMatList->setTextureLookupPath( mShapeResource.getPath().getPath() );
  246. // Cycle through the materials
  247. const Vector<String> &materialNames = pMatList->getMaterialNameList();
  248. for ( S32 i = 0; i < materialNames.size(); i++ )
  249. {
  250. // Try changing base
  251. const String &pName = materialNames[i];
  252. if ( pName.compare( oldBaseName, oldBaseNameLength, String::NoCase ) == 0 )
  253. {
  254. String newName( pName );
  255. newName.replace( 0, oldBaseNameLength, newBaseName );
  256. pMatList->renameMaterial( i, newName );
  257. }
  258. }
  259. // Initialize the material instances
  260. initMaterialList();
  261. }
  262. //-------------------------------------------------------------------------------------
  263. // Render & detail selection
  264. //-------------------------------------------------------------------------------------
  265. void TSShapeInstance::renderDebugNormals( F32 normalScalar, S32 dl )
  266. {
  267. if ( dl < 0 )
  268. return;
  269. AssertFatal( dl >= 0 && dl < mShape->details.size(),
  270. "TSShapeInstance::renderDebugNormals() - Bad detail level!" );
  271. static GFXStateBlockRef sb;
  272. if ( sb.isNull() )
  273. {
  274. GFXStateBlockDesc desc;
  275. desc.setCullMode( GFXCullNone );
  276. desc.setZReadWrite( true );
  277. desc.zWriteEnable = false;
  278. desc.vertexColorEnable = true;
  279. sb = GFX->createStateBlock( desc );
  280. }
  281. GFX->setStateBlock( sb );
  282. const TSDetail *detail = &mShape->details[dl];
  283. const S32 ss = detail->subShapeNum;
  284. if ( ss < 0 )
  285. return;
  286. const S32 start = mShape->subShapeFirstObject[ss];
  287. const S32 end = start + mShape->subShapeNumObjects[ss];
  288. for ( S32 i = start; i < end; i++ )
  289. {
  290. MeshObjectInstance *meshObj = &mMeshObjects[i];
  291. if ( !meshObj )
  292. continue;
  293. const MatrixF &meshMat = meshObj->getTransform();
  294. // Then go through each TSMesh...
  295. U32 m = 0;
  296. for( TSMesh *mesh = meshObj->getMesh(m); mesh != NULL; mesh = meshObj->getMesh(m++) )
  297. {
  298. // and pull out the list of normals.
  299. const U32 numNrms = mesh->mNumVerts;
  300. PrimBuild::begin( GFXLineList, 2 * numNrms );
  301. for ( U32 n = 0; n < numNrms; n++ )
  302. {
  303. Point3F norm = mesh->mVertexData[n].normal();
  304. Point3F vert = mesh->mVertexData[n].vert();
  305. meshMat.mulP( vert );
  306. meshMat.mulV( norm );
  307. // Then render them.
  308. PrimBuild::color4f( mFabs( norm.x ), mFabs( norm.y ), mFabs( norm.z ), 1.0f );
  309. PrimBuild::vertex3fv( vert );
  310. PrimBuild::vertex3fv( vert + (norm * normalScalar) );
  311. }
  312. PrimBuild::end();
  313. }
  314. }
  315. }
  316. void TSShapeInstance::renderDebugNodes()
  317. {
  318. GFXDrawUtil *drawUtil = GFX->getDrawUtil();
  319. ColorI color( 255, 0, 0, 255 );
  320. GFXStateBlockDesc desc;
  321. desc.setBlend( false );
  322. desc.setZReadWrite( false, false );
  323. for ( U32 i = 0; i < mNodeTransforms.size(); i++ )
  324. drawUtil->drawTransform( desc, mNodeTransforms[i], NULL, NULL );
  325. }
  326. void TSShapeInstance::listMeshes( const String &state ) const
  327. {
  328. if ( state.equal( "All", String::NoCase ) )
  329. {
  330. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  331. {
  332. const MeshObjectInstance &mesh = mMeshObjects[i];
  333. Con::warnf( "meshidx %3d, %8s, %s", i, ( mesh.forceHidden ) ? "Hidden" : "Visible", mShape->getMeshName(i).c_str() );
  334. }
  335. }
  336. else if ( state.equal( "Hidden", String::NoCase ) )
  337. {
  338. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  339. {
  340. const MeshObjectInstance &mesh = mMeshObjects[i];
  341. if ( mesh.forceHidden )
  342. Con::warnf( "meshidx %3d, %8s, %s", i, "Visible", mShape->getMeshName(i).c_str() );
  343. }
  344. }
  345. else if ( state.equal( "Visible", String::NoCase ) )
  346. {
  347. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  348. {
  349. const MeshObjectInstance &mesh = mMeshObjects[i];
  350. if ( !mesh.forceHidden )
  351. Con::warnf( "meshidx %3d, %8s, %s", i, "Hidden", mShape->getMeshName(i).c_str() );
  352. }
  353. }
  354. else
  355. {
  356. Con::warnf( "TSShapeInstance::listMeshes( %s ) - only All/Hidden/Visible are valid parameters." );
  357. }
  358. }
  359. void TSShapeInstance::render( const TSRenderState &rdata )
  360. {
  361. if (mCurrentDetailLevel<0)
  362. return;
  363. PROFILE_SCOPE( TSShapeInstance_Render );
  364. // alphaIn: we start to alpha-in next detail level when intraDL > 1-alphaIn-alphaOut
  365. // (finishing when intraDL = 1-alphaOut)
  366. // alphaOut: start to alpha-out this detail level when intraDL > 1-alphaOut
  367. // NOTE:
  368. // intraDL is at 1 when if shape were any closer to us we'd be at dl-1,
  369. // intraDL is at 0 when if shape were any farther away we'd be at dl+1
  370. F32 alphaOut = mShape->alphaOut[mCurrentDetailLevel];
  371. F32 alphaIn = mShape->alphaIn[mCurrentDetailLevel];
  372. F32 saveAA = mAlphaAlways ? mAlphaAlwaysValue : 1.0f;
  373. /// This first case is the single detail level render.
  374. if ( mCurrentIntraDetailLevel > alphaIn + alphaOut )
  375. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  376. else if ( mCurrentIntraDetailLevel > alphaOut )
  377. {
  378. // draw this detail level w/ alpha=1 and next detail level w/
  379. // alpha=1-(intraDl-alphaOut)/alphaIn
  380. // first draw next detail level
  381. if ( mCurrentDetailLevel + 1 < mShape->details.size() && mShape->details[ mCurrentDetailLevel + 1 ].size > 0.0f )
  382. {
  383. setAlphaAlways( saveAA * ( alphaIn + alphaOut - mCurrentIntraDetailLevel ) / alphaIn );
  384. render( rdata, mCurrentDetailLevel + 1, 0.0f );
  385. }
  386. setAlphaAlways( saveAA );
  387. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  388. }
  389. else
  390. {
  391. // draw next detail level w/ alpha=1 and this detail level w/
  392. // alpha = 1-intraDL/alphaOut
  393. // first draw next detail level
  394. if ( mCurrentDetailLevel + 1 < mShape->details.size() && mShape->details[ mCurrentDetailLevel + 1 ].size > 0.0f )
  395. render( rdata, mCurrentDetailLevel+1, 0.0f );
  396. setAlphaAlways( saveAA * mCurrentIntraDetailLevel / alphaOut );
  397. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  398. setAlphaAlways( saveAA );
  399. }
  400. }
  401. void TSShapeInstance::setMeshForceHidden( const char *meshName, bool hidden )
  402. {
  403. Vector<MeshObjectInstance>::iterator iter = mMeshObjects.begin();
  404. for ( ; iter != mMeshObjects.end(); iter++ )
  405. {
  406. S32 nameIndex = iter->object->nameIndex;
  407. const char *name = mShape->names[ nameIndex ];
  408. if ( dStrcmp( meshName, name ) == 0 )
  409. {
  410. iter->forceHidden = hidden;
  411. return;
  412. }
  413. }
  414. }
  415. void TSShapeInstance::setMeshForceHidden( S32 meshIndex, bool hidden )
  416. {
  417. AssertFatal( meshIndex > -1 && meshIndex < mMeshObjects.size(),
  418. "TSShapeInstance::setMeshForceHidden - Invalid index!" );
  419. mMeshObjects[meshIndex].forceHidden = hidden;
  420. }
  421. void TSShapeInstance::render( const TSRenderState &rdata, S32 dl, F32 intraDL )
  422. {
  423. AssertFatal( dl >= 0 && dl < mShape->details.size(),"TSShapeInstance::render" );
  424. S32 i;
  425. const TSDetail * detail = &mShape->details[dl];
  426. S32 ss = detail->subShapeNum;
  427. S32 od = detail->objectDetailNum;
  428. // if we're a billboard detail, draw it and exit
  429. if ( ss < 0 )
  430. {
  431. PROFILE_SCOPE( TSShapeInstance_RenderBillboards );
  432. if ( !rdata.isNoRenderTranslucent() && ( TSLastDetail::smCanShadow || !rdata.getSceneState()->isShadowPass() ) )
  433. mShape->billboardDetails[ dl ]->render( rdata, mAlphaAlways ? mAlphaAlwaysValue : 1.0f );
  434. return;
  435. }
  436. // run through the meshes
  437. S32 start = rdata.isNoRenderNonTranslucent() ? mShape->subShapeFirstTranslucentObject[ss] : mShape->subShapeFirstObject[ss];
  438. S32 end = rdata.isNoRenderTranslucent() ? mShape->subShapeFirstTranslucentObject[ss] : mShape->subShapeFirstObject[ss] + mShape->subShapeNumObjects[ss];
  439. for (i=start; i<end; i++)
  440. {
  441. // following line is handy for debugging, to see what part of the shape that it is rendering
  442. // const char *name = mShape->names[ mMeshObjects[i].object->nameIndex ];
  443. mMeshObjects[i].render( od, mMaterialList, rdata, mAlphaAlways ? mAlphaAlwaysValue : 1.0f );
  444. }
  445. }
  446. void TSShapeInstance::setCurrentDetail( S32 dl, F32 intraDL )
  447. {
  448. PROFILE_SCOPE( TSShapeInstance_setCurrentDetail );
  449. mCurrentDetailLevel = mClamp( dl, -1, mShape->mSmallestVisibleDL );
  450. mCurrentIntraDetailLevel = intraDL > 1.0f ? 1.0f : (intraDL < 0.0f ? 0.0f : intraDL);
  451. // Restrict the chosen detail level by cutoff value.
  452. if ( smNumSkipRenderDetails > 0 && mCurrentDetailLevel >= 0 )
  453. {
  454. S32 cutoff = getMin( smNumSkipRenderDetails, mShape->mSmallestVisibleDL );
  455. if ( mCurrentDetailLevel < cutoff )
  456. {
  457. mCurrentDetailLevel = cutoff;
  458. mCurrentIntraDetailLevel = 1.0f;
  459. }
  460. }
  461. }
  462. S32 TSShapeInstance::setDetailFromPosAndScale( const SceneRenderState *state,
  463. const Point3F &pos,
  464. const Point3F &scale )
  465. {
  466. VectorF camVector = pos - state->getDiffuseCameraPosition();
  467. F32 dist = getMax( camVector.len(), 0.01f );
  468. F32 invScale = ( 1.0f / getMax( getMax( scale.x, scale.y ), scale.z ) );
  469. return setDetailFromDistance( state, dist * invScale );
  470. }
  471. S32 TSShapeInstance::setDetailFromDistance( const SceneRenderState *state, F32 scaledDistance )
  472. {
  473. PROFILE_SCOPE( TSShapeInstance_setDetailFromDistance );
  474. // For debugging/metrics.
  475. smLastScaledDistance = scaledDistance;
  476. // Shortcut if the distance is really close or negative.
  477. if ( scaledDistance <= 0.0f )
  478. {
  479. mShape->mDetailLevelLookup[0].get( mCurrentDetailLevel, mCurrentIntraDetailLevel );
  480. return mCurrentDetailLevel;
  481. }
  482. // The pixel scale is used the linearly scale the lod
  483. // selection based on the viewport size.
  484. //
  485. // The original calculation from TGEA was...
  486. //
  487. // pixelScale = viewport.extent.x * 1.6f / 640.0f;
  488. //
  489. // Since we now work on the viewport height, assuming
  490. // 4:3 aspect ratio, we've changed the reference value
  491. // to 300 to be more compatible with legacy shapes.
  492. //
  493. const F32 pixelScale = (state->getViewport().extent.x / state->getViewport().extent.y);
  494. // This is legacy DTS support for older "multires" based
  495. // meshes. The original crossbow weapon uses this.
  496. //
  497. // If we have more than one detail level and the maxError
  498. // is non-negative then we do some sort of screen error
  499. // metric for detail selection.
  500. //
  501. if ( mShape->mUseDetailFromScreenError )
  502. {
  503. // The pixel size of 1 meter at the input distance.
  504. F32 pixelRadius = state->projectRadius( scaledDistance, 1.0f ) * pixelScale;
  505. static const F32 smScreenError = 5.0f;
  506. return setDetailFromScreenError( smScreenError / pixelRadius );
  507. }
  508. // We're inlining SceneRenderState::projectRadius here to
  509. // skip the unnessasary divide by zero protection.
  510. F32 pixelRadius = ( mShape->radius / scaledDistance ) * state->getWorldToScreenScale().y * pixelScale;
  511. F32 pixelSize = pixelRadius * smDetailAdjust;
  512. if ( pixelSize < smSmallestVisiblePixelSize ) {
  513. mCurrentDetailLevel = -1;
  514. return mCurrentDetailLevel;
  515. }
  516. if ( pixelSize > smSmallestVisiblePixelSize &&
  517. pixelSize <= mShape->mSmallestVisibleSize )
  518. pixelSize = mShape->mSmallestVisibleSize + 0.01f;
  519. // For debugging/metrics.
  520. smLastPixelSize = pixelSize;
  521. // Clamp it to an acceptable range for the lookup table.
  522. U32 index = (U32)mClampF( pixelSize, 0, mShape->mDetailLevelLookup.size() - 1 );
  523. // Check the lookup table for the detail and intra detail levels.
  524. mShape->mDetailLevelLookup[ index ].get( mCurrentDetailLevel, mCurrentIntraDetailLevel );
  525. // Restrict the chosen detail level by cutoff value.
  526. if ( smNumSkipRenderDetails > 0 && mCurrentDetailLevel >= 0 )
  527. {
  528. S32 cutoff = getMin( smNumSkipRenderDetails, mShape->mSmallestVisibleDL );
  529. if ( mCurrentDetailLevel < cutoff )
  530. {
  531. mCurrentDetailLevel = cutoff;
  532. mCurrentIntraDetailLevel = 1.0f;
  533. }
  534. }
  535. return mCurrentDetailLevel;
  536. }
  537. S32 TSShapeInstance::setDetailFromScreenError( F32 errorTolerance )
  538. {
  539. PROFILE_SCOPE( TSShapeInstance_setDetailFromScreenError );
  540. // For debugging/metrics.
  541. smLastScreenErrorTolerance = errorTolerance;
  542. // note: we use 10 time the average error as the metric...this is
  543. // more robust than the maxError...the factor of 10 is to put average error
  544. // on about the same scale as maxError. The errorTOL is how much
  545. // error we are able to tolerate before going to a more detailed version of the
  546. // shape. We look for a pair of details with errors bounding our errorTOL,
  547. // and then we select an interpolation parameter to tween betwen them. Ok, so
  548. // this isn't exactly an error tolerance. A tween value of 0 is the lower poly
  549. // model (higher detail number) and a value of 1 is the higher poly model (lower
  550. // detail number).
  551. // deal with degenerate case first...
  552. // if smallest detail corresponds to less than half tolerable error, then don't even draw
  553. F32 prevErr;
  554. if ( mShape->mSmallestVisibleDL < 0 )
  555. prevErr = 0.0f;
  556. else
  557. prevErr = 10.0f * mShape->details[mShape->mSmallestVisibleDL].averageError * 20.0f;
  558. if ( mShape->mSmallestVisibleDL < 0 || prevErr < errorTolerance )
  559. {
  560. // draw last detail
  561. mCurrentDetailLevel = mShape->mSmallestVisibleDL;
  562. mCurrentIntraDetailLevel = 0.0f;
  563. return mCurrentDetailLevel;
  564. }
  565. // this function is a little odd
  566. // the reason is that the detail numbers correspond to
  567. // when we stop using a given detail level...
  568. // we search the details from most error to least error
  569. // until we fit under the tolerance (errorTOL) and then
  570. // we use the next highest detail (higher error)
  571. for (S32 i = mShape->mSmallestVisibleDL; i >= 0; i-- )
  572. {
  573. F32 err0 = 10.0f * mShape->details[i].averageError;
  574. if ( err0 < errorTolerance )
  575. {
  576. // ok, stop here
  577. // intraDL = 1 corresponds to fully this detail
  578. // intraDL = 0 corresponds to the next lower (higher number) detail
  579. mCurrentDetailLevel = i;
  580. mCurrentIntraDetailLevel = 1.0f - (errorTolerance - err0) / (prevErr - err0);
  581. return mCurrentDetailLevel;
  582. }
  583. prevErr = err0;
  584. }
  585. // get here if we are drawing at DL==0
  586. mCurrentDetailLevel = 0;
  587. mCurrentIntraDetailLevel = 1.0f;
  588. return mCurrentDetailLevel;
  589. }
  590. //-------------------------------------------------------------------------------------
  591. // Object (MeshObjectInstance & PluginObjectInstance) render methods
  592. //-------------------------------------------------------------------------------------
  593. void TSShapeInstance::ObjectInstance::render( S32, TSMaterialList *, const TSRenderState &rdata, F32 alpha )
  594. {
  595. AssertFatal(0,"TSShapeInstance::ObjectInstance::render: no default render method.");
  596. }
  597. void TSShapeInstance::MeshObjectInstance::render( S32 objectDetail,
  598. TSMaterialList *materials,
  599. const TSRenderState &rdata,
  600. F32 alpha )
  601. {
  602. PROFILE_SCOPE( TSShapeInstance_MeshObjectInstance_render );
  603. if ( forceHidden || ( ( visible * alpha ) <= 0.01f ) )
  604. return;
  605. TSMesh *mesh = getMesh(objectDetail);
  606. if ( !mesh )
  607. return;
  608. const MatrixF &transform = getTransform();
  609. if ( rdata.getCuller() )
  610. {
  611. Box3F box( mesh->getBounds() );
  612. transform.mul( box );
  613. if ( rdata.getCuller()->isCulled( box ) )
  614. return;
  615. }
  616. GFX->pushWorldMatrix();
  617. GFX->multWorld( transform );
  618. mesh->setFade( visible * alpha );
  619. // Pass a hint to the mesh that time has advanced and that the
  620. // skin is dirty and needs to be updated. This should result
  621. // in the skin only updating once per frame in most cases.
  622. const U32 currTime = Sim::getCurrentTime();
  623. bool isSkinDirty = currTime != mLastTime;
  624. mesh->render( materials,
  625. rdata,
  626. isSkinDirty,
  627. *mTransforms,
  628. mVertexBuffer,
  629. mPrimitiveBuffer );
  630. // Update the last render time.
  631. mLastTime = currTime;
  632. GFX->popWorldMatrix();
  633. }
  634. TSShapeInstance::MeshObjectInstance::MeshObjectInstance()
  635. : meshList(0), object(0), frame(0), matFrame(0),
  636. visible(1.0f), forceHidden(false), mLastTime( 0 )
  637. {
  638. }
  639. void TSShapeInstance::prepCollision()
  640. {
  641. PROFILE_SCOPE( TSShapeInstance_PrepCollision );
  642. // Iterate over all our meshes and call prepCollision on them...
  643. for(S32 i=0; i<mShape->meshes.size(); i++)
  644. {
  645. if(mShape->meshes[i])
  646. mShape->meshes[i]->prepOpcodeCollision();
  647. }
  648. }
  649. // Returns true is the shape contains any materials with accumulation enabled.
  650. bool TSShapeInstance::hasAccumulation()
  651. {
  652. bool result = false;
  653. for ( U32 i = 0; i < mMaterialList->size(); ++i )
  654. {
  655. BaseMatInstance* mat = mMaterialList->getMaterialInst(i);
  656. if ( mat->hasAccumulation() )
  657. result = true;
  658. }
  659. return result;
  660. }