gfxGLDevice.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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/gl/gfxGLDevice.h"
  24. #include "gfxGLTextureArray.h"
  25. #include "platform/platformGL.h"
  26. #include "gfx/gfxCubemap.h"
  27. #include "gfx/gl/screenshotGL.h"
  28. #include "gfx/gfxDrawUtil.h"
  29. #include "gfx/gl/gfxGLEnumTranslate.h"
  30. #include "gfx/gl/gfxGLVertexBuffer.h"
  31. #include "gfx/gl/gfxGLPrimitiveBuffer.h"
  32. #include "gfx/gl/gfxGLTextureTarget.h"
  33. #include "gfx/gl/gfxGLTextureManager.h"
  34. #include "gfx/gl/gfxGLTextureObject.h"
  35. #include "gfx/gl/gfxGLCubemap.h"
  36. #include "gfx/gl/gfxGLCardProfiler.h"
  37. #include "gfx/gl/gfxGLWindowTarget.h"
  38. #include "platform/platformDlibrary.h"
  39. #include "gfx/gl/gfxGLShader.h"
  40. #include "gfx/primBuilder.h"
  41. #include "console/console.h"
  42. #include "gfx/gl/gfxGLOcclusionQuery.h"
  43. #include "materials/shaderData.h"
  44. #include "gfx/gl/gfxGLStateCache.h"
  45. #include "gfx/gl/gfxGLVertexAttribLocation.h"
  46. #include "gfx/gl/gfxGLVertexDecl.h"
  47. #include "shaderGen/shaderGen.h"
  48. #include "gfxGLUtils.h"
  49. #if defined(TORQUE_OS_WIN)
  50. #include "gfx/gl/tGL/tWGL.h"
  51. #elif defined(TORQUE_OS_LINUX)
  52. #include "gfx/gl/tGL/tXGL.h"
  53. #endif
  54. GFXAdapter::CreateDeviceInstanceDelegate GFXGLDevice::mCreateDeviceInstance(GFXGLDevice::createInstance);
  55. GFXDevice *GFXGLDevice::createInstance( U32 adapterIndex )
  56. {
  57. return new GFXGLDevice(adapterIndex);
  58. }
  59. namespace GL
  60. {
  61. extern void gglPerformBinds();
  62. extern void gglPerformExtensionBinds(void *context);
  63. }
  64. void loadGLCore()
  65. {
  66. static bool coreLoaded = false; // Guess what this is for.
  67. if(coreLoaded)
  68. return;
  69. coreLoaded = true;
  70. // Make sure we've got our GL bindings.
  71. GL::gglPerformBinds();
  72. }
  73. void loadGLExtensions(void *context)
  74. {
  75. static bool extensionsLoaded = false;
  76. if(extensionsLoaded)
  77. return;
  78. extensionsLoaded = true;
  79. GL::gglPerformExtensionBinds(context);
  80. }
  81. void STDCALL glDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  82. const GLchar *message, const void *userParam)
  83. {
  84. // JTH [11/24/2016]: This is a temporary fix so that we do not get spammed for redundant fbo changes.
  85. // This only happens on Intel cards. This should be looked into sometime in the near future.
  86. if (dStrStartsWith(message, "API_ID_REDUNDANT_FBO"))
  87. return;
  88. if (severity == GL_DEBUG_SEVERITY_HIGH)
  89. Con::errorf("OPENGL: %s", message);
  90. else if (severity == GL_DEBUG_SEVERITY_MEDIUM)
  91. Con::warnf("OPENGL: %s", message);
  92. else if (severity == GL_DEBUG_SEVERITY_LOW)
  93. Con::printf("OPENGL: %s", message);
  94. }
  95. void STDCALL glAmdDebugCallback(GLuint id, GLenum category, GLenum severity, GLsizei length,
  96. const GLchar* message, GLvoid* userParam)
  97. {
  98. if (severity == GL_DEBUG_SEVERITY_HIGH)
  99. Con::errorf("AMDOPENGL: %s", message);
  100. else if (severity == GL_DEBUG_SEVERITY_MEDIUM)
  101. Con::warnf("AMDOPENGL: %s", message);
  102. else if (severity == GL_DEBUG_SEVERITY_LOW)
  103. Con::printf("AMDOPENGL: %s", message);
  104. }
  105. void GFXGLDevice::initGLState()
  106. {
  107. // We don't currently need to sync device state with a known good place because we are
  108. // going to set everything in GFXGLStateBlock, but if we change our GFXGLStateBlock strategy, this may
  109. // need to happen.
  110. // Deal with the card profiler here when we know we have a valid context.
  111. mCardProfiler = new GFXGLCardProfiler();
  112. mCardProfiler->init();
  113. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint*)&mMaxShaderTextures);
  114. // JTH: Needs removed, ffp
  115. //glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint*)&mMaxFFTextures);
  116. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, (GLint*)&mMaxTRColors);
  117. mMaxTRColors = getMin( mMaxTRColors, (U32)(GFXTextureTarget::MaxRenderSlotId-1) );
  118. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  119. // [JTH 5/6/2016] GLSL 1.50 is really SM 4.0
  120. // Setting mPixelShaderVersion to 3.0 will allow Advanced Lighting to run.
  121. mPixelShaderVersion = 3.0;
  122. // Set capability extensions.
  123. mCapabilities.anisotropicFiltering = mCardProfiler->queryProfile("GL_EXT_texture_filter_anisotropic");
  124. mCapabilities.bufferStorage = mCardProfiler->queryProfile("GL_ARB_buffer_storage");
  125. mCapabilities.textureStorage = mCardProfiler->queryProfile("GL_ARB_texture_storage");
  126. mCapabilities.copyImage = mCardProfiler->queryProfile("GL_ARB_copy_image");
  127. mCapabilities.vertexAttributeBinding = mCardProfiler->queryProfile("GL_ARB_vertex_attrib_binding");
  128. mCapabilities.khrDebug = mCardProfiler->queryProfile("GL_KHR_debug");
  129. mCapabilities.extDebugMarker = mCardProfiler->queryProfile("GL_EXT_debug_marker");
  130. String vendorStr = (const char*)glGetString( GL_VENDOR );
  131. if( vendorStr.find("NVIDIA", 0, String::NoCase | String::Left) != String::NPos)
  132. mUseGlMap = false;
  133. // Workaround for all Mac's, has a problem using glMap* with volatile buffers
  134. #ifdef TORQUE_OS_MAC
  135. mUseGlMap = false;
  136. #endif
  137. #if TORQUE_DEBUG
  138. if( gglHasExtension(ARB_debug_output) )
  139. {
  140. glEnable(GL_DEBUG_OUTPUT);
  141. glDebugMessageCallbackARB(glDebugCallback, NULL);
  142. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  143. GLuint unusedIds = 0;
  144. glDebugMessageControlARB(GL_DONT_CARE,
  145. GL_DONT_CARE,
  146. GL_DONT_CARE,
  147. 0,
  148. &unusedIds,
  149. GL_TRUE);
  150. }
  151. else if(gglHasExtension(AMD_debug_output))
  152. {
  153. glEnable(GL_DEBUG_OUTPUT);
  154. glDebugMessageCallbackAMD(glAmdDebugCallback, NULL);
  155. //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  156. GLuint unusedIds = 0;
  157. glDebugMessageEnableAMD(GL_DONT_CARE, GL_DONT_CARE, 0,&unusedIds, GL_TRUE);
  158. }
  159. #endif
  160. PlatformGL::setVSync(smEnableVSync);
  161. //install vsync callback
  162. Con::NotifyDelegate clbk(this, &GFXGLDevice::vsyncCallback);
  163. Con::addVariableNotify("$pref::Video::enableVerticalSync", clbk);
  164. //OpenGL 3 need a binded VAO for render
  165. GLuint vao;
  166. glGenVertexArrays(1, &vao);
  167. glBindVertexArray(vao);
  168. // MacOS uses OGL 4.1. This workaround is functional, but will not provide the improvied depth performance.
  169. #if defined(__MACOSX__)
  170. glDepthRangef(0.0, 1.0);
  171. #else
  172. glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
  173. #endif
  174. //enable sRGB
  175. glEnable(GL_FRAMEBUFFER_SRGB);
  176. //enable seamless cubemapping
  177. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  178. }
  179. void GFXGLDevice::vsyncCallback()
  180. {
  181. PlatformGL::setVSync(smEnableVSync);
  182. }
  183. GFXGLDevice::GFXGLDevice(U32 adapterIndex) :
  184. mAdapterIndex(adapterIndex),
  185. mNeedUpdateVertexAttrib(false),
  186. mCurrentPB(NULL),
  187. mDrawInstancesCount(0),
  188. mCurrentShader( NULL ),
  189. m_mCurrentWorld(true),
  190. m_mCurrentView(true),
  191. mContext(NULL),
  192. mPixelFormat(NULL),
  193. mPixelShaderVersion(0.0f),
  194. mMaxShaderTextures(2),
  195. mMaxFFTextures(2),
  196. mMaxTRColors(1),
  197. mClip(0, 0, 0, 0),
  198. mWindowRT(NULL),
  199. mUseGlMap(true)
  200. {
  201. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  202. {
  203. mCurrentVB[i] = NULL;
  204. mCurrentVB_Divisor[i] = 0;
  205. }
  206. // Initiailize capabilities to false.
  207. memset(&mCapabilities, 0, sizeof(GLCapabilities));
  208. loadGLCore();
  209. GFXGLEnumTranslate::init();
  210. GFXVertexColor::setSwizzle( &Swizzles::rgba );
  211. // OpenGL have native RGB, no need swizzle
  212. mDeviceSwizzle32 = &Swizzles::rgba;
  213. mDeviceSwizzle24 = &Swizzles::rgb;
  214. mTextureManager = new GFXGLTextureManager();
  215. gScreenShot = new ScreenShotGL();
  216. for(U32 i = 0; i < GFX_TEXTURE_STAGE_COUNT; i++)
  217. mActiveTextureType[i] = GL_ZERO;
  218. mNumVertexStream = 2;
  219. for(int i = 0; i < GS_COUNT; ++i)
  220. mModelViewProjSC[i] = NULL;
  221. mOpenglStateCache = new GFXGLStateCache;
  222. mCurrentConstBuffer = NULL;
  223. }
  224. GFXGLDevice::~GFXGLDevice()
  225. {
  226. mCurrentStateBlock = NULL;
  227. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  228. mCurrentVB[i] = NULL;
  229. mCurrentPB = NULL;
  230. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  231. mVolatileVBs[i] = NULL;
  232. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  233. mVolatilePBs[i] = NULL;
  234. // Clear out our current texture references
  235. for (U32 i = 0; i < GFX_TEXTURE_STAGE_COUNT; i++)
  236. {
  237. mCurrentTexture[i] = NULL;
  238. mNewTexture[i] = NULL;
  239. mCurrentCubemap[i] = NULL;
  240. mNewCubemap[i] = NULL;
  241. }
  242. mRTStack.clear();
  243. mCurrentRT = NULL;
  244. if( mTextureManager )
  245. {
  246. mTextureManager->zombify();
  247. mTextureManager->kill();
  248. }
  249. // Free device buffers
  250. DeviceBufferMap::Iterator bufferIter = mDeviceBufferMap.begin();
  251. for (; bufferIter != mDeviceBufferMap.end(); ++bufferIter)
  252. glDeleteBuffers(1, &bufferIter->value);
  253. GFXResource* walk = mResourceListHead;
  254. while(walk)
  255. {
  256. walk->zombify();
  257. walk = walk->getNextResource();
  258. }
  259. if( mCardProfiler )
  260. SAFE_DELETE( mCardProfiler );
  261. SAFE_DELETE( gScreenShot );
  262. SAFE_DELETE( mOpenglStateCache );
  263. }
  264. GLuint GFXGLDevice::getDeviceBuffer(const GFXShaderConstDesc desc)
  265. {
  266. String name(desc.name + "_" + String::ToString(desc.size));
  267. DeviceBufferMap::Iterator buf = mDeviceBufferMap.find(name);
  268. if (buf != mDeviceBufferMap.end())
  269. {
  270. return mDeviceBufferMap[name];
  271. }
  272. GLuint uboHandle;
  273. glGenBuffers(1, &uboHandle);
  274. glBindBuffer(GL_UNIFORM_BUFFER, uboHandle);
  275. glBufferData(GL_UNIFORM_BUFFER, desc.size, NULL, GL_DYNAMIC_DRAW); // allocate once
  276. mDeviceBufferMap[name] = uboHandle;
  277. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  278. return uboHandle;
  279. }
  280. void GFXGLDevice::zombify()
  281. {
  282. mTextureManager->zombify();
  283. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  284. if(mCurrentVB[i])
  285. mCurrentVB[i]->finish();
  286. if(mCurrentPB)
  287. mCurrentPB->finish();
  288. //mVolatileVBs.clear();
  289. //mVolatilePBs.clear();
  290. GFXResource* walk = mResourceListHead;
  291. while(walk)
  292. {
  293. walk->zombify();
  294. walk = walk->getNextResource();
  295. }
  296. }
  297. void GFXGLDevice::resurrect()
  298. {
  299. GFXResource* walk = mResourceListHead;
  300. while(walk)
  301. {
  302. walk->resurrect();
  303. walk = walk->getNextResource();
  304. }
  305. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  306. if(mCurrentVB[i])
  307. mCurrentVB[i]->prepare();
  308. if(mCurrentPB)
  309. mCurrentPB->prepare();
  310. mTextureManager->resurrect();
  311. }
  312. GFXVertexBuffer* GFXGLDevice::findVolatileVBO(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize)
  313. {
  314. PROFILE_SCOPE(GFXGLDevice_findVBPool);
  315. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  316. if ( mVolatileVBs[i]->mNumVerts >= numVerts &&
  317. mVolatileVBs[i]->mVertexFormat.isEqual( *vertexFormat ) &&
  318. mVolatileVBs[i]->mVertexSize == vertSize &&
  319. mVolatileVBs[i]->getRefCount() == 1 )
  320. return mVolatileVBs[i];
  321. // No existing VB, so create one
  322. PROFILE_SCOPE(GFXGLDevice_createVBPool);
  323. StrongRefPtr<GFXGLVertexBuffer> buf(new GFXGLVertexBuffer(GFX, numVerts, vertexFormat, vertSize, GFXBufferTypeVolatile));
  324. buf->registerResourceWithDevice(this);
  325. mVolatileVBs.push_back(buf);
  326. return buf.getPointer();
  327. }
  328. GFXPrimitiveBuffer* GFXGLDevice::findVolatilePBO(U32 numIndices, U32 numPrimitives)
  329. {
  330. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  331. if((mVolatilePBs[i]->mIndexCount >= numIndices) && (mVolatilePBs[i]->getRefCount() == 1))
  332. return mVolatilePBs[i];
  333. // No existing PB, so create one
  334. StrongRefPtr<GFXGLPrimitiveBuffer> buf(new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, GFXBufferTypeVolatile));
  335. buf->registerResourceWithDevice(this);
  336. mVolatilePBs.push_back(buf);
  337. return buf.getPointer();
  338. }
  339. GFXVertexBuffer *GFXGLDevice::allocVertexBuffer( U32 numVerts,
  340. const GFXVertexFormat *vertexFormat,
  341. U32 vertSize,
  342. GFXBufferType bufferType,
  343. void* data )
  344. {
  345. PROFILE_SCOPE(GFXGLDevice_allocVertexBuffer);
  346. if(bufferType == GFXBufferTypeVolatile)
  347. return findVolatileVBO(numVerts, vertexFormat, vertSize);
  348. GFXGLVertexBuffer* buf = new GFXGLVertexBuffer( GFX, numVerts, vertexFormat, vertSize, bufferType );
  349. buf->registerResourceWithDevice(this);
  350. if(data)
  351. {
  352. void* dest;
  353. buf->lock(0, numVerts, &dest);
  354. dMemcpy(dest, data, vertSize * numVerts);
  355. buf->unlock();
  356. }
  357. return buf;
  358. }
  359. GFXPrimitiveBuffer *GFXGLDevice::allocPrimitiveBuffer( U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void* data )
  360. {
  361. GFXPrimitiveBuffer* buf;
  362. if(bufferType == GFXBufferTypeVolatile)
  363. {
  364. buf = findVolatilePBO(numIndices, numPrimitives);
  365. }
  366. else
  367. {
  368. buf = new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, bufferType);
  369. buf->registerResourceWithDevice(this);
  370. }
  371. if(data)
  372. {
  373. void* dest;
  374. buf->lock(0, numIndices, &dest);
  375. dMemcpy(dest, data, sizeof(U16) * numIndices);
  376. buf->unlock();
  377. }
  378. return buf;
  379. }
  380. void GFXGLDevice::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  381. {
  382. AssertFatal(stream <= 1, "GFXGLDevice::setVertexStream only support 2 stream (0: data, 1: instancing)");
  383. //if(mCurrentVB[stream] != buffer)
  384. {
  385. // Reset the state the old VB required, then set the state the new VB requires.
  386. if( mCurrentVB[stream] )
  387. {
  388. mCurrentVB[stream]->finish();
  389. }
  390. mCurrentVB[stream] = static_cast<GFXGLVertexBuffer*>( buffer );
  391. mNeedUpdateVertexAttrib = true;
  392. }
  393. }
  394. void GFXGLDevice::setVertexStreamFrequency( U32 stream, U32 frequency )
  395. {
  396. if( stream == 0 )
  397. {
  398. mCurrentVB_Divisor[stream] = 0; // non instanced, is vertex buffer
  399. mDrawInstancesCount = frequency; // instances count
  400. }
  401. else
  402. {
  403. AssertFatal(frequency <= 1, "GFXGLDevice::setVertexStreamFrequency only support 0/1 for this stream" );
  404. if( stream == 1 && frequency == 1 )
  405. mCurrentVB_Divisor[stream] = 1; // instances data need a frequency of 1
  406. else
  407. mCurrentVB_Divisor[stream] = 0;
  408. }
  409. mNeedUpdateVertexAttrib = true;
  410. }
  411. GFXCubemap* GFXGLDevice::createCubemap()
  412. {
  413. GFXGLCubemap* cube = new GFXGLCubemap();
  414. cube->registerResourceWithDevice(this);
  415. return cube;
  416. };
  417. GFXCubemapArray *GFXGLDevice::createCubemapArray()
  418. {
  419. GFXGLCubemapArray* cubeArray = new GFXGLCubemapArray();
  420. cubeArray->registerResourceWithDevice(this);
  421. return cubeArray;
  422. }
  423. GFXTextureArray* GFXGLDevice::createTextureArray()
  424. {
  425. GFXGLTextureArray* textureArray = new GFXGLTextureArray();
  426. textureArray->registerResourceWithDevice(this);
  427. return textureArray;
  428. }
  429. void GFXGLDevice::endSceneInternal()
  430. {
  431. // nothing to do for opengl
  432. mCanCurrentlyRender = false;
  433. }
  434. void GFXGLDevice::copyResource(GFXTextureObject* pDst, GFXCubemap* pSrc, const U32 face)
  435. {
  436. AssertFatal(pDst, "GFXGLDevice::copyResource: Destination texture is null");
  437. AssertFatal(pSrc, "GFXGLDevice::copyResource: Source cubemap is null");
  438. GFXGLTextureObject* gGLDst = static_cast<GFXGLTextureObject*>(pDst);
  439. GFXGLCubemap* pGLSrc = static_cast<GFXGLCubemap*>(pSrc);
  440. const GFXFormat format = pGLSrc->getFormat();
  441. const bool isCompressed = ImageUtil::isCompressedFormat(format);
  442. const U32 mipLevels = pGLSrc->getMipMapLevels();
  443. const U32 texSize = pGLSrc->getSize();
  444. //set up pbo if we don't have copyImage support
  445. if (!GFXGL->mCapabilities.copyImage)
  446. {
  447. const GLuint pbo = gGLDst->getBuffer();
  448. glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
  449. //allocate data
  450. glBufferData(GL_PIXEL_PACK_BUFFER, texSize * texSize * GFXFormat_getByteSize(format), NULL, GL_STREAM_COPY);
  451. }
  452. for (U32 mip = 0; mip < mipLevels; mip++)
  453. {
  454. const U32 mipSize = texSize >> mip;
  455. if (GFXGL->mCapabilities.copyImage)
  456. {
  457. glCopyImageSubData(pGLSrc->mCubemap, GL_TEXTURE_CUBE_MAP, mip, 0, 0, face, gGLDst->getHandle(), GL_TEXTURE_2D, mip, 0, 0, 0, mipSize, mipSize, 1);
  458. }
  459. else
  460. {
  461. //pbo id
  462. const GLuint pbo = gGLDst->getBuffer();
  463. //copy source texture data to pbo
  464. glBindTexture(GL_TEXTURE_CUBE_MAP, pGLSrc->mCubemap);
  465. glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
  466. if (isCompressed)
  467. glGetCompressedTexImage(GFXGLFaceType[face], mip, NULL);
  468. else
  469. glGetTexImage(GFXGLFaceType[face], mip, GFXGLTextureFormat[format], GFXGLTextureType[format], NULL);
  470. glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
  471. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  472. //copy data from pbo to destination
  473. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
  474. glBindTexture(gGLDst->getBinding(), gGLDst->getHandle());
  475. if (isCompressed)
  476. {
  477. const U32 mipDataSize = getCompressedSurfaceSize(format, pGLSrc->getSize(), pGLSrc->getSize(), 0);
  478. glCompressedTexSubImage2D(gGLDst->getBinding(), mip, 0, 0, mipSize, mipSize, GFXGLTextureFormat[format], mipDataSize, NULL);
  479. }
  480. else
  481. {
  482. glTexSubImage2D(gGLDst->getBinding(), mip, 0, 0, mipSize, mipSize, GFXGLTextureFormat[format], GFXGLTextureType[format], NULL);
  483. }
  484. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
  485. glBindTexture(gGLDst->getBinding(), 0);
  486. }
  487. }
  488. }
  489. void GFXGLDevice::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
  490. {
  491. // Make sure we have flushed our render target state.
  492. _updateRenderTargets();
  493. bool writeAllColors = true;
  494. bool zwrite = true;
  495. bool writeAllStencil = true;
  496. const GFXStateBlockDesc *desc = NULL;
  497. if (mCurrentGLStateBlock)
  498. {
  499. desc = &mCurrentGLStateBlock->getDesc();
  500. zwrite = desc->zWriteEnable;
  501. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  502. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  503. }
  504. glColorMask(true, true, true, true);
  505. glDepthMask(true);
  506. glStencilMask(0xFFFFFFFF);
  507. glClearColor(color.red, color.green, color.blue, color.alpha);
  508. glClearDepth(z);
  509. glClearStencil(stencil);
  510. GLbitfield clearflags = 0;
  511. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  512. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  513. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  514. glClear(clearflags);
  515. if(!writeAllColors)
  516. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  517. if(!zwrite)
  518. glDepthMask(false);
  519. if(!writeAllStencil)
  520. glStencilMask(desc->stencilWriteMask);
  521. }
  522. void GFXGLDevice::clearColorAttachment(const U32 attachment, const LinearColorF& color)
  523. {
  524. const GLfloat clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  525. glClearBufferfv(GL_COLOR, attachment, clearColor);
  526. }
  527. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  528. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  529. {
  530. switch (primType)
  531. {
  532. case GFXPointList :
  533. return primitiveCount;
  534. break;
  535. case GFXLineList :
  536. return primitiveCount * 2;
  537. break;
  538. case GFXLineStrip :
  539. return primitiveCount + 1;
  540. break;
  541. case GFXTriangleList :
  542. return primitiveCount * 3;
  543. break;
  544. case GFXTriangleStrip :
  545. return 2 + primitiveCount;
  546. break;
  547. default:
  548. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  549. break;
  550. }
  551. return 0;
  552. }
  553. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  554. {
  555. PROFILE_SCOPE(GFXGLDevice_allocVertexDecl);
  556. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  557. static GFXGLVertexDeclMap declMap;
  558. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  559. if(itr != declMap.end())
  560. return &itr->value;
  561. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  562. decl.init(vertexFormat);
  563. return &decl;
  564. }
  565. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  566. {
  567. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  568. }
  569. inline void GFXGLDevice::preDrawPrimitive()
  570. {
  571. if( mStateDirty )
  572. {
  573. updateStates();
  574. }
  575. if(mCurrentShaderConstBuffer)
  576. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  577. if( mNeedUpdateVertexAttrib )
  578. {
  579. AssertFatal(mCurrVertexDecl, "");
  580. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  581. for(int i = 0; i < getNumVertexStreams(); ++i)
  582. {
  583. if(mCurrentVB[i])
  584. {
  585. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  586. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  587. }
  588. }
  589. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  590. }
  591. mNeedUpdateVertexAttrib = false;
  592. }
  593. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  594. {
  595. mDeviceStatistics.mDrawCalls++;
  596. mDeviceStatistics.mPolyCount += primitiveCount;
  597. }
  598. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  599. {
  600. preDrawPrimitive();
  601. if(mCurrentVB[0])
  602. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  603. if(mDrawInstancesCount)
  604. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  605. else
  606. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  607. postDrawPrimitive(primitiveCount);
  608. }
  609. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  610. U32 startVertex,
  611. U32 minIndex,
  612. U32 numVerts,
  613. U32 startIndex,
  614. U32 primitiveCount )
  615. {
  616. preDrawPrimitive();
  617. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex + mCurrentPrimitiveBuffer->mVolatileStart;
  618. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset + startVertex;
  619. if(mDrawInstancesCount)
  620. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  621. else
  622. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  623. postDrawPrimitive(primitiveCount);
  624. }
  625. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  626. {
  627. if(mCurrentPB)
  628. mCurrentPB->finish();
  629. mCurrentPB = pb;
  630. }
  631. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  632. {
  633. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  634. if (tex)
  635. {
  636. mActiveTextureType[textureUnit] = tex->getBinding();
  637. tex->bind(textureUnit);
  638. }
  639. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  640. {
  641. glActiveTexture(GL_TEXTURE0 + textureUnit);
  642. glBindTexture(mActiveTextureType[textureUnit], 0);
  643. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  644. mActiveTextureType[textureUnit] = GL_ZERO;
  645. }
  646. }
  647. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  648. {
  649. if(texture)
  650. {
  651. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  652. texture->bind(textureUnit);
  653. }
  654. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  655. {
  656. glActiveTexture(GL_TEXTURE0 + textureUnit);
  657. glBindTexture(mActiveTextureType[textureUnit], 0);
  658. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  659. mActiveTextureType[textureUnit] = GL_ZERO;
  660. }
  661. }
  662. void GFXGLDevice::setCubemapArrayInternal(U32 textureUnit, const GFXGLCubemapArray* texture)
  663. {
  664. if (texture)
  665. {
  666. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP_ARRAY_ARB;
  667. texture->bind(textureUnit);
  668. }
  669. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  670. {
  671. glActiveTexture(GL_TEXTURE0 + textureUnit);
  672. glBindTexture(mActiveTextureType[textureUnit], 0);
  673. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  674. mActiveTextureType[textureUnit] = GL_ZERO;
  675. }
  676. }
  677. void GFXGLDevice::setTextureArrayInternal(U32 textureUnit, const GFXGLTextureArray* texture)
  678. {
  679. if (texture)
  680. {
  681. mActiveTextureType[textureUnit] = GL_TEXTURE_2D_ARRAY;
  682. texture->bind(textureUnit);
  683. }
  684. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  685. {
  686. glActiveTexture(GL_TEXTURE0 + textureUnit);
  687. glBindTexture(mActiveTextureType[textureUnit], 0);
  688. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  689. mActiveTextureType[textureUnit] = GL_ZERO;
  690. }
  691. }
  692. void GFXGLDevice::setClipRect( const RectI &inRect )
  693. {
  694. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  695. // Clip the rect against the renderable size.
  696. Point2I size = mCurrentRT->getSize();
  697. RectI maxRect(Point2I(0,0), size);
  698. mClip = inRect;
  699. mClip.intersect(maxRect);
  700. static Point4F pt;
  701. F32 l = F32(mClip.point.x);
  702. F32 r = F32(mClip.point.x + mClip.extent.x);
  703. F32 b = F32(mClip.point.y + mClip.extent.y);
  704. F32 t = F32(mClip.point.y);
  705. // Set up projection matrix,
  706. //static Point4F pt;
  707. pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f);
  708. mProjectionMatrix.setColumn(0, pt);
  709. pt.set(0.0f, 2.0f / (t - b), 0.0f, 0.0f);
  710. mProjectionMatrix.setColumn(1, pt);
  711. pt.set(0.0f, 0.0f, 1.0f, 0.0f);
  712. mProjectionMatrix.setColumn(2, pt);
  713. pt.set((l + r) / (l - r), (t + b) / (b - t), 1.0f, 1.0f);
  714. mProjectionMatrix.setColumn(3, pt);
  715. MatrixF mTempMatrix(true);
  716. setViewMatrix( mTempMatrix );
  717. setWorldMatrix( mTempMatrix );
  718. // Set the viewport to the clip rect
  719. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  720. setViewport(viewport);
  721. }
  722. /// Creates a state block object based on the desc passed in. This object
  723. /// represents an immutable state.
  724. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  725. {
  726. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  727. }
  728. /// Activates a stateblock
  729. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  730. {
  731. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  732. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  733. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  734. if (force)
  735. glCurrent = NULL;
  736. glBlock->activate(glCurrent); // Doesn't use current yet.
  737. mCurrentGLStateBlock = glBlock;
  738. }
  739. //------------------------------------------------------------------------------
  740. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget(bool genMips)
  741. {
  742. GFXGLTextureTarget *targ = new GFXGLTextureTarget(genMips);
  743. targ->registerResourceWithDevice(this);
  744. return targ;
  745. }
  746. GFXFence * GFXGLDevice::createFence()
  747. {
  748. GFXFence* fence = _createPlatformSpecificFence();
  749. if(!fence)
  750. fence = new GFXGeneralFence( this );
  751. fence->registerResourceWithDevice(this);
  752. return fence;
  753. }
  754. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  755. {
  756. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  757. query->registerResourceWithDevice(this);
  758. return query;
  759. }
  760. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  761. {
  762. AssertFatal(type != GSTargetRestore, "");
  763. if( mGenericShader[GSColor] == NULL )
  764. {
  765. ShaderData *shaderData;
  766. shaderData = new ShaderData();
  767. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorV.glsl"));
  768. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorP.glsl"));
  769. shaderData->setField("pixVersion", "2.0");
  770. shaderData->registerObject();
  771. mGenericShader[GSColor] = shaderData->getShader();
  772. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  773. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  774. Sim::getRootGroup()->addObject(shaderData);
  775. shaderData = new ShaderData();
  776. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureV.glsl"));
  777. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureP.glsl"));
  778. shaderData->setSamplerName("$diffuseMap", 0);
  779. shaderData->setField("pixVersion", "2.0");
  780. shaderData->registerObject();
  781. mGenericShader[GSModColorTexture] = shaderData->getShader();
  782. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  783. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  784. Sim::getRootGroup()->addObject(shaderData);
  785. shaderData = new ShaderData();
  786. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureV.glsl"));
  787. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureP.glsl"));
  788. shaderData->setSamplerName("$diffuseMap", 0);
  789. shaderData->setField("pixVersion", "2.0");
  790. shaderData->registerObject();
  791. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  792. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  793. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  794. Sim::getRootGroup()->addObject(shaderData);
  795. shaderData = new ShaderData();
  796. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureV.glsl"));
  797. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureP.glsl"));
  798. shaderData->setSamplerName("$diffuseMap", 0);
  799. shaderData->setField("pixVersion", "2.0");
  800. shaderData->registerObject();
  801. mGenericShader[GSTexture] = shaderData->getShader();
  802. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  803. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  804. Sim::getRootGroup()->addObject(shaderData);
  805. }
  806. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  807. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  808. setShader( mGenericShader[type] );
  809. setShaderConstBuffer( mGenericShaderBuffer[type] );
  810. }
  811. GFXShader* GFXGLDevice::createShader()
  812. {
  813. GFXGLShader* shader = new GFXGLShader(this);
  814. shader->registerResourceWithDevice( this );
  815. return shader;
  816. }
  817. void GFXGLDevice::setShader(GFXShader *shader, bool force)
  818. {
  819. if(mCurrentShader == shader && !force)
  820. return;
  821. if ( shader )
  822. {
  823. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  824. glShader->useProgram();
  825. mCurrentShader = shader;
  826. }
  827. else
  828. {
  829. setupGenericShaders();
  830. }
  831. }
  832. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  833. {
  834. if (buffer)
  835. {
  836. PROFILE_SCOPE(GFXGLDevice_setShaderConstBufferInternal);
  837. AssertFatal(static_cast<GFXGLShaderConstBuffer*>(buffer), "Incorrect shader const buffer type for this device!");
  838. GFXGLShaderConstBuffer* oglBuffer = static_cast<GFXGLShaderConstBuffer*>(buffer);
  839. oglBuffer->activate(mCurrentConstBuffer);
  840. mCurrentConstBuffer = oglBuffer;
  841. }
  842. else
  843. {
  844. mCurrentConstBuffer = NULL;
  845. }
  846. }
  847. U32 GFXGLDevice::getNumSamplers() const
  848. {
  849. return getMin((U32)GFX_TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  850. }
  851. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  852. {
  853. if(mWindowRT && mWindowRT->getPointer())
  854. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  855. return NULL;
  856. }
  857. U32 GFXGLDevice::getNumRenderTargets() const
  858. {
  859. return mMaxTRColors;
  860. }
  861. void GFXGLDevice::_updateRenderTargets()
  862. {
  863. if ( mRTDirty || mCurrentRT->isPendingState() )
  864. {
  865. if ( mRTDeactivate )
  866. {
  867. mRTDeactivate->deactivate();
  868. mRTDeactivate = NULL;
  869. }
  870. // NOTE: The render target changes is not really accurate
  871. // as the GFXTextureTarget supports MRT internally. So when
  872. // we activate a GFXTarget it could result in multiple calls
  873. // to SetRenderTarget on the actual device.
  874. mDeviceStatistics.mRenderTargetChanges++;
  875. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  876. if ( tex )
  877. {
  878. tex->applyState();
  879. tex->makeActive();
  880. }
  881. else
  882. {
  883. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  884. AssertFatal( win != NULL,
  885. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  886. win->makeActive();
  887. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  888. {
  889. mRTDirty = false;
  890. GFX->updateStates(true);
  891. }
  892. }
  893. mRTDirty = false;
  894. }
  895. if ( mViewportDirty )
  896. {
  897. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  898. mViewportDirty = false;
  899. }
  900. }
  901. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  902. const Vector<GFXFormat>& formats,
  903. bool texture,
  904. bool mustblend,
  905. bool mustfilter )
  906. {
  907. for(U32 i = 0; i < formats.size(); i++)
  908. {
  909. // Single channel textures are not supported by FBOs.
  910. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  911. continue;
  912. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  913. continue;
  914. return formats[i];
  915. }
  916. return GFXFormatR8G8B8A8;
  917. }
  918. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  919. {
  920. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  921. if( gglHasExtension(ATI_meminfo) )
  922. {
  923. GLint mem[4] = {0};
  924. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  925. /* With mem[0] i get only the total memory free in the pool in KB
  926. *
  927. * mem[0] - total memory free in the pool
  928. * mem[1] - largest available free block in the pool
  929. * mem[2] - total auxiliary memory free
  930. * mem[3] - largest auxiliary free block
  931. */
  932. return mem[0] / 1024;
  933. }
  934. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  935. else if( gglHasExtension(NVX_gpu_memory_info) )
  936. {
  937. GLint mem = 0;
  938. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  939. return mem / 1024;
  940. }
  941. #if defined(TORQUE_OS_WIN)
  942. else if( (gglHasWExtension(AMD_gpu_association)) )
  943. {
  944. // Just assume 1 AMD gpu. Who uses crossfire anyways now? And, crossfire doesn't double
  945. // vram anyways, so does it really matter?
  946. UINT id;
  947. if (wglGetGPUIDsAMD(1, &id) != 0)
  948. {
  949. S32 memorySize;
  950. if (wglGetGPUInfoAMD(id, WGL_GPU_RAM_AMD, GL_INT, 1, &memorySize) != -1)
  951. {
  952. // memory size is returned in MB
  953. return memorySize;
  954. }
  955. }
  956. }
  957. #endif
  958. #if defined(TORQUE_OS_LINUX)
  959. else if ( (gglHasXExtension(NULL, NULL, MESA_query_renderer)) )
  960. {
  961. // memory size is in mb
  962. U32 memorySize;
  963. glXQueryCurrentRendererIntegerMESA(GLX_RENDERER_VIDEO_MEMORY_MESA, &memorySize);
  964. return memorySize;
  965. }
  966. #endif
  967. // No other way, sad. Probably windows Intel.
  968. return 0;
  969. }
  970. //
  971. // Register this device with GFXInit
  972. //
  973. class GFXGLRegisterDevice
  974. {
  975. public:
  976. GFXGLRegisterDevice()
  977. {
  978. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  979. }
  980. };
  981. static GFXGLRegisterDevice pGLRegisterDevice;
  982. DefineEngineFunction(cycleResources, void, (),, "")
  983. {
  984. static_cast<GFXGLDevice*>(GFX)->zombify();
  985. static_cast<GFXGLDevice*>(GFX)->resurrect();
  986. }