gfxDevice.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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 "gfx/gfxDevice.h"
  24. #include "gfx/gfxInit.h"
  25. #include "gfx/gfxCubemap.h"
  26. #include "gfx/primBuilder.h"
  27. #include "gfx/gfxDrawUtil.h"
  28. #include "gfx/gfxFence.h"
  29. #include "gfx/gfxFontRenderBatcher.h"
  30. #include "gfx/gfxPrimitiveBuffer.h"
  31. #include "gfx/gfxShader.h"
  32. #include "gfx/gfxStateBlock.h"
  33. #include "gfx/screenshot.h"
  34. #include "gfx/gfxStringEnumTranslate.h"
  35. #include "gfx/gfxTextureManager.h"
  36. #include "core/frameAllocator.h"
  37. #include "core/stream/fileStream.h"
  38. #include "core/strings/unicode.h"
  39. #include "core/util/journal/process.h"
  40. #include "core/util/safeDelete.h"
  41. #include "math/util/frustum.h"
  42. #include "console/consoleTypes.h"
  43. #include "console/engineAPI.h"
  44. GFXDevice * GFXDevice::smGFXDevice = NULL;
  45. bool GFXDevice::smWireframe = false;
  46. bool GFXDevice::smDisableVSync = true;
  47. F32 GFXDevice::smForcedPixVersion = -1.0f;
  48. bool GFXDevice::smDisableOcclusionQuery = false;
  49. bool gDisassembleAllShaders = false;
  50. void GFXDevice::initConsole()
  51. {
  52. GFXStringEnumTranslate::init();
  53. Con::addVariable( "$gfx::wireframe", TypeBool, &smWireframe,
  54. "Used to toggle wireframe rendering at runtime.\n"
  55. "@ingroup GFX\n" );
  56. Con::addVariable( "$gfx::disassembleAllShaders", TypeBool, &gDisassembleAllShaders,
  57. "On supported devices this will dump shader disassembly to the "
  58. "procedural shader folder.\n"
  59. "@ingroup GFX\n" );
  60. Con::addVariable( "$gfx::disableOcclusionQuery", TypeBool, &smDisableOcclusionQuery,
  61. "Debug helper that disables all hardware occlusion queries causing "
  62. "them to return only the visibile state.\n"
  63. "@ingroup GFX\n" );
  64. Con::addVariable( "$pref::Video::disableVerticalSync", TypeBool, &smDisableVSync,
  65. "Disables vertical sync on the active device.\n"
  66. "@note The video mode must be reset for the change to take affect.\n"
  67. "@ingroup GFX\n" );
  68. Con::addVariable( "$pref::Video::forcedPixVersion", TypeF32, &smForcedPixVersion,
  69. "Will force the shader model if the value is positive and less than the "
  70. "shader model supported by the active device. Use 0 for fixed function.\n"
  71. "@note The graphics device must be reset for the change to take affect.\n"
  72. "@ingroup GFX\n" );
  73. }
  74. GFXDevice::DeviceEventSignal& GFXDevice::getDeviceEventSignal()
  75. {
  76. static DeviceEventSignal theSignal;
  77. return theSignal;
  78. }
  79. GFXDevice::GFXDevice()
  80. {
  81. VECTOR_SET_ASSOCIATION( mVideoModes );
  82. VECTOR_SET_ASSOCIATION( mRTStack );
  83. mWorldMatrixDirty = false;
  84. mWorldStackSize = 0;
  85. mProjectionMatrixDirty = false;
  86. mViewMatrixDirty = false;
  87. mTextureMatrixCheckDirty = false;
  88. mViewMatrix.identity();
  89. mProjectionMatrix.identity();
  90. for( S32 i = 0; i < WORLD_STACK_MAX; i++ )
  91. mWorldMatrix[i].identity();
  92. AssertFatal(smGFXDevice == NULL, "Already a GFXDevice created! Bad!");
  93. smGFXDevice = this;
  94. // Vertex buffer cache
  95. mCurrVertexDecl = NULL;
  96. mVertexDeclDirty = false;
  97. for ( U32 i=0; i < VERTEX_STREAM_COUNT; i++ )
  98. {
  99. mVertexBufferDirty[i] = false;
  100. mVertexBufferFrequency[i] = 0;
  101. mVertexBufferFrequencyDirty[i] = false;
  102. }
  103. // Primitive buffer cache
  104. mPrimitiveBufferDirty = false;
  105. mTexturesDirty = false;
  106. // Use of TEXTURE_STAGE_COUNT in initialization is okay [7/2/2007 Pat]
  107. for(U32 i = 0; i < TEXTURE_STAGE_COUNT; i++)
  108. {
  109. mTextureDirty[i] = false;
  110. mCurrentTexture[i] = NULL;
  111. mNewTexture[i] = NULL;
  112. mCurrentCubemap[i] = NULL;
  113. mNewCubemap[i] = NULL;
  114. mCurrentCubemapArray[i] = NULL;
  115. mNewTextureArray[i] = NULL;
  116. mCurrentTextureArray[i] = NULL;
  117. mNewCubemapArray[i] = NULL;
  118. mTexType[i] = GFXTDT_Normal;
  119. mTextureMatrix[i].identity();
  120. mTextureMatrixDirty[i] = false;
  121. }
  122. mLightsDirty = false;
  123. for(U32 i = 0; i < LIGHT_STAGE_COUNT; i++)
  124. {
  125. mLightDirty[i] = false;
  126. mCurrentLightEnable[i] = false;
  127. }
  128. mGlobalAmbientColorDirty = false;
  129. mGlobalAmbientColor = LinearColorF(0.0f, 0.0f, 0.0f, 1.0f);
  130. mLightMaterialDirty = false;
  131. dMemset(&mCurrentLightMaterial, 0, sizeof(GFXLightMaterial));
  132. // State block
  133. mStateBlockDirty = false;
  134. mCurrentStateBlock = NULL;
  135. mNewStateBlock = NULL;
  136. mCurrentShaderConstBuffer = NULL;
  137. // misc
  138. mAllowRender = true;
  139. mCurrentRenderStyle = RS_Standard;
  140. mCurrentStereoTarget = -1;
  141. mStereoHeadTransform = MatrixF(1);
  142. mCanCurrentlyRender = false;
  143. mInitialized = false;
  144. mRTDirty = false;
  145. mViewport = RectI::Zero;
  146. mViewportDirty = false;
  147. mCurrentFrontBufferIdx = 0;
  148. mDeviceSwizzle32 = NULL;
  149. mDeviceSwizzle24 = NULL;
  150. mResourceListHead = NULL;
  151. mCardProfiler = NULL;
  152. // Initialize our drawing utility.
  153. mDrawer = NULL;
  154. mFrameTime = PlatformTimer::create();
  155. // Add a few system wide shader macros.
  156. GFXShader::addGlobalMacro( "TORQUE", "1" );
  157. GFXShader::addGlobalMacro( "TORQUE_VERSION", String::ToString(getVersionNumber()) );
  158. #if defined TORQUE_OS_WIN
  159. GFXShader::addGlobalMacro( "TORQUE_OS_WIN" );
  160. #elif defined TORQUE_OS_MAC
  161. GFXShader::addGlobalMacro( "TORQUE_OS_MAC" );
  162. #elif defined TORQUE_OS_LINUX
  163. GFXShader::addGlobalMacro( "TORQUE_OS_LINUX" );
  164. #endif
  165. mStereoTargets[0] = NULL;
  166. mStereoTargets[1] = NULL;
  167. }
  168. GFXDrawUtil* GFXDevice::getDrawUtil()
  169. {
  170. if (!mDrawer)
  171. {
  172. mDrawer = new GFXDrawUtil(this);
  173. }
  174. return mDrawer;
  175. }
  176. void GFXDevice::deviceInited()
  177. {
  178. getDeviceEventSignal().trigger(deInit);
  179. mDeviceStatistics.setPrefix("$GFXDeviceStatistics::");
  180. // Initialize the static helper textures.
  181. GBitmap temp( 2, 2, false, GFXFormatR8G8B8A8 );
  182. temp.fill( ColorI::ONE );
  183. GFXTexHandle::ONE.set( &temp, &GFXStaticTextureSRGBProfile, false, "GFXTexHandle::ONE" );
  184. temp.fill( ColorI::ZERO );
  185. GFXTexHandle::ZERO.set( &temp, &GFXStaticTextureSRGBProfile, false, "GFXTexHandle::ZERO" );
  186. temp.fill( ColorI( 128, 128, 255 ) );
  187. GFXTexHandle::ZUP.set( &temp, &GFXNormalMapProfile, false, "GFXTexHandle::ZUP" );
  188. }
  189. bool GFXDevice::destroy()
  190. {
  191. // Cleanup the static helper textures.
  192. GFXTexHandle::ONE.free();
  193. GFXTexHandle::ZERO.free();
  194. GFXTexHandle::ZUP.free();
  195. // Make this release its buffer.
  196. PrimBuild::shutdown();
  197. // Let people know we are shutting down
  198. getDeviceEventSignal().trigger(deDestroy);
  199. if(smGFXDevice)
  200. smGFXDevice->preDestroy();
  201. SAFE_DELETE(smGFXDevice);
  202. return true;
  203. }
  204. void GFXDevice::preDestroy()
  205. {
  206. // Delete draw util
  207. SAFE_DELETE( mDrawer );
  208. }
  209. GFXDevice::~GFXDevice()
  210. {
  211. smGFXDevice = NULL;
  212. // Clean up our current buffers.
  213. mCurrentPrimitiveBuffer = NULL;
  214. for ( U32 i=0; i < VERTEX_STREAM_COUNT; i++ )
  215. mCurrentVertexBuffer[i] = NULL;
  216. // Clear out our current texture references
  217. for (U32 i = 0; i < TEXTURE_STAGE_COUNT; i++)
  218. {
  219. mCurrentTexture[i] = NULL;
  220. mNewTexture[i] = NULL;
  221. mCurrentCubemap[i] = NULL;
  222. mNewCubemap[i] = NULL;
  223. mCurrentCubemapArray[i] = NULL;
  224. mNewCubemapArray[i] = NULL;
  225. mCurrentTextureArray[i] = NULL;
  226. mNewTextureArray[i] = NULL;
  227. }
  228. mCurrentRT = NULL;
  229. // Release all the unreferenced textures in the cache.
  230. mTextureManager->cleanupCache();
  231. // Check for resource leaks
  232. #ifdef TORQUE_DEBUG
  233. AssertFatal( GFXTextureObject::dumpActiveTOs() == 0, "There is a texture object leak, check the log for more details." );
  234. GFXPrimitiveBuffer::dumpActivePBs();
  235. #endif
  236. SAFE_DELETE( mTextureManager );
  237. SAFE_DELETE( mFrameTime );
  238. // Clear out our state block references
  239. mCurrentStateBlocks.clear();
  240. mNewStateBlock = NULL;
  241. mCurrentStateBlock = NULL;
  242. mCurrentShaderConstBuffer = NULL;
  243. /// End Block above BTR
  244. // -- Clear out resource list
  245. // Note: our derived class destructor will have already released resources.
  246. // Clearing this list saves us from having our resources (which are not deleted
  247. // just released) turn around and try to remove themselves from this list.
  248. while (mResourceListHead)
  249. {
  250. GFXResource * head = mResourceListHead;
  251. mResourceListHead = head->mNextResource;
  252. head->mPrevResource = NULL;
  253. head->mNextResource = NULL;
  254. head->mOwningDevice = NULL;
  255. }
  256. }
  257. GFXStateBlockRef GFXDevice::createStateBlock(const GFXStateBlockDesc& desc)
  258. {
  259. PROFILE_SCOPE( GFXDevice_CreateStateBlock );
  260. U32 hashValue = desc.getHashValue();
  261. if (mCurrentStateBlocks[hashValue])
  262. return mCurrentStateBlocks[hashValue];
  263. GFXStateBlockRef result = createStateBlockInternal(desc);
  264. result->registerResourceWithDevice(this);
  265. mCurrentStateBlocks[hashValue] = result;
  266. return result;
  267. }
  268. void GFXDevice::setStateBlock(GFXStateBlock* block)
  269. {
  270. AssertFatal(block, "NULL state block!");
  271. AssertFatal(block->getOwningDevice() == this, "This state doesn't apply to this device!");
  272. if (block != mCurrentStateBlock)
  273. {
  274. mStateDirty = true;
  275. mStateBlockDirty = true;
  276. mNewStateBlock = block;
  277. } else {
  278. mStateBlockDirty = false;
  279. mNewStateBlock = mCurrentStateBlock;
  280. }
  281. }
  282. void GFXDevice::setStateBlockByDesc( const GFXStateBlockDesc &desc )
  283. {
  284. PROFILE_SCOPE( GFXDevice_SetStateBlockByDesc );
  285. GFXStateBlock *block = createStateBlock( desc );
  286. setStateBlock( block );
  287. }
  288. void GFXDevice::setShaderConstBuffer(GFXShaderConstBuffer* buffer)
  289. {
  290. mCurrentShaderConstBuffer = buffer;
  291. }
  292. void GFXDevice::updateStates(bool forceSetAll /*=false*/)
  293. {
  294. PROFILE_SCOPE(GFXDevice_updateStates);
  295. if(forceSetAll)
  296. {
  297. bool rememberToEndScene = false;
  298. if(!canCurrentlyRender())
  299. {
  300. if (!beginScene())
  301. {
  302. AssertFatal(false, "GFXDevice::updateStates: Unable to beginScene!");
  303. }
  304. rememberToEndScene = true;
  305. }
  306. setMatrix( GFXMatrixProjection, mProjectionMatrix );
  307. setMatrix( GFXMatrixWorld, mWorldMatrix[mWorldStackSize] );
  308. setMatrix( GFXMatrixView, mViewMatrix );
  309. setVertexDecl( mCurrVertexDecl );
  310. for ( U32 i=0; i < VERTEX_STREAM_COUNT; i++ )
  311. {
  312. setVertexStream( i, mCurrentVertexBuffer[i] );
  313. setVertexStreamFrequency( i, mVertexBufferFrequency[i] );
  314. }
  315. if( mCurrentPrimitiveBuffer.isValid() ) // This could be NULL when the device is initalizing
  316. mCurrentPrimitiveBuffer->prepare();
  317. /// Stateblocks
  318. if ( mNewStateBlock )
  319. setStateBlockInternal(mNewStateBlock, true);
  320. mCurrentStateBlock = mNewStateBlock;
  321. for(U32 i = 0; i < getNumSamplers(); i++)
  322. {
  323. switch (mTexType[i])
  324. {
  325. case GFXTDT_Normal :
  326. {
  327. mCurrentTexture[i] = mNewTexture[i];
  328. setTextureInternal(i, mCurrentTexture[i]);
  329. }
  330. break;
  331. case GFXTDT_Cube :
  332. {
  333. mCurrentCubemap[i] = mNewCubemap[i];
  334. if (mCurrentCubemap[i])
  335. mCurrentCubemap[i]->setToTexUnit(i);
  336. else
  337. setTextureInternal(i, NULL);
  338. }
  339. break;
  340. case GFXTDT_CubeArray:
  341. {
  342. mCurrentCubemapArray[i] = mNewCubemapArray[i];
  343. if (mCurrentCubemapArray[i])
  344. mCurrentCubemapArray[i]->setToTexUnit(i);
  345. else
  346. setTextureInternal(i, NULL);
  347. }
  348. break;
  349. case GFXTDT_TextureArray:
  350. {
  351. mCurrentTextureArray[i] = mNewTextureArray[i];
  352. if (mCurrentTextureArray[i])
  353. mCurrentTextureArray[i]->setToTexUnit(i);
  354. else
  355. setTextureInternal(i, NULL);
  356. }
  357. break;
  358. default:
  359. AssertFatal(false, "Unknown texture type!");
  360. break;
  361. }
  362. }
  363. // Set our material
  364. setLightMaterialInternal(mCurrentLightMaterial);
  365. // Set our lights
  366. for(U32 i = 0; i < LIGHT_STAGE_COUNT; i++)
  367. {
  368. setLightInternal(i, mCurrentLight[i], mCurrentLightEnable[i]);
  369. }
  370. _updateRenderTargets();
  371. if(rememberToEndScene)
  372. endScene();
  373. return;
  374. }
  375. if (!mStateDirty)
  376. return;
  377. // Normal update logic begins here.
  378. mStateDirty = false;
  379. // Update Projection Matrix
  380. if( mProjectionMatrixDirty )
  381. {
  382. setMatrix( GFXMatrixProjection, mProjectionMatrix );
  383. mProjectionMatrixDirty = false;
  384. }
  385. // Update World Matrix
  386. if( mWorldMatrixDirty )
  387. {
  388. setMatrix( GFXMatrixWorld, mWorldMatrix[mWorldStackSize] );
  389. mWorldMatrixDirty = false;
  390. }
  391. // Update View Matrix
  392. if( mViewMatrixDirty )
  393. {
  394. setMatrix( GFXMatrixView, mViewMatrix );
  395. mViewMatrixDirty = false;
  396. }
  397. if( mTextureMatrixCheckDirty )
  398. {
  399. for( S32 i = 0; i < getNumSamplers(); i++ )
  400. {
  401. if( mTextureMatrixDirty[i] )
  402. {
  403. mTextureMatrixDirty[i] = false;
  404. setMatrix( (GFXMatrixType)(GFXMatrixTexture + i), mTextureMatrix[i] );
  405. }
  406. }
  407. mTextureMatrixCheckDirty = false;
  408. }
  409. // Update the vertex declaration.
  410. if ( mVertexDeclDirty )
  411. {
  412. setVertexDecl( mCurrVertexDecl );
  413. mVertexDeclDirty = false;
  414. }
  415. // Update the vertex buffers.
  416. for ( U32 i=0; i < VERTEX_STREAM_COUNT; i++ )
  417. {
  418. if ( mVertexBufferDirty[i] )
  419. {
  420. setVertexStream( i, mCurrentVertexBuffer[i] );
  421. mVertexBufferDirty[i] = false;
  422. }
  423. if ( mVertexBufferFrequencyDirty[i] )
  424. {
  425. setVertexStreamFrequency( i, mVertexBufferFrequency[i] );
  426. mVertexBufferFrequencyDirty[i] = false;
  427. }
  428. }
  429. // Update primitive buffer
  430. //
  431. // NOTE: It is very important to set the primitive buffer AFTER the vertex buffer
  432. // because in order to draw indexed primitives in DX8, the call to SetIndicies
  433. // needs to include the base vertex offset, and the DX8 GFXDevice relies on
  434. // having mCurrentVB properly assigned before the call to setIndices -patw
  435. if( mPrimitiveBufferDirty )
  436. {
  437. if( mCurrentPrimitiveBuffer.isValid() ) // This could be NULL when the device is initalizing
  438. mCurrentPrimitiveBuffer->prepare();
  439. mPrimitiveBufferDirty = false;
  440. }
  441. // NOTE: With state blocks, it's now important to update state before setting textures
  442. // some devices (e.g. OpenGL) set states on the texture and we need that information before
  443. // the texture is activated.
  444. if (mStateBlockDirty)
  445. {
  446. setStateBlockInternal(mNewStateBlock, false);
  447. mCurrentStateBlock = mNewStateBlock;
  448. mStateBlockDirty = false;
  449. }
  450. _updateRenderTargets();
  451. if( mTexturesDirty )
  452. {
  453. mTexturesDirty = false;
  454. for(U32 i = 0; i < getNumSamplers(); i++)
  455. {
  456. if(!mTextureDirty[i])
  457. continue;
  458. mTextureDirty[i] = false;
  459. switch (mTexType[i])
  460. {
  461. case GFXTDT_Normal :
  462. {
  463. mCurrentTexture[i] = mNewTexture[i];
  464. setTextureInternal(i, mCurrentTexture[i]);
  465. }
  466. break;
  467. case GFXTDT_Cube :
  468. {
  469. mCurrentCubemap[i] = mNewCubemap[i];
  470. if (mCurrentCubemap[i])
  471. mCurrentCubemap[i]->setToTexUnit(i);
  472. else
  473. setTextureInternal(i, NULL);
  474. }
  475. break;
  476. case GFXTDT_CubeArray:
  477. {
  478. mCurrentCubemapArray[i] = mNewCubemapArray[i];
  479. if (mCurrentCubemapArray[i])
  480. mCurrentCubemapArray[i]->setToTexUnit(i);
  481. else
  482. setTextureInternal(i, NULL);
  483. }
  484. break;
  485. case GFXTDT_TextureArray:
  486. {
  487. mCurrentTextureArray[i] = mNewTextureArray[i];
  488. if (mCurrentTextureArray[i])
  489. mCurrentTextureArray[i]->setToTexUnit(i);
  490. else
  491. setTextureInternal(i, NULL);
  492. }
  493. break;
  494. default:
  495. AssertFatal(false, "Unknown texture type!");
  496. break;
  497. }
  498. }
  499. }
  500. // Set light material
  501. if(mLightMaterialDirty)
  502. {
  503. setLightMaterialInternal(mCurrentLightMaterial);
  504. mLightMaterialDirty = false;
  505. }
  506. // Set our lights
  507. if(mLightsDirty)
  508. {
  509. mLightsDirty = false;
  510. for(U32 i = 0; i < LIGHT_STAGE_COUNT; i++)
  511. {
  512. if(!mLightDirty[i])
  513. continue;
  514. mLightDirty[i] = false;
  515. setLightInternal(i, mCurrentLight[i], mCurrentLightEnable[i]);
  516. }
  517. }
  518. _updateRenderTargets();
  519. #ifdef TORQUE_DEBUG_RENDER
  520. doParanoidStateCheck();
  521. #endif
  522. }
  523. void GFXDevice::clearTextureStateImmediate(U32 stage)
  524. {
  525. mCurrentTexture[stage] = NULL;
  526. mCurrentCubemap[stage] = NULL;
  527. setTextureInternal(stage, NULL);
  528. }
  529. void GFXDevice::setPrimitiveBuffer( GFXPrimitiveBuffer *buffer )
  530. {
  531. if( buffer == mCurrentPrimitiveBuffer )
  532. return;
  533. mCurrentPrimitiveBuffer = buffer;
  534. mPrimitiveBufferDirty = true;
  535. mStateDirty = true;
  536. }
  537. void GFXDevice::drawPrimitive( U32 primitiveIndex )
  538. {
  539. AssertFatal( mCurrentPrimitiveBuffer.isValid(), "Trying to call drawPrimitive with no current primitive buffer, call setPrimitiveBuffer()" );
  540. AssertFatal( primitiveIndex < mCurrentPrimitiveBuffer->mPrimitiveCount, "Out of range primitive index.");
  541. drawPrimitive( mCurrentPrimitiveBuffer->mPrimitiveArray[primitiveIndex] );
  542. }
  543. void GFXDevice::drawPrimitive( const GFXPrimitive &prim )
  544. {
  545. // Do NOT add index buffer offset to this call, it will be added by drawIndexedPrimitive
  546. drawIndexedPrimitive( prim.type,
  547. prim.startVertex,
  548. prim.minIndex,
  549. prim.numVertices,
  550. prim.startIndex,
  551. prim.numPrimitives );
  552. }
  553. void GFXDevice::drawPrimitives()
  554. {
  555. AssertFatal( mCurrentPrimitiveBuffer.isValid(), "Trying to call drawPrimitive with no current primitive buffer, call setPrimitiveBuffer()" );
  556. GFXPrimitive *info = NULL;
  557. for( U32 i = 0; i < mCurrentPrimitiveBuffer->mPrimitiveCount; i++ ) {
  558. info = &mCurrentPrimitiveBuffer->mPrimitiveArray[i];
  559. // Do NOT add index buffer offset to this call, it will be added by drawIndexedPrimitive
  560. drawIndexedPrimitive( info->type,
  561. info->startVertex,
  562. info->minIndex,
  563. info->numVertices,
  564. info->startIndex,
  565. info->numPrimitives );
  566. }
  567. }
  568. DefineEngineFunction( getDisplayDeviceList, String, (),,
  569. "Returns a tab-seperated string of the detected devices across all adapters.\n"
  570. "@ingroup GFX\n" )
  571. {
  572. Vector<GFXAdapter*> adapters;
  573. GFXInit::getAdapters(&adapters);
  574. StringBuilder str;
  575. for (S32 i=0; i<adapters.size(); i++)
  576. {
  577. if (i)
  578. str.append( '\t' );
  579. str.append(adapters[i]->mName);
  580. }
  581. return str.end();
  582. }
  583. void GFXDevice::setFrustum( F32 left,
  584. F32 right,
  585. F32 bottom,
  586. F32 top,
  587. F32 nearPlane,
  588. F32 farPlane,
  589. bool bRotate )
  590. {
  591. // store values
  592. mFrustum.set(false, left, right, top, bottom, nearPlane, farPlane);
  593. // compute matrix
  594. MatrixF projection;
  595. mFrustum.getProjectionMatrix(&projection, bRotate);
  596. setProjectionMatrix( projection );
  597. }
  598. void GFXDevice::setFrustum( const Frustum& frust, bool bRotate )
  599. {
  600. // store values
  601. mFrustum = frust;
  602. // compute matrix
  603. MatrixF projection;
  604. mFrustum.getProjectionMatrix(&projection, bRotate);
  605. setProjectionMatrix( projection );
  606. }
  607. void GFXDevice::getFrustum( F32 *left, F32 *right, F32 *bottom, F32 *top, F32 *nearPlane, F32 *farPlane, bool *isOrtho ) const
  608. {
  609. if ( left ) *left = mFrustum.getNearLeft();
  610. if ( right ) *right = mFrustum.getNearRight();
  611. if ( bottom ) *bottom = mFrustum.getNearBottom();
  612. if ( top ) *top = mFrustum.getNearTop();
  613. if ( nearPlane ) *nearPlane = mFrustum.getNearDist();
  614. if ( farPlane ) *farPlane = mFrustum.getFarDist();
  615. if ( isOrtho ) *isOrtho = mFrustum.isOrtho();
  616. }
  617. void GFXDevice::setOrtho( F32 left,
  618. F32 right,
  619. F32 bottom,
  620. F32 top,
  621. F32 nearPlane,
  622. F32 farPlane,
  623. bool doRotate )
  624. {
  625. // store values
  626. mFrustum.set(true, left, right, top, bottom, nearPlane, farPlane);
  627. // compute matrix
  628. MatrixF projection;
  629. mFrustum.getProjectionMatrix(&projection, doRotate);
  630. setProjectionMatrix( projection );
  631. }
  632. Point2F GFXDevice::getWorldToScreenScale() const
  633. {
  634. Point2F scale;
  635. const RectI &viewport = getViewport();
  636. if ( mFrustum.isOrtho() )
  637. scale.set( viewport.extent.x / mFrustum.getWidth(),
  638. viewport.extent.y / mFrustum.getHeight() );
  639. else
  640. scale.set( ( mFrustum.getNearDist() * viewport.extent.x ) / mFrustum.getWidth(),
  641. ( mFrustum.getNearDist() * viewport.extent.y ) / mFrustum.getHeight() );
  642. return scale;
  643. }
  644. //-----------------------------------------------------------------------------
  645. // Set Light
  646. //-----------------------------------------------------------------------------
  647. void GFXDevice::setLight(U32 stage, GFXLightInfo* light)
  648. {
  649. AssertFatal(stage < LIGHT_STAGE_COUNT, "GFXDevice::setLight - out of range stage!");
  650. if(!mLightDirty[stage])
  651. {
  652. mStateDirty = true;
  653. mLightsDirty = true;
  654. mLightDirty[stage] = true;
  655. }
  656. mCurrentLightEnable[stage] = (light != NULL);
  657. if(mCurrentLightEnable[stage])
  658. mCurrentLight[stage] = *light;
  659. }
  660. //-----------------------------------------------------------------------------
  661. // Set Light Material
  662. //-----------------------------------------------------------------------------
  663. void GFXDevice::setLightMaterial(const GFXLightMaterial& mat)
  664. {
  665. mCurrentLightMaterial = mat;
  666. mLightMaterialDirty = true;
  667. mStateDirty = true;
  668. }
  669. void GFXDevice::setGlobalAmbientColor(const LinearColorF& color)
  670. {
  671. if(mGlobalAmbientColor != color)
  672. {
  673. mGlobalAmbientColor = color;
  674. mGlobalAmbientColorDirty = true;
  675. }
  676. }
  677. //-----------------------------------------------------------------------------
  678. // Set texture
  679. //-----------------------------------------------------------------------------
  680. void GFXDevice::setTexture( U32 stage, GFXTextureObject *texture )
  681. {
  682. AssertFatal(stage < getNumSamplers(), "GFXDevice::setTexture - out of range stage!");
  683. if ( mTexType[stage] == GFXTDT_Normal &&
  684. ( ( mTextureDirty[stage] && mNewTexture[stage].getPointer() == texture ) ||
  685. ( !mTextureDirty[stage] && mCurrentTexture[stage].getPointer() == texture ) ) )
  686. return;
  687. mStateDirty = true;
  688. mTexturesDirty = true;
  689. mTextureDirty[stage] = true;
  690. mNewTexture[stage] = texture;
  691. mTexType[stage] = GFXTDT_Normal;
  692. // Clear out the cubemaps
  693. mNewCubemap[stage] = NULL;
  694. mCurrentCubemap[stage] = NULL;
  695. mNewCubemapArray[stage] = NULL;
  696. mCurrentCubemapArray[stage] = NULL;
  697. mNewTextureArray[stage] = NULL;
  698. mCurrentTextureArray[stage] = NULL;
  699. }
  700. //-----------------------------------------------------------------------------
  701. // Set cube texture
  702. //-----------------------------------------------------------------------------
  703. void GFXDevice::setCubeTexture( U32 stage, GFXCubemap *cubemap )
  704. {
  705. AssertFatal(stage < getNumSamplers(), "GFXDevice::setTexture - out of range stage!");
  706. if ( mTexType[stage] == GFXTDT_Cube &&
  707. ( ( mTextureDirty[stage] && mNewCubemap[stage].getPointer() == cubemap) ||
  708. ( !mTextureDirty[stage] && mCurrentCubemap[stage].getPointer() == cubemap) ) )
  709. return;
  710. mStateDirty = true;
  711. mTexturesDirty = true;
  712. mTextureDirty[stage] = true;
  713. mNewCubemap[stage] = cubemap;
  714. mTexType[stage] = GFXTDT_Cube;
  715. // Clear out textures
  716. mNewTexture[stage] = NULL;
  717. mCurrentTexture[stage] = NULL;
  718. mNewCubemapArray[stage] = NULL;
  719. mCurrentCubemapArray[stage] = NULL;
  720. mNewTextureArray[stage] = NULL;
  721. mCurrentTextureArray[stage] = NULL;
  722. }
  723. //-----------------------------------------------------------------------------
  724. // Set cube texture array
  725. //-----------------------------------------------------------------------------
  726. void GFXDevice::setCubeArrayTexture(U32 stage, GFXCubemapArray *cubemapArray)
  727. {
  728. AssertFatal(stage < getNumSamplers(), avar("GFXDevice::setTexture - out of range stage! %i>%i", stage, getNumSamplers()));
  729. if (mTexType[stage] == GFXTDT_CubeArray &&
  730. ((mTextureDirty[stage] && mNewCubemapArray[stage].getPointer() == cubemapArray) ||
  731. (!mTextureDirty[stage] && mCurrentCubemapArray[stage].getPointer() == cubemapArray)))
  732. return;
  733. mStateDirty = true;
  734. mTexturesDirty = true;
  735. mTextureDirty[stage] = true;
  736. mNewCubemapArray[stage] = cubemapArray;
  737. mTexType[stage] = GFXTDT_CubeArray;
  738. // Clear out textures
  739. mNewTexture[stage] = NULL;
  740. mCurrentTexture[stage] = NULL;
  741. mNewCubemap[stage] = NULL;
  742. mCurrentCubemap[stage] = NULL;
  743. mNewTextureArray[stage] = NULL;
  744. mCurrentTextureArray[stage] = NULL;
  745. }
  746. //-----------------------------------------------------------------------------
  747. // Set texture array
  748. //-----------------------------------------------------------------------------
  749. void GFXDevice::setTextureArray(U32 stage, GFXTextureArray *textureArray)
  750. {
  751. AssertFatal(stage < getNumSamplers(), avar("GFXDevice::setTextureArray - out of range stage! %i>%i", stage, getNumSamplers()));
  752. if (mTexType[stage] == GFXTDT_TextureArray &&
  753. ((mTextureDirty[stage] && mNewTextureArray[stage].getPointer() == textureArray) ||
  754. (!mTextureDirty[stage] && mCurrentTextureArray[stage].getPointer() == textureArray)))
  755. return;
  756. mStateDirty = true;
  757. mTexturesDirty = true;
  758. mTextureDirty[stage] = true;
  759. mNewTextureArray[stage] = textureArray;
  760. mTexType[stage] = GFXTDT_TextureArray;
  761. // Clear out textures
  762. mNewTexture[stage] = NULL;
  763. mCurrentTexture[stage] = NULL;
  764. mNewCubemap[stage] = NULL;
  765. mCurrentCubemap[stage] = NULL;
  766. mNewCubemapArray[stage] = NULL;
  767. mCurrentCubemapArray[stage] = NULL;
  768. }
  769. //------------------------------------------------------------------------------
  770. inline bool GFXDevice::beginScene()
  771. {
  772. AssertFatal( mCanCurrentlyRender == false, "GFXDevice::beginScene() - The scene has already begun!" );
  773. mDeviceStatistics.clear();
  774. // Send the start of frame signal.
  775. getDeviceEventSignal().trigger( GFXDevice::deStartOfFrame );
  776. mFrameTime->reset();
  777. return beginSceneInternal();
  778. }
  779. inline void GFXDevice::endScene()
  780. {
  781. AssertFatal( mCanCurrentlyRender == true, "GFXDevice::endScene() - The scene has already ended!" );
  782. // End frame signal
  783. getDeviceEventSignal().trigger( GFXDevice::deEndOfFrame );
  784. endSceneInternal();
  785. mDeviceStatistics.exportToConsole();
  786. }
  787. inline void GFXDevice::beginField()
  788. {
  789. AssertFatal( mCanCurrentlyRender == true, "GFXDevice::beginField() - The scene has not yet begun!" );
  790. // Send the start of field signal.
  791. getDeviceEventSignal().trigger( GFXDevice::deStartOfField );
  792. }
  793. inline void GFXDevice::endField()
  794. {
  795. AssertFatal( mCanCurrentlyRender == true, "GFXDevice::endField() - The scene has not yet begun!" );
  796. // Send the end of field signal.
  797. getDeviceEventSignal().trigger( GFXDevice::deEndOfField );
  798. }
  799. void GFXDevice::setViewport( const RectI &inRect )
  800. {
  801. // Clip the rect against the renderable size.
  802. Point2I size = mCurrentRT->getSize();
  803. RectI maxRect(Point2I(0,0), size);
  804. RectI rect = inRect;
  805. rect.intersect(maxRect);
  806. if ( mViewport != rect )
  807. {
  808. mViewport = rect;
  809. mViewportDirty = true;
  810. }
  811. }
  812. void GFXDevice::pushActiveRenderTarget()
  813. {
  814. // Push the current target on to the stack.
  815. mRTStack.push_back( mCurrentRT );
  816. }
  817. void GFXDevice::popActiveRenderTarget()
  818. {
  819. AssertFatal( mRTStack.size() > 0, "GFXDevice::popActiveRenderTarget() - stack is empty!" );
  820. // Restore the last item on the stack and pop.
  821. setActiveRenderTarget( mRTStack.last() );
  822. mRTStack.pop_back();
  823. }
  824. void GFXDevice::setActiveRenderTarget( GFXTarget *target, bool updateViewport )
  825. {
  826. AssertFatal( target,
  827. "GFXDevice::setActiveRenderTarget - must specify a render target!" );
  828. if ( target == mCurrentRT )
  829. return;
  830. // If we're not dirty then store the
  831. // current RT for deactivation later.
  832. if ( !mRTDirty )
  833. {
  834. // Deactivate the target queued for deactivation
  835. if(mRTDeactivate)
  836. mRTDeactivate->deactivate();
  837. mRTDeactivate = mCurrentRT;
  838. }
  839. mRTDirty = true;
  840. mCurrentRT = target;
  841. // When a target changes we also change the viewport
  842. // to match it. This causes problems when the viewport
  843. // has been modified for clipping to a GUI bounds.
  844. //
  845. // We should consider removing this and making it the
  846. // responsibility of the caller to set a proper viewport
  847. // when the target is changed.
  848. if ( updateViewport )
  849. {
  850. setViewport( RectI( Point2I::Zero, mCurrentRT->getSize() ) );
  851. }
  852. }
  853. /// Helper class for GFXDevice::describeResources.
  854. class DescriptionOutputter
  855. {
  856. /// Are we writing to a file?
  857. bool mWriteToFile;
  858. /// File if we are writing to a file
  859. FileStream mFile;
  860. public:
  861. DescriptionOutputter(const char* file)
  862. {
  863. mWriteToFile = false;
  864. // If we've been given what could be a valid file path, open it.
  865. if(file && file[0] != '\0')
  866. {
  867. mWriteToFile = mFile.open(file, Torque::FS::File::Write);
  868. // Note that it is safe to retry. If this is hit, we'll just write to the console instead of to the file.
  869. AssertFatal(mWriteToFile, avar("DescriptionOutputter::DescriptionOutputter - could not open file %s", file));
  870. }
  871. }
  872. ~DescriptionOutputter()
  873. {
  874. // Close the file
  875. if(mWriteToFile)
  876. mFile.close();
  877. }
  878. /// Writes line to the file or to the console, depending on what we want.
  879. void write(const char* line)
  880. {
  881. if(mWriteToFile)
  882. mFile.writeLine((const U8*)line);
  883. else
  884. Con::printf(line);
  885. }
  886. };
  887. #ifndef TORQUE_SHIPPING
  888. void GFXDevice::dumpStates( const char *fileName ) const
  889. {
  890. DescriptionOutputter output(fileName);
  891. output.write("Current state");
  892. if (!mCurrentStateBlock.isNull())
  893. output.write(mCurrentStateBlock->getDesc().describeSelf().c_str());
  894. else
  895. output.write("No state!");
  896. output.write("\nAll states:\n");
  897. GFXResource* walk = mResourceListHead;
  898. while(walk)
  899. {
  900. const GFXStateBlock* sb = dynamic_cast<const GFXStateBlock*>(walk);
  901. if (sb)
  902. {
  903. output.write(sb->getDesc().describeSelf().c_str());
  904. }
  905. walk = walk->getNextResource();
  906. }
  907. }
  908. #endif
  909. void GFXDevice::listResources(bool unflaggedOnly)
  910. {
  911. U32 numTextures = 0, numShaders = 0, numRenderToTextureTargs = 0, numWindowTargs = 0;
  912. U32 numCubemaps = 0, numVertexBuffers = 0, numPrimitiveBuffers = 0, numFences = 0;
  913. U32 numStateBlocks = 0;
  914. GFXResource* walk = mResourceListHead;
  915. while(walk)
  916. {
  917. if(unflaggedOnly && walk->isFlagged())
  918. {
  919. walk = walk->getNextResource();
  920. continue;
  921. }
  922. if(dynamic_cast<GFXTextureObject*>(walk))
  923. numTextures++;
  924. else if(dynamic_cast<GFXShader*>(walk))
  925. numShaders++;
  926. else if(dynamic_cast<GFXTextureTarget*>(walk))
  927. numRenderToTextureTargs++;
  928. else if(dynamic_cast<GFXWindowTarget*>(walk))
  929. numWindowTargs++;
  930. else if(dynamic_cast<GFXCubemap*>(walk))
  931. numCubemaps++;
  932. else if(dynamic_cast<GFXVertexBuffer*>(walk))
  933. numVertexBuffers++;
  934. else if(dynamic_cast<GFXPrimitiveBuffer*>(walk))
  935. numPrimitiveBuffers++;
  936. else if(dynamic_cast<GFXFence*>(walk))
  937. numFences++;
  938. else if (dynamic_cast<GFXStateBlock*>(walk))
  939. numStateBlocks++;
  940. else
  941. Con::warnf("Unknown resource: %x", walk);
  942. walk = walk->getNextResource();
  943. }
  944. const char* flag = unflaggedOnly ? "unflagged" : "allocated";
  945. Con::printf("GFX currently has:");
  946. Con::printf(" %i %s textures", numTextures, flag);
  947. Con::printf(" %i %s shaders", numShaders, flag);
  948. Con::printf(" %i %s texture targets", numRenderToTextureTargs, flag);
  949. Con::printf(" %i %s window targets", numWindowTargs, flag);
  950. Con::printf(" %i %s cubemaps", numCubemaps, flag);
  951. Con::printf(" %i %s vertex buffers", numVertexBuffers, flag);
  952. Con::printf(" %i %s primitive buffers", numPrimitiveBuffers, flag);
  953. Con::printf(" %i %s fences", numFences, flag);
  954. Con::printf(" %i %s state blocks", numStateBlocks, flag);
  955. }
  956. void GFXDevice::fillResourceVectors(const char* resNames, bool unflaggedOnly, Vector<GFXResource*> &textureObjects,
  957. Vector<GFXResource*> &textureTargets, Vector<GFXResource*> &windowTargets, Vector<GFXResource*> &vertexBuffers,
  958. Vector<GFXResource*> &primitiveBuffers, Vector<GFXResource*> &fences, Vector<GFXResource*> &cubemaps,
  959. Vector<GFXResource*> &shaders, Vector<GFXResource*> &stateblocks)
  960. {
  961. bool describeTexture = true, describeTextureTarget = true, describeWindowTarget = true, describeVertexBuffer = true,
  962. describePrimitiveBuffer = true, describeFence = true, describeCubemap = true, describeShader = true,
  963. describeStateBlock = true;
  964. // If we didn't specify a string of names, we'll print all of them
  965. if(resNames && resNames[0] != '\0')
  966. {
  967. // If we did specify a string of names, determine which names
  968. describeTexture = (dStrstr(resNames, "GFXTextureObject") != NULL);
  969. describeTextureTarget = (dStrstr(resNames, "GFXTextureTarget") != NULL);
  970. describeWindowTarget = (dStrstr(resNames, "GFXWindowTarget") != NULL);
  971. describeVertexBuffer = (dStrstr(resNames, "GFXVertexBuffer") != NULL);
  972. describePrimitiveBuffer = (dStrstr(resNames, "GFXPrimitiveBuffer") != NULL);
  973. describeFence = (dStrstr(resNames, "GFXFence") != NULL);
  974. describeCubemap = (dStrstr(resNames, "GFXCubemap") != NULL);
  975. describeShader = (dStrstr(resNames, "GFXShader") != NULL);
  976. describeStateBlock = (dStrstr(resNames, "GFXStateBlock") != NULL);
  977. }
  978. // Start going through the list
  979. GFXResource* walk = mResourceListHead;
  980. while(walk)
  981. {
  982. // If we only want unflagged resources, skip all flagged resources
  983. if(unflaggedOnly && walk->isFlagged())
  984. {
  985. walk = walk->getNextResource();
  986. continue;
  987. }
  988. // All of the following checks go through the same logic.
  989. // if(describingThisResource)
  990. // {
  991. // ResourceType* type = dynamic_cast<ResourceType*>(walk)
  992. // if(type)
  993. // {
  994. // typeVector.push_back(type);
  995. // walk = walk->getNextResource();
  996. // continue;
  997. // }
  998. // }
  999. if(describeTexture)
  1000. {
  1001. GFXTextureObject* tex = dynamic_cast<GFXTextureObject*>(walk);
  1002. {
  1003. if(tex)
  1004. {
  1005. textureObjects.push_back(tex);
  1006. walk = walk->getNextResource();
  1007. continue;
  1008. }
  1009. }
  1010. }
  1011. if(describeShader)
  1012. {
  1013. GFXShader* shd = dynamic_cast<GFXShader*>(walk);
  1014. if(shd)
  1015. {
  1016. shaders.push_back(shd);
  1017. walk = walk->getNextResource();
  1018. continue;
  1019. }
  1020. }
  1021. if(describeVertexBuffer)
  1022. {
  1023. GFXVertexBuffer* buf = dynamic_cast<GFXVertexBuffer*>(walk);
  1024. if(buf)
  1025. {
  1026. vertexBuffers.push_back(buf);
  1027. walk = walk->getNextResource();
  1028. continue;
  1029. }
  1030. }
  1031. if(describePrimitiveBuffer)
  1032. {
  1033. GFXPrimitiveBuffer* buf = dynamic_cast<GFXPrimitiveBuffer*>(walk);
  1034. if(buf)
  1035. {
  1036. primitiveBuffers.push_back(buf);
  1037. walk = walk->getNextResource();
  1038. continue;
  1039. }
  1040. }
  1041. if(describeTextureTarget)
  1042. {
  1043. GFXTextureTarget* targ = dynamic_cast<GFXTextureTarget*>(walk);
  1044. if(targ)
  1045. {
  1046. textureTargets.push_back(targ);
  1047. walk = walk->getNextResource();
  1048. continue;
  1049. }
  1050. }
  1051. if(describeWindowTarget)
  1052. {
  1053. GFXWindowTarget* targ = dynamic_cast<GFXWindowTarget*>(walk);
  1054. if(targ)
  1055. {
  1056. windowTargets.push_back(targ);
  1057. walk = walk->getNextResource();
  1058. continue;
  1059. }
  1060. }
  1061. if(describeCubemap)
  1062. {
  1063. GFXCubemap* cube = dynamic_cast<GFXCubemap*>(walk);
  1064. if(cube)
  1065. {
  1066. cubemaps.push_back(cube);
  1067. walk = walk->getNextResource();
  1068. continue;
  1069. }
  1070. }
  1071. if(describeFence)
  1072. {
  1073. GFXFence* fence = dynamic_cast<GFXFence*>(walk);
  1074. if(fence)
  1075. {
  1076. fences.push_back(fence);
  1077. walk = walk->getNextResource();
  1078. continue;
  1079. }
  1080. }
  1081. if (describeStateBlock)
  1082. {
  1083. GFXStateBlock* sb = dynamic_cast<GFXStateBlock*>(walk);
  1084. if (sb)
  1085. {
  1086. stateblocks.push_back(sb);
  1087. walk = walk->getNextResource();
  1088. continue;
  1089. }
  1090. }
  1091. // Wasn't something we were looking for
  1092. walk = walk->getNextResource();
  1093. }
  1094. }
  1095. void GFXDevice::describeResources(const char* resNames, const char* filePath, bool unflaggedOnly)
  1096. {
  1097. const U32 numResourceTypes = 9;
  1098. Vector<GFXResource*> resVectors[numResourceTypes];
  1099. const char* reslabels[numResourceTypes] = { "texture", "texture target", "window target", "vertex buffers", "primitive buffers", "fences", "cubemaps", "shaders", "stateblocks" };
  1100. // Fill the vectors with the right resources
  1101. fillResourceVectors(resNames, unflaggedOnly, resVectors[0], resVectors[1], resVectors[2], resVectors[3],
  1102. resVectors[4], resVectors[5], resVectors[6], resVectors[7], resVectors[8]);
  1103. // Helper object
  1104. DescriptionOutputter output(filePath);
  1105. // Print the info to the file
  1106. // Note that we check if we have any objects of that type.
  1107. for (U32 i = 0; i < numResourceTypes; i++)
  1108. {
  1109. if (resVectors[i].size())
  1110. {
  1111. // Header
  1112. String header = String::ToString("--------Dumping GFX %s descriptions...----------", reslabels[i]);
  1113. output.write(header);
  1114. // Data
  1115. for (U32 j = 0; j < resVectors[i].size(); j++)
  1116. {
  1117. GFXResource* resource = resVectors[i][j];
  1118. String dataline = String::ToString("Addr: %x %s", resource, resource->describeSelf().c_str());
  1119. output.write(dataline.c_str());
  1120. }
  1121. // Footer
  1122. output.write("--------------------Done---------------------");
  1123. output.write("");
  1124. }
  1125. }
  1126. }
  1127. void GFXDevice::flagCurrentResources()
  1128. {
  1129. GFXResource* walk = mResourceListHead;
  1130. while(walk)
  1131. {
  1132. walk->setFlag();
  1133. walk = walk->getNextResource();
  1134. }
  1135. }
  1136. void GFXDevice::clearResourceFlags()
  1137. {
  1138. GFXResource* walk = mResourceListHead;
  1139. while(walk)
  1140. {
  1141. walk->clearFlag();
  1142. walk = walk->getNextResource();
  1143. }
  1144. }
  1145. DefineEngineFunction( listGFXResources, void, ( bool unflaggedOnly ), ( false ),
  1146. "Returns a list of the unflagged GFX resources. See flagCurrentGFXResources for usage details.\n"
  1147. "@ingroup GFX\n"
  1148. "@see flagCurrentGFXResources, clearGFXResourceFlags, describeGFXResources" )
  1149. {
  1150. GFX->listResources(unflaggedOnly);
  1151. }
  1152. DefineEngineFunction( flagCurrentGFXResources, void, (),,
  1153. "@brief Flags all currently allocated GFX resources.\n"
  1154. "Used for resource allocation and leak tracking by flagging "
  1155. "current resources then dumping a list of unflagged resources "
  1156. "at some later point in execution.\n"
  1157. "@ingroup GFX\n"
  1158. "@see listGFXResources, clearGFXResourceFlags, describeGFXResources" )
  1159. {
  1160. GFX->flagCurrentResources();
  1161. }
  1162. DefineEngineFunction( clearGFXResourceFlags, void, (),,
  1163. "Clears the flagged state on all allocated GFX resources. "
  1164. "See flagCurrentGFXResources for usage details.\n"
  1165. "@ingroup GFX\n"
  1166. "@see flagCurrentGFXResources, listGFXResources, describeGFXResources" )
  1167. {
  1168. GFX->clearResourceFlags();
  1169. }
  1170. DefineEngineFunction( describeGFXResources, void, ( const char *resourceTypes, const char *filePath, bool unflaggedOnly ), ( false ),
  1171. "@brief Dumps a description of GFX resources to a file or the console.\n"
  1172. "@param resourceTypes A space seperated list of resource types or an empty string for all resources.\n"
  1173. "@param filePath A file to dump the list to or an empty string to write to the console.\n"
  1174. "@param unflaggedOnly If true only unflagged resources are dumped. See flagCurrentGFXResources.\n"
  1175. "@note The resource types can be one or more of the following:\n\n"
  1176. " - texture\n"
  1177. " - texture target\n"
  1178. " - window target\n"
  1179. " - vertex buffers\n"
  1180. " - primitive buffers\n"
  1181. " - fences\n"
  1182. " - cubemaps\n"
  1183. " - shaders\n"
  1184. " - stateblocks\n\n"
  1185. "@ingroup GFX\n" )
  1186. {
  1187. GFX->describeResources( resourceTypes, filePath, unflaggedOnly );
  1188. }
  1189. DefineEngineFunction( describeGFXStateBlocks, void, ( const char *filePath ),,
  1190. "Dumps a description of all state blocks.\n"
  1191. "@param filePath A file to dump the state blocks to or an empty string to write to the console.\n"
  1192. "@ingroup GFX\n" )
  1193. {
  1194. GFX->dumpStates( filePath );
  1195. }
  1196. DefineEngineFunction( getPixelShaderVersion, F32, (),,
  1197. "Returns the pixel shader version for the active device.\n"
  1198. "@ingroup GFX\n" )
  1199. {
  1200. return GFX->getPixelShaderVersion();
  1201. }
  1202. DefineEngineFunction( setPixelShaderVersion, void, ( F32 version ),,
  1203. "@brief Sets the pixel shader version for the active device.\n"
  1204. "This can be used to force a lower pixel shader version than is supported by "
  1205. "the device for testing or performance optimization.\n"
  1206. "@param version The floating point shader version number.\n"
  1207. "@note This will only affect shaders/materials created after the call "
  1208. "and should be used before the game begins.\n"
  1209. "@see $pref::Video::forcedPixVersion\n"
  1210. "@ingroup GFX\n" )
  1211. {
  1212. GFX->setPixelShaderVersion( version );
  1213. }
  1214. DefineEngineFunction( getDisplayDeviceInformation, const char*, (),,
  1215. "Get the string describing the active GFX device.\n"
  1216. "@ingroup GFX\n" )
  1217. {
  1218. if (!GFXDevice::devicePresent())
  1219. return "(no device)";
  1220. const GFXAdapter& adapter = GFX->getAdapter();
  1221. return adapter.getName();
  1222. }
  1223. DefineEngineFunction(getDisplayDeviceType, GFXAdapterType, (), ,
  1224. "Get the string describing the active GFX device type.\n"
  1225. "@ingroup GFX\n")
  1226. {
  1227. if (!GFXDevice::devicePresent())
  1228. return NullDevice;
  1229. const GFXAdapter& adapter = GFX->getAdapter();
  1230. return adapter.mType;
  1231. }
  1232. DefineEngineFunction( getBestHDRFormat, GFXFormat, (),,
  1233. "Returns the best texture format for storage of HDR data for the active device.\n"
  1234. "@ingroup GFX\n" )
  1235. {
  1236. // TODO: Maybe expose GFX::selectSupportedFormat() so that this
  1237. // specialized method can be moved to script.
  1238. // Figure out the best HDR format. This is the smallest
  1239. // format which supports blending and filtering.
  1240. Vector<GFXFormat> formats;
  1241. formats.push_back(GFXFormatR16G16B16A16F);
  1242. formats.push_back( GFXFormatR10G10B10A2 );
  1243. GFXFormat format = GFX->selectSupportedFormat( &GFXRenderTargetProfile,
  1244. formats,
  1245. true,
  1246. true,
  1247. true );
  1248. return format;
  1249. }
  1250. DefineEngineFunction(ResetGFX, void, (), , "forces the gbuffer to be reinitialized in cases of improper/lack of buffer clears.")
  1251. {
  1252. GFX->beginReset();
  1253. }