tsShapeInstance.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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 2000. 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. mUseOverrideTexture = false;
  105. buildInstanceData( mShape, loadMaterials );
  106. }
  107. TSShapeInstance::TSShapeInstance( TSShape *shape, bool loadMaterials )
  108. {
  109. VECTOR_SET_ASSOCIATION(mMeshObjects);
  110. VECTOR_SET_ASSOCIATION(mNodeTransforms);
  111. VECTOR_SET_ASSOCIATION(mNodeReferenceRotations);
  112. VECTOR_SET_ASSOCIATION(mNodeReferenceTranslations);
  113. VECTOR_SET_ASSOCIATION(mNodeReferenceUniformScales);
  114. VECTOR_SET_ASSOCIATION(mNodeReferenceScaleFactors);
  115. VECTOR_SET_ASSOCIATION(mNodeReferenceArbitraryScaleRots);
  116. VECTOR_SET_ASSOCIATION(mThreadList);
  117. VECTOR_SET_ASSOCIATION(mTransitionThreads);
  118. mShapeResource = NULL;
  119. mShape = shape;
  120. mUseOverrideTexture = false;
  121. buildInstanceData( mShape, loadMaterials );
  122. }
  123. TSShapeInstance::~TSShapeInstance()
  124. {
  125. mMeshObjects.clear();
  126. while (mThreadList.size())
  127. destroyThread(mThreadList.last());
  128. setMaterialList(NULL);
  129. delete [] mDirtyFlags;
  130. }
  131. void TSShapeInstance::buildInstanceData(TSShape * _shape, bool loadMaterials)
  132. {
  133. mShape = _shape;
  134. debrisRefCount = 0;
  135. mCurrentDetailLevel = 0;
  136. mCurrentIntraDetailLevel = 1.0f;
  137. // all triggers off at start
  138. mTriggerStates = 0;
  139. //
  140. mAlphaAlways = false;
  141. mAlphaAlwaysValue = 1.0f;
  142. // material list...
  143. mMaterialList = NULL;
  144. mOwnMaterialList = false;
  145. mUseOwnBuffer = false;
  146. //
  147. mData = 0;
  148. mScaleCurrentlyAnimated = false;
  149. if(loadMaterials)
  150. setMaterialList(mShape->materialList);
  151. // set up node data
  152. initNodeTransforms();
  153. // add objects to trees
  154. initMeshObjects();
  155. // set up subtree data
  156. S32 ss = mShape->subShapeFirstNode.size(); // we have this many subtrees
  157. mDirtyFlags = new U32[ss];
  158. mGroundThread = NULL;
  159. mCurrentDetailLevel = 0;
  160. animateSubtrees();
  161. // Construct billboards if not done already
  162. if ( loadMaterials && mShapeResource && GFXDevice::devicePresent() )
  163. mShape->setupBillboardDetails( mShapeResource.getPath().getFullPath() );
  164. }
  165. void TSShapeInstance::initNodeTransforms()
  166. {
  167. // set up node data
  168. S32 numNodes = mShape->nodes.size();
  169. mNodeTransforms.setSize(numNodes);
  170. }
  171. void TSShapeInstance::initMeshObjects()
  172. {
  173. // add objects to trees
  174. S32 numObjects = mShape->objects.size();
  175. mMeshObjects.setSize(numObjects);
  176. for (S32 i=0; i<numObjects; i++)
  177. {
  178. const TSObject * obj = &mShape->objects[i];
  179. MeshObjectInstance * objInst = &mMeshObjects[i];
  180. // hook up the object to it's node and transforms.
  181. objInst->mTransforms = &mNodeTransforms;
  182. objInst->nodeIndex = obj->nodeIndex;
  183. // set up list of meshes
  184. if (obj->numMeshes)
  185. objInst->meshList = &mShape->meshes[obj->startMeshIndex];
  186. else
  187. objInst->meshList = NULL;
  188. objInst->object = obj;
  189. objInst->forceHidden = false;
  190. }
  191. }
  192. void TSShapeInstance::setMaterialList( TSMaterialList *matList )
  193. {
  194. // get rid of old list
  195. if ( mOwnMaterialList )
  196. delete mMaterialList;
  197. mMaterialList = matList;
  198. mOwnMaterialList = false;
  199. // If the material list is already be mapped then
  200. // don't bother doing the initializing a second time.
  201. // Note: only check the last material instance as this will catch both
  202. // uninitialised lists, as well as initialised lists that have had new
  203. // materials appended
  204. if ( mMaterialList && !mMaterialList->getMaterialInst( mMaterialList->size()-1 ) )
  205. {
  206. mMaterialList->setTextureLookupPath( mShapeResource.getPath().getPath() );
  207. mMaterialList->mapMaterials();
  208. Material::sAllowTextureTargetAssignment = true;
  209. initMaterialList();
  210. Material::sAllowTextureTargetAssignment = false;
  211. }
  212. }
  213. void TSShapeInstance::cloneMaterialList( const FeatureSet *features )
  214. {
  215. if ( mOwnMaterialList )
  216. return;
  217. Material::sAllowTextureTargetAssignment = true;
  218. mMaterialList = new TSMaterialList(mMaterialList);
  219. initMaterialList( features );
  220. Material::sAllowTextureTargetAssignment = false;
  221. mOwnMaterialList = true;
  222. }
  223. void TSShapeInstance::initMaterialList( const FeatureSet *features )
  224. {
  225. // If we don't have features then use the default.
  226. if ( !features )
  227. features = &MATMGR->getDefaultFeatures();
  228. // Initialize the materials.
  229. mMaterialList->initMatInstances( *features, mShape->getVertexFormat() );
  230. // TODO: It would be good to go thru all the meshes and
  231. // pre-create all the active material hooks for shadows,
  232. // reflections, and instancing. This would keep these
  233. // hiccups from happening at runtime.
  234. }
  235. void TSShapeInstance::reSkin( String newBaseName, String oldBaseName )
  236. {
  237. if( newBaseName.isEmpty() )
  238. newBaseName = "base";
  239. if( oldBaseName.isEmpty() )
  240. oldBaseName = "base";
  241. if ( newBaseName.equal( oldBaseName, String::NoCase ) )
  242. return;
  243. const U32 oldBaseNameLength = oldBaseName.length();
  244. // Make our own copy of the materials list from the resource if necessary
  245. if (ownMaterialList() == false)
  246. cloneMaterialList();
  247. TSMaterialList* pMatList = getMaterialList();
  248. pMatList->setTextureLookupPath( mShapeResource.getPath().getPath() );
  249. // Cycle through the materials
  250. const Vector<String> &materialNames = pMatList->getMaterialNameList();
  251. for ( S32 i = 0; i < materialNames.size(); i++ )
  252. {
  253. // Try changing base
  254. const String &pName = materialNames[i];
  255. String newName( String::ToLower(pName) );
  256. newName.replace( String::ToLower(oldBaseName), String::ToLower(newBaseName) );
  257. pMatList->renameMaterial( i, newName );
  258. }
  259. // Initialize the material instances
  260. initMaterialList();
  261. }
  262. void TSShapeInstance::resetMaterialList()
  263. {
  264. TSMaterialList* oMatlist = mShape->materialList;
  265. setMaterialList(oMatlist);
  266. }
  267. //-------------------------------------------------------------------------------------
  268. // Render & detail selection
  269. //-------------------------------------------------------------------------------------
  270. void TSShapeInstance::renderDebugNormals( F32 normalScalar, S32 dl )
  271. {
  272. if ( dl < 0 )
  273. return;
  274. AssertFatal( dl >= 0 && dl < mShape->details.size(),
  275. "TSShapeInstance::renderDebugNormals() - Bad detail level!" );
  276. static GFXStateBlockRef sb;
  277. if ( sb.isNull() )
  278. {
  279. GFXStateBlockDesc desc;
  280. desc.setCullMode( GFXCullNone );
  281. desc.setZReadWrite( true );
  282. desc.zWriteEnable = false;
  283. desc.vertexColorEnable = true;
  284. sb = GFX->createStateBlock( desc );
  285. }
  286. GFX->setStateBlock( sb );
  287. const TSDetail *detail = &mShape->details[dl];
  288. const S32 ss = detail->subShapeNum;
  289. if ( ss < 0 )
  290. return;
  291. const S32 start = mShape->subShapeFirstObject[ss];
  292. const S32 end = start + mShape->subShapeNumObjects[ss];
  293. for ( S32 i = start; i < end; i++ )
  294. {
  295. MeshObjectInstance *meshObj = &mMeshObjects[i];
  296. if ( !meshObj )
  297. continue;
  298. const MatrixF &meshMat = meshObj->getTransform();
  299. // Then go through each TSMesh...
  300. U32 m = 0;
  301. for( TSMesh *mesh = meshObj->getMesh(m); mesh != NULL; mesh = meshObj->getMesh(m++) )
  302. {
  303. // and pull out the list of normals.
  304. const U32 numNrms = mesh->mNumVerts;
  305. PrimBuild::begin( GFXLineList, 2 * numNrms );
  306. for ( U32 n = 0; n < numNrms; n++ )
  307. {
  308. const TSMesh::__TSMeshVertexBase &v = mesh->mVertexData.getBase(n);
  309. Point3F norm = v.normal();
  310. Point3F vert = v.vert();
  311. meshMat.mulP( vert );
  312. meshMat.mulV( norm );
  313. // Then render them.
  314. PrimBuild::color4f( mFabs( norm.x ), mFabs( norm.y ), mFabs( norm.z ), 1.0f );
  315. PrimBuild::vertex3fv( vert );
  316. PrimBuild::vertex3fv( vert + (norm * normalScalar) );
  317. }
  318. PrimBuild::end();
  319. }
  320. }
  321. }
  322. void TSShapeInstance::renderDebugNodes()
  323. {
  324. GFXDrawUtil *drawUtil = GFX->getDrawUtil();
  325. ColorI color( 255, 0, 0, 255 );
  326. GFXStateBlockDesc desc;
  327. desc.setBlend( false );
  328. desc.setZReadWrite( false, false );
  329. for ( U32 i = 0; i < mNodeTransforms.size(); i++ )
  330. drawUtil->drawTransform( desc, mNodeTransforms[i], NULL, NULL );
  331. }
  332. void TSShapeInstance::listMeshes( const String &state ) const
  333. {
  334. if ( state.equal( "All", String::NoCase ) )
  335. {
  336. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  337. {
  338. const MeshObjectInstance &mesh = mMeshObjects[i];
  339. Con::warnf( "meshidx %3d, %8s, %s", i, ( mesh.forceHidden ) ? "Hidden" : "Visible", mShape->getMeshName(i).c_str() );
  340. }
  341. }
  342. else if ( state.equal( "Hidden", String::NoCase ) )
  343. {
  344. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  345. {
  346. const MeshObjectInstance &mesh = mMeshObjects[i];
  347. if ( mesh.forceHidden )
  348. Con::warnf( "meshidx %3d, %8s, %s", i, "Visible", mShape->getMeshName(i).c_str() );
  349. }
  350. }
  351. else if ( state.equal( "Visible", String::NoCase ) )
  352. {
  353. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  354. {
  355. const MeshObjectInstance &mesh = mMeshObjects[i];
  356. if ( !mesh.forceHidden )
  357. Con::warnf( "meshidx %3d, %8s, %s", i, "Hidden", mShape->getMeshName(i).c_str() );
  358. }
  359. }
  360. else
  361. {
  362. Con::warnf( "TSShapeInstance::listMeshes( %s ) - only All/Hidden/Visible are valid parameters." );
  363. }
  364. }
  365. void TSShapeInstance::render( const TSRenderState &rdata )
  366. {
  367. if (mCurrentDetailLevel<0)
  368. return;
  369. PROFILE_SCOPE( TSShapeInstance_Render );
  370. // alphaIn: we start to alpha-in next detail level when intraDL > 1-alphaIn-alphaOut
  371. // (finishing when intraDL = 1-alphaOut)
  372. // alphaOut: start to alpha-out this detail level when intraDL > 1-alphaOut
  373. // NOTE:
  374. // intraDL is at 1 when if shape were any closer to us we'd be at dl-1,
  375. // intraDL is at 0 when if shape were any farther away we'd be at dl+1
  376. F32 alphaOut = mShape->alphaOut[mCurrentDetailLevel];
  377. F32 alphaIn = mShape->alphaIn[mCurrentDetailLevel];
  378. F32 saveAA = mAlphaAlways ? mAlphaAlwaysValue : 1.0f;
  379. /// This first case is the single detail level render.
  380. if ( mCurrentIntraDetailLevel > alphaIn + alphaOut )
  381. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  382. else if ( mCurrentIntraDetailLevel > alphaOut )
  383. {
  384. // draw this detail level w/ alpha=1 and next detail level w/
  385. // alpha=1-(intraDl-alphaOut)/alphaIn
  386. // first draw next detail level
  387. if ( mCurrentDetailLevel + 1 < mShape->details.size() && mShape->details[ mCurrentDetailLevel + 1 ].size > 0.0f )
  388. {
  389. setAlphaAlways( saveAA * ( alphaIn + alphaOut - mCurrentIntraDetailLevel ) / alphaIn );
  390. render( rdata, mCurrentDetailLevel + 1, 0.0f );
  391. }
  392. setAlphaAlways( saveAA );
  393. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  394. }
  395. else
  396. {
  397. // draw next detail level w/ alpha=1 and this detail level w/
  398. // alpha = 1-intraDL/alphaOut
  399. // first draw next detail level
  400. if ( mCurrentDetailLevel + 1 < mShape->details.size() && mShape->details[ mCurrentDetailLevel + 1 ].size > 0.0f )
  401. render( rdata, mCurrentDetailLevel+1, 0.0f );
  402. setAlphaAlways( saveAA * mCurrentIntraDetailLevel / alphaOut );
  403. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  404. setAlphaAlways( saveAA );
  405. }
  406. }
  407. void TSShapeInstance::setMeshForceHidden( const char *meshName, bool hidden )
  408. {
  409. Vector<MeshObjectInstance>::iterator iter = mMeshObjects.begin();
  410. for ( ; iter != mMeshObjects.end(); iter++ )
  411. {
  412. S32 nameIndex = iter->object->nameIndex;
  413. const char *name = mShape->names[ nameIndex ];
  414. if ( String::compare( meshName, name ) == 0 )
  415. {
  416. iter->forceHidden = hidden;
  417. return;
  418. }
  419. }
  420. }
  421. void TSShapeInstance::setMeshForceHidden( S32 meshIndex, bool hidden )
  422. {
  423. AssertFatal( meshIndex > -1 && meshIndex < mMeshObjects.size(),
  424. "TSShapeInstance::setMeshForceHidden - Invalid index!" );
  425. mMeshObjects[meshIndex].forceHidden = hidden;
  426. }
  427. void TSShapeInstance::render( const TSRenderState &rdata, S32 dl, F32 intraDL )
  428. {
  429. AssertFatal( dl >= 0 && dl < mShape->details.size(),"TSShapeInstance::render" );
  430. S32 i;
  431. const TSDetail * detail = &mShape->details[dl];
  432. S32 ss = detail->subShapeNum;
  433. S32 od = detail->objectDetailNum;
  434. // if we're a billboard detail, draw it and exit
  435. if ( ss < 0 )
  436. {
  437. PROFILE_SCOPE( TSShapeInstance_RenderBillboards );
  438. if ( !rdata.isNoRenderTranslucent() && ( TSLastDetail::smCanShadow || !rdata.getSceneState()->isShadowPass() ) )
  439. mShape->billboardDetails[ dl ]->render( rdata, mAlphaAlways ? mAlphaAlwaysValue : 1.0f );
  440. return;
  441. }
  442. S32 start = rdata.isNoRenderNonTranslucent() ? mShape->subShapeFirstTranslucentObject[ss] : mShape->subShapeFirstObject[ss];
  443. S32 end = rdata.isNoRenderTranslucent() ? mShape->subShapeFirstTranslucentObject[ss] : mShape->subShapeFirstObject[ss] + mShape->subShapeNumObjects[ss];
  444. TSVertexBufferHandle *realBuffer;
  445. if (TSShape::smUseHardwareSkinning && !mUseOwnBuffer)
  446. {
  447. // For hardware skinning, just using the buffer associated with the shape will work fine
  448. realBuffer = &mShape->mShapeVertexBuffer;
  449. }
  450. else
  451. {
  452. // For software skinning, we need to update our own buffer each frame
  453. realBuffer = &mSoftwareVertexBuffer;
  454. if (realBuffer->getPointer() == NULL)
  455. {
  456. mShape->getVertexBuffer(*realBuffer, GFXBufferTypeDynamic);
  457. }
  458. if (bufferNeedsUpdate(od, start, end))
  459. {
  460. U8 *buffer = realBuffer->lock();
  461. if (!buffer)
  462. return;
  463. // Base vertex data
  464. dMemcpy(buffer, mShape->mShapeVertexData.base, mShape->mShapeVertexData.size);
  465. // Apply skinned verts (where applicable)
  466. for (i = start; i < end; i++)
  467. {
  468. mMeshObjects[i].updateVertexBuffer(od, buffer);
  469. }
  470. realBuffer->unlock();
  471. }
  472. }
  473. // run through the meshes
  474. for (i=start; i<end; i++)
  475. {
  476. TSRenderState objState = rdata;
  477. // following line is handy for debugging, to see what part of the shape that it is rendering
  478. const char *name = mShape->names[ mMeshObjects[i].object->nameIndex ];
  479. mMeshObjects[i].render( od, *realBuffer, mMaterialList, objState, mAlphaAlways ? mAlphaAlwaysValue : 1.0f, name );
  480. }
  481. }
  482. bool TSShapeInstance::bufferNeedsUpdate(S32 objectDetail, S32 start, S32 end)
  483. {
  484. // run through the meshes
  485. for (U32 i = start; i<end; i++)
  486. {
  487. if (mMeshObjects[i].bufferNeedsUpdate(objectDetail))
  488. return true;
  489. }
  490. return false;
  491. }
  492. void TSShapeInstance::setCurrentDetail( S32 dl, F32 intraDL )
  493. {
  494. PROFILE_SCOPE( TSShapeInstance_setCurrentDetail );
  495. mCurrentDetailLevel = mClamp( dl, -1, mShape->mSmallestVisibleDL );
  496. mCurrentIntraDetailLevel = intraDL > 1.0f ? 1.0f : (intraDL < 0.0f ? 0.0f : intraDL);
  497. // Restrict the chosen detail level by cutoff value.
  498. if ( smNumSkipRenderDetails > 0 && mCurrentDetailLevel >= 0 )
  499. {
  500. S32 cutoff = getMin( smNumSkipRenderDetails, mShape->mSmallestVisibleDL );
  501. if ( mCurrentDetailLevel < cutoff )
  502. {
  503. mCurrentDetailLevel = cutoff;
  504. mCurrentIntraDetailLevel = 1.0f;
  505. }
  506. }
  507. }
  508. S32 TSShapeInstance::setDetailFromPosAndScale( const SceneRenderState *state,
  509. const Point3F &pos,
  510. const Point3F &scale )
  511. {
  512. VectorF camVector = pos - state->getDiffuseCameraPosition();
  513. F32 dist = getMax( camVector.len(), 0.01f );
  514. F32 invScale = ( 1.0f / getMax( getMax( scale.x, scale.y ), scale.z ) );
  515. return setDetailFromDistance( state, dist * invScale );
  516. }
  517. S32 TSShapeInstance::setDetailFromDistance( const SceneRenderState *state, F32 scaledDistance )
  518. {
  519. PROFILE_SCOPE( TSShapeInstance_setDetailFromDistance );
  520. // For debugging/metrics.
  521. smLastScaledDistance = scaledDistance;
  522. // Shortcut if the distance is really close or negative.
  523. if ( scaledDistance <= 0.0f )
  524. {
  525. mShape->mDetailLevelLookup[0].get( mCurrentDetailLevel, mCurrentIntraDetailLevel );
  526. return mCurrentDetailLevel;
  527. }
  528. // The pixel scale is used the linearly scale the lod
  529. // selection based on the viewport size.
  530. //
  531. // The original calculation from TGEA was...
  532. //
  533. // pixelScale = viewport.extent.x * 1.6f / 640.0f;
  534. //
  535. // Since we now work on the viewport height, assuming
  536. // 4:3 aspect ratio, we've changed the reference value
  537. // to 300 to be more compatible with legacy shapes.
  538. //
  539. const F32 pixelScale = (state->getViewport().extent.x / state->getViewport().extent.y)*2;
  540. // This is legacy DTS support for older "multires" based
  541. // meshes. The original crossbow weapon uses this.
  542. //
  543. // If we have more than one detail level and the maxError
  544. // is non-negative then we do some sort of screen error
  545. // metric for detail selection.
  546. //
  547. if ( mShape->mUseDetailFromScreenError )
  548. {
  549. // The pixel size of 1 meter at the input distance.
  550. F32 pixelRadius = state->projectRadius( scaledDistance, 1.0f ) * pixelScale;
  551. static const F32 smScreenError = 5.0f;
  552. return setDetailFromScreenError( smScreenError / pixelRadius );
  553. }
  554. // We're inlining SceneRenderState::projectRadius here to
  555. // skip the unnessasary divide by zero protection.
  556. F32 pixelRadius = ( mShape->mRadius / scaledDistance ) * state->getWorldToScreenScale().y * pixelScale;
  557. F32 pixelSize = pixelRadius * smDetailAdjust;
  558. if ( pixelSize < smSmallestVisiblePixelSize ) {
  559. mCurrentDetailLevel = -1;
  560. return mCurrentDetailLevel;
  561. }
  562. if ( pixelSize > smSmallestVisiblePixelSize &&
  563. pixelSize <= mShape->mSmallestVisibleSize )
  564. pixelSize = mShape->mSmallestVisibleSize + 0.01f;
  565. // For debugging/metrics.
  566. smLastPixelSize = pixelSize;
  567. // Clamp it to an acceptable range for the lookup table.
  568. U32 index = (U32)mClampF( pixelSize, 0, mShape->mDetailLevelLookup.size() - 1 );
  569. // Check the lookup table for the detail and intra detail levels.
  570. mShape->mDetailLevelLookup[ index ].get( mCurrentDetailLevel, mCurrentIntraDetailLevel );
  571. // Restrict the chosen detail level by cutoff value.
  572. if ( smNumSkipRenderDetails > 0 && mCurrentDetailLevel >= 0 )
  573. {
  574. S32 cutoff = getMin( smNumSkipRenderDetails, mShape->mSmallestVisibleDL );
  575. if ( mCurrentDetailLevel < cutoff )
  576. {
  577. mCurrentDetailLevel = cutoff;
  578. mCurrentIntraDetailLevel = 1.0f;
  579. }
  580. }
  581. return mCurrentDetailLevel;
  582. }
  583. S32 TSShapeInstance::setDetailFromScreenError( F32 errorTolerance )
  584. {
  585. PROFILE_SCOPE( TSShapeInstance_setDetailFromScreenError );
  586. // For debugging/metrics.
  587. smLastScreenErrorTolerance = errorTolerance;
  588. // note: we use 10 time the average error as the metric...this is
  589. // more robust than the maxError...the factor of 10 is to put average error
  590. // on about the same scale as maxError. The errorTOL is how much
  591. // error we are able to tolerate before going to a more detailed version of the
  592. // shape. We look for a pair of details with errors bounding our errorTOL,
  593. // and then we select an interpolation parameter to tween betwen them. Ok, so
  594. // this isn't exactly an error tolerance. A tween value of 0 is the lower poly
  595. // model (higher detail number) and a value of 1 is the higher poly model (lower
  596. // detail number).
  597. // deal with degenerate case first...
  598. // if smallest detail corresponds to less than half tolerable error, then don't even draw
  599. F32 prevErr;
  600. if ( mShape->mSmallestVisibleDL < 0 )
  601. prevErr = 0.0f;
  602. else
  603. prevErr = 10.0f * mShape->details[mShape->mSmallestVisibleDL].averageError * 20.0f;
  604. if ( mShape->mSmallestVisibleDL < 0 || prevErr < errorTolerance )
  605. {
  606. // draw last detail
  607. mCurrentDetailLevel = mShape->mSmallestVisibleDL;
  608. mCurrentIntraDetailLevel = 0.0f;
  609. return mCurrentDetailLevel;
  610. }
  611. // this function is a little odd
  612. // the reason is that the detail numbers correspond to
  613. // when we stop using a given detail level...
  614. // we search the details from most error to least error
  615. // until we fit under the tolerance (errorTOL) and then
  616. // we use the next highest detail (higher error)
  617. for (S32 i = mShape->mSmallestVisibleDL; i >= 0; i-- )
  618. {
  619. F32 err0 = 10.0f * mShape->details[i].averageError;
  620. if ( err0 < errorTolerance )
  621. {
  622. // ok, stop here
  623. // intraDL = 1 corresponds to fully this detail
  624. // intraDL = 0 corresponds to the next lower (higher number) detail
  625. mCurrentDetailLevel = i;
  626. mCurrentIntraDetailLevel = 1.0f - (errorTolerance - err0) / (prevErr - err0);
  627. return mCurrentDetailLevel;
  628. }
  629. prevErr = err0;
  630. }
  631. // get here if we are drawing at DL==0
  632. mCurrentDetailLevel = 0;
  633. mCurrentIntraDetailLevel = 1.0f;
  634. return mCurrentDetailLevel;
  635. }
  636. //-------------------------------------------------------------------------------------
  637. // Object (MeshObjectInstance & PluginObjectInstance) render methods
  638. //-------------------------------------------------------------------------------------
  639. void TSShapeInstance::ObjectInstance::render( S32, TSVertexBufferHandle &vb, TSMaterialList *, TSRenderState &rdata, F32 alpha, const char *meshName )
  640. {
  641. AssertFatal(0,"TSShapeInstance::ObjectInstance::render: no default render method.");
  642. }
  643. void TSShapeInstance::ObjectInstance::updateVertexBuffer( S32 objectDetail, U8 *buffer )
  644. {
  645. AssertFatal(0, "TSShapeInstance::ObjectInstance::updateVertexBuffer: no default vertex buffer update method.");
  646. }
  647. bool TSShapeInstance::ObjectInstance::bufferNeedsUpdate( S32 objectDetai )
  648. {
  649. return false;
  650. }
  651. void TSShapeInstance::MeshObjectInstance::render( S32 objectDetail,
  652. TSVertexBufferHandle &vb,
  653. TSMaterialList *materials,
  654. TSRenderState &rdata,
  655. F32 alpha,
  656. const char *meshName )
  657. {
  658. PROFILE_SCOPE( TSShapeInstance_MeshObjectInstance_render );
  659. if ( forceHidden || ( ( visible * alpha ) <= 0.01f ) )
  660. return;
  661. TSMesh *mesh = getMesh(objectDetail);
  662. if ( !mesh )
  663. return;
  664. const MatrixF &transform = getTransform();
  665. if ( rdata.getCuller() )
  666. {
  667. Box3F box( mesh->getBounds() );
  668. transform.mul( box );
  669. if ( rdata.getCuller()->isCulled( box ) )
  670. return;
  671. }
  672. GFX->pushWorldMatrix();
  673. GFX->multWorld( transform );
  674. mesh->setFade( visible * alpha );
  675. // Pass a hint to the mesh that time has advanced and that the
  676. // skin is dirty and needs to be updated. This should result
  677. // in the skin only updating once per frame in most cases.
  678. const U32 currTime = Sim::getCurrentTime();
  679. bool isSkinDirty = (currTime != mLastTime) || (objectDetail != mLastObjectDetail);
  680. // Update active transform list for bones for GPU skinning
  681. if ( mesh->getMeshType() == TSMesh::SkinMeshType )
  682. {
  683. if (isSkinDirty)
  684. {
  685. static_cast<TSSkinMesh*>(mesh)->updateSkinBones(*mTransforms, mActiveTransforms);
  686. }
  687. rdata.setNodeTransforms(mActiveTransforms.address(), mActiveTransforms.size());
  688. }
  689. mesh->render( materials,
  690. rdata,
  691. isSkinDirty,
  692. *mTransforms,
  693. vb,
  694. meshName );
  695. // Update the last render time.
  696. mLastTime = currTime;
  697. mLastObjectDetail = objectDetail;
  698. GFX->popWorldMatrix();
  699. }
  700. void TSShapeInstance::MeshObjectInstance::updateVertexBuffer(S32 objectDetail, U8 *buffer)
  701. {
  702. PROFILE_SCOPE(TSShapeInstance_MeshObjectInstance_updateVertexBuffer);
  703. if (forceHidden || ((visible) <= 0.01f))
  704. return;
  705. TSMesh *mesh = getMesh(objectDetail);
  706. if (!mesh)
  707. return;
  708. // Update the buffer here
  709. if (mesh->getMeshType() == TSMesh::SkinMeshType)
  710. {
  711. static_cast<TSSkinMesh*>(mesh)->updateSkinBuffer(*mTransforms, buffer);
  712. }
  713. mLastTime = Sim::getCurrentTime();
  714. }
  715. bool TSShapeInstance::MeshObjectInstance::bufferNeedsUpdate( S32 objectDetail )
  716. {
  717. TSMesh *mesh = getMesh(objectDetail);
  718. const U32 currTime = Sim::getCurrentTime();
  719. return mesh && mesh->getMeshType() == TSMesh::SkinMeshType && currTime != mLastTime;
  720. }
  721. TSShapeInstance::MeshObjectInstance::MeshObjectInstance()
  722. : meshList(0), object(0), frame(0), matFrame(0),
  723. visible(1.0f), forceHidden(false), mLastTime(0), mLastObjectDetail(0)
  724. {
  725. }
  726. void TSShapeInstance::prepCollision()
  727. {
  728. PROFILE_SCOPE( TSShapeInstance_PrepCollision );
  729. // Iterate over all our meshes and call prepCollision on them...
  730. for(S32 i=0; i<mShape->meshes.size(); i++)
  731. {
  732. if(mShape->meshes[i])
  733. mShape->meshes[i]->prepOpcodeCollision();
  734. }
  735. }
  736. // Returns true is the shape contains any materials with accumulation enabled.
  737. bool TSShapeInstance::hasAccumulation()
  738. {
  739. bool result = false;
  740. for ( U32 i = 0; i < mMaterialList->size(); ++i )
  741. {
  742. BaseMatInstance* mat = mMaterialList->getMaterialInst(i);
  743. if ( mat->hasAccumulation() )
  744. result = true;
  745. }
  746. return result;
  747. }
  748. void TSShapeInstance::setUseOwnBuffer()
  749. {
  750. mUseOwnBuffer = true;
  751. }