gfxGLDevice.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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. }
  223. GFXGLDevice::~GFXGLDevice()
  224. {
  225. mCurrentStateBlock = NULL;
  226. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  227. mCurrentVB[i] = NULL;
  228. mCurrentPB = NULL;
  229. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  230. mVolatileVBs[i] = NULL;
  231. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  232. mVolatilePBs[i] = NULL;
  233. // Clear out our current texture references
  234. for (U32 i = 0; i < GFX_TEXTURE_STAGE_COUNT; i++)
  235. {
  236. mCurrentTexture[i] = NULL;
  237. mNewTexture[i] = NULL;
  238. mCurrentCubemap[i] = NULL;
  239. mNewCubemap[i] = NULL;
  240. }
  241. mRTStack.clear();
  242. mCurrentRT = NULL;
  243. if( mTextureManager )
  244. {
  245. mTextureManager->zombify();
  246. mTextureManager->kill();
  247. }
  248. GFXResource* walk = mResourceListHead;
  249. while(walk)
  250. {
  251. walk->zombify();
  252. walk = walk->getNextResource();
  253. }
  254. if( mCardProfiler )
  255. SAFE_DELETE( mCardProfiler );
  256. SAFE_DELETE( gScreenShot );
  257. SAFE_DELETE( mOpenglStateCache );
  258. }
  259. void GFXGLDevice::zombify()
  260. {
  261. mTextureManager->zombify();
  262. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  263. if(mCurrentVB[i])
  264. mCurrentVB[i]->finish();
  265. if(mCurrentPB)
  266. mCurrentPB->finish();
  267. //mVolatileVBs.clear();
  268. //mVolatilePBs.clear();
  269. GFXResource* walk = mResourceListHead;
  270. while(walk)
  271. {
  272. walk->zombify();
  273. walk = walk->getNextResource();
  274. }
  275. }
  276. void GFXGLDevice::resurrect()
  277. {
  278. GFXResource* walk = mResourceListHead;
  279. while(walk)
  280. {
  281. walk->resurrect();
  282. walk = walk->getNextResource();
  283. }
  284. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  285. if(mCurrentVB[i])
  286. mCurrentVB[i]->prepare();
  287. if(mCurrentPB)
  288. mCurrentPB->prepare();
  289. mTextureManager->resurrect();
  290. }
  291. GFXVertexBuffer* GFXGLDevice::findVolatileVBO(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize)
  292. {
  293. PROFILE_SCOPE(GFXGLDevice_findVBPool);
  294. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  295. if ( mVolatileVBs[i]->mNumVerts >= numVerts &&
  296. mVolatileVBs[i]->mVertexFormat.isEqual( *vertexFormat ) &&
  297. mVolatileVBs[i]->mVertexSize == vertSize &&
  298. mVolatileVBs[i]->getRefCount() == 1 )
  299. return mVolatileVBs[i];
  300. // No existing VB, so create one
  301. PROFILE_SCOPE(GFXGLDevice_createVBPool);
  302. StrongRefPtr<GFXGLVertexBuffer> buf(new GFXGLVertexBuffer(GFX, numVerts, vertexFormat, vertSize, GFXBufferTypeVolatile));
  303. buf->registerResourceWithDevice(this);
  304. mVolatileVBs.push_back(buf);
  305. return buf.getPointer();
  306. }
  307. GFXPrimitiveBuffer* GFXGLDevice::findVolatilePBO(U32 numIndices, U32 numPrimitives)
  308. {
  309. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  310. if((mVolatilePBs[i]->mIndexCount >= numIndices) && (mVolatilePBs[i]->getRefCount() == 1))
  311. return mVolatilePBs[i];
  312. // No existing PB, so create one
  313. StrongRefPtr<GFXGLPrimitiveBuffer> buf(new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, GFXBufferTypeVolatile));
  314. buf->registerResourceWithDevice(this);
  315. mVolatilePBs.push_back(buf);
  316. return buf.getPointer();
  317. }
  318. GFXVertexBuffer *GFXGLDevice::allocVertexBuffer( U32 numVerts,
  319. const GFXVertexFormat *vertexFormat,
  320. U32 vertSize,
  321. GFXBufferType bufferType,
  322. void* data )
  323. {
  324. PROFILE_SCOPE(GFXGLDevice_allocVertexBuffer);
  325. if(bufferType == GFXBufferTypeVolatile)
  326. return findVolatileVBO(numVerts, vertexFormat, vertSize);
  327. GFXGLVertexBuffer* buf = new GFXGLVertexBuffer( GFX, numVerts, vertexFormat, vertSize, bufferType );
  328. buf->registerResourceWithDevice(this);
  329. if(data)
  330. {
  331. void* dest;
  332. buf->lock(0, numVerts, &dest);
  333. dMemcpy(dest, data, vertSize * numVerts);
  334. buf->unlock();
  335. }
  336. return buf;
  337. }
  338. GFXPrimitiveBuffer *GFXGLDevice::allocPrimitiveBuffer( U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void* data )
  339. {
  340. GFXPrimitiveBuffer* buf;
  341. if(bufferType == GFXBufferTypeVolatile)
  342. {
  343. buf = findVolatilePBO(numIndices, numPrimitives);
  344. }
  345. else
  346. {
  347. buf = new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, bufferType);
  348. buf->registerResourceWithDevice(this);
  349. }
  350. if(data)
  351. {
  352. void* dest;
  353. buf->lock(0, numIndices, &dest);
  354. dMemcpy(dest, data, sizeof(U16) * numIndices);
  355. buf->unlock();
  356. }
  357. return buf;
  358. }
  359. void GFXGLDevice::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  360. {
  361. AssertFatal(stream <= 1, "GFXGLDevice::setVertexStream only support 2 stream (0: data, 1: instancing)");
  362. //if(mCurrentVB[stream] != buffer)
  363. {
  364. // Reset the state the old VB required, then set the state the new VB requires.
  365. if( mCurrentVB[stream] )
  366. {
  367. mCurrentVB[stream]->finish();
  368. }
  369. mCurrentVB[stream] = static_cast<GFXGLVertexBuffer*>( buffer );
  370. mNeedUpdateVertexAttrib = true;
  371. }
  372. }
  373. void GFXGLDevice::setVertexStreamFrequency( U32 stream, U32 frequency )
  374. {
  375. if( stream == 0 )
  376. {
  377. mCurrentVB_Divisor[stream] = 0; // non instanced, is vertex buffer
  378. mDrawInstancesCount = frequency; // instances count
  379. }
  380. else
  381. {
  382. AssertFatal(frequency <= 1, "GFXGLDevice::setVertexStreamFrequency only support 0/1 for this stream" );
  383. if( stream == 1 && frequency == 1 )
  384. mCurrentVB_Divisor[stream] = 1; // instances data need a frequency of 1
  385. else
  386. mCurrentVB_Divisor[stream] = 0;
  387. }
  388. mNeedUpdateVertexAttrib = true;
  389. }
  390. GFXCubemap* GFXGLDevice::createCubemap()
  391. {
  392. GFXGLCubemap* cube = new GFXGLCubemap();
  393. cube->registerResourceWithDevice(this);
  394. return cube;
  395. };
  396. GFXCubemapArray *GFXGLDevice::createCubemapArray()
  397. {
  398. GFXGLCubemapArray* cubeArray = new GFXGLCubemapArray();
  399. cubeArray->registerResourceWithDevice(this);
  400. return cubeArray;
  401. }
  402. GFXTextureArray* GFXGLDevice::createTextureArray()
  403. {
  404. GFXGLTextureArray* textureArray = new GFXGLTextureArray();
  405. textureArray->registerResourceWithDevice(this);
  406. return textureArray;
  407. }
  408. void GFXGLDevice::endSceneInternal()
  409. {
  410. // nothing to do for opengl
  411. mCanCurrentlyRender = false;
  412. }
  413. void GFXGLDevice::copyResource(GFXTextureObject* pDst, GFXCubemap* pSrc, const U32 face)
  414. {
  415. AssertFatal(pDst, "GFXGLDevice::copyResource: Destination texture is null");
  416. AssertFatal(pSrc, "GFXGLDevice::copyResource: Source cubemap is null");
  417. GFXGLTextureObject* gGLDst = static_cast<GFXGLTextureObject*>(pDst);
  418. GFXGLCubemap* pGLSrc = static_cast<GFXGLCubemap*>(pSrc);
  419. const GFXFormat format = pGLSrc->getFormat();
  420. const bool isCompressed = ImageUtil::isCompressedFormat(format);
  421. const U32 mipLevels = pGLSrc->getMipMapLevels();
  422. const U32 texSize = pGLSrc->getSize();
  423. //set up pbo if we don't have copyImage support
  424. if (!GFXGL->mCapabilities.copyImage)
  425. {
  426. const GLuint pbo = gGLDst->getBuffer();
  427. glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
  428. //allocate data
  429. glBufferData(GL_PIXEL_PACK_BUFFER, texSize * texSize * GFXFormat_getByteSize(format), NULL, GL_STREAM_COPY);
  430. }
  431. for (U32 mip = 0; mip < mipLevels; mip++)
  432. {
  433. const U32 mipSize = texSize >> mip;
  434. if (GFXGL->mCapabilities.copyImage)
  435. {
  436. glCopyImageSubData(pGLSrc->mCubemap, GL_TEXTURE_CUBE_MAP, mip, 0, 0, face, gGLDst->getHandle(), GL_TEXTURE_2D, mip, 0, 0, 0, mipSize, mipSize, 1);
  437. }
  438. else
  439. {
  440. //pbo id
  441. const GLuint pbo = gGLDst->getBuffer();
  442. //copy source texture data to pbo
  443. glBindTexture(GL_TEXTURE_CUBE_MAP, pGLSrc->mCubemap);
  444. glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
  445. if (isCompressed)
  446. glGetCompressedTexImage(GFXGLFaceType[face], mip, NULL);
  447. else
  448. glGetTexImage(GFXGLFaceType[face], mip, GFXGLTextureFormat[format], GFXGLTextureType[format], NULL);
  449. glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
  450. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  451. //copy data from pbo to destination
  452. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
  453. glBindTexture(gGLDst->getBinding(), gGLDst->getHandle());
  454. if (isCompressed)
  455. {
  456. const U32 mipDataSize = getCompressedSurfaceSize(format, pGLSrc->getSize(), pGLSrc->getSize(), 0);
  457. glCompressedTexSubImage2D(gGLDst->getBinding(), mip, 0, 0, mipSize, mipSize, GFXGLTextureFormat[format], mipDataSize, NULL);
  458. }
  459. else
  460. {
  461. glTexSubImage2D(gGLDst->getBinding(), mip, 0, 0, mipSize, mipSize, GFXGLTextureFormat[format], GFXGLTextureType[format], NULL);
  462. }
  463. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
  464. glBindTexture(gGLDst->getBinding(), 0);
  465. }
  466. }
  467. }
  468. void GFXGLDevice::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
  469. {
  470. // Make sure we have flushed our render target state.
  471. _updateRenderTargets();
  472. bool writeAllColors = true;
  473. bool zwrite = true;
  474. bool writeAllStencil = true;
  475. const GFXStateBlockDesc *desc = NULL;
  476. if (mCurrentGLStateBlock)
  477. {
  478. desc = &mCurrentGLStateBlock->getDesc();
  479. zwrite = desc->zWriteEnable;
  480. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  481. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  482. }
  483. glColorMask(true, true, true, true);
  484. glDepthMask(true);
  485. glStencilMask(0xFFFFFFFF);
  486. glClearColor(color.red, color.green, color.blue, color.alpha);
  487. glClearDepth(z);
  488. glClearStencil(stencil);
  489. GLbitfield clearflags = 0;
  490. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  491. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  492. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  493. glClear(clearflags);
  494. if(!writeAllColors)
  495. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  496. if(!zwrite)
  497. glDepthMask(false);
  498. if(!writeAllStencil)
  499. glStencilMask(desc->stencilWriteMask);
  500. }
  501. void GFXGLDevice::clearColorAttachment(const U32 attachment, const LinearColorF& color)
  502. {
  503. const GLfloat clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  504. glClearBufferfv(GL_COLOR, attachment, clearColor);
  505. }
  506. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  507. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  508. {
  509. switch (primType)
  510. {
  511. case GFXPointList :
  512. return primitiveCount;
  513. break;
  514. case GFXLineList :
  515. return primitiveCount * 2;
  516. break;
  517. case GFXLineStrip :
  518. return primitiveCount + 1;
  519. break;
  520. case GFXTriangleList :
  521. return primitiveCount * 3;
  522. break;
  523. case GFXTriangleStrip :
  524. return 2 + primitiveCount;
  525. break;
  526. default:
  527. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  528. break;
  529. }
  530. return 0;
  531. }
  532. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  533. {
  534. PROFILE_SCOPE(GFXGLDevice_allocVertexDecl);
  535. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  536. static GFXGLVertexDeclMap declMap;
  537. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  538. if(itr != declMap.end())
  539. return &itr->value;
  540. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  541. decl.init(vertexFormat);
  542. return &decl;
  543. }
  544. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  545. {
  546. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  547. }
  548. inline void GFXGLDevice::preDrawPrimitive()
  549. {
  550. if( mStateDirty )
  551. {
  552. updateStates();
  553. }
  554. if(mCurrentShaderConstBuffer)
  555. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  556. if( mNeedUpdateVertexAttrib )
  557. {
  558. AssertFatal(mCurrVertexDecl, "");
  559. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  560. for(int i = 0; i < getNumVertexStreams(); ++i)
  561. {
  562. if(mCurrentVB[i])
  563. {
  564. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  565. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  566. }
  567. }
  568. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  569. }
  570. mNeedUpdateVertexAttrib = false;
  571. }
  572. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  573. {
  574. mDeviceStatistics.mDrawCalls++;
  575. mDeviceStatistics.mPolyCount += primitiveCount;
  576. }
  577. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  578. {
  579. preDrawPrimitive();
  580. if(mCurrentVB[0])
  581. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  582. if(mDrawInstancesCount)
  583. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  584. else
  585. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  586. postDrawPrimitive(primitiveCount);
  587. }
  588. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  589. U32 startVertex,
  590. U32 minIndex,
  591. U32 numVerts,
  592. U32 startIndex,
  593. U32 primitiveCount )
  594. {
  595. preDrawPrimitive();
  596. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex + mCurrentPrimitiveBuffer->mVolatileStart;
  597. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset + startVertex;
  598. if(mDrawInstancesCount)
  599. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  600. else
  601. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  602. postDrawPrimitive(primitiveCount);
  603. }
  604. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  605. {
  606. if(mCurrentPB)
  607. mCurrentPB->finish();
  608. mCurrentPB = pb;
  609. }
  610. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  611. {
  612. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  613. if (tex)
  614. {
  615. mActiveTextureType[textureUnit] = tex->getBinding();
  616. tex->bind(textureUnit);
  617. }
  618. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  619. {
  620. glActiveTexture(GL_TEXTURE0 + textureUnit);
  621. glBindTexture(mActiveTextureType[textureUnit], 0);
  622. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  623. mActiveTextureType[textureUnit] = GL_ZERO;
  624. }
  625. }
  626. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  627. {
  628. if(texture)
  629. {
  630. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  631. texture->bind(textureUnit);
  632. }
  633. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  634. {
  635. glActiveTexture(GL_TEXTURE0 + textureUnit);
  636. glBindTexture(mActiveTextureType[textureUnit], 0);
  637. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  638. mActiveTextureType[textureUnit] = GL_ZERO;
  639. }
  640. }
  641. void GFXGLDevice::setCubemapArrayInternal(U32 textureUnit, const GFXGLCubemapArray* texture)
  642. {
  643. if (texture)
  644. {
  645. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP_ARRAY_ARB;
  646. texture->bind(textureUnit);
  647. }
  648. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  649. {
  650. glActiveTexture(GL_TEXTURE0 + textureUnit);
  651. glBindTexture(mActiveTextureType[textureUnit], 0);
  652. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  653. mActiveTextureType[textureUnit] = GL_ZERO;
  654. }
  655. }
  656. void GFXGLDevice::setTextureArrayInternal(U32 textureUnit, const GFXGLTextureArray* texture)
  657. {
  658. if (texture)
  659. {
  660. mActiveTextureType[textureUnit] = GL_TEXTURE_2D_ARRAY;
  661. texture->bind(textureUnit);
  662. }
  663. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  664. {
  665. glActiveTexture(GL_TEXTURE0 + textureUnit);
  666. glBindTexture(mActiveTextureType[textureUnit], 0);
  667. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  668. mActiveTextureType[textureUnit] = GL_ZERO;
  669. }
  670. }
  671. void GFXGLDevice::setClipRect( const RectI &inRect )
  672. {
  673. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  674. // Clip the rect against the renderable size.
  675. Point2I size = mCurrentRT->getSize();
  676. RectI maxRect(Point2I(0,0), size);
  677. mClip = inRect;
  678. mClip.intersect(maxRect);
  679. static Point4F pt;
  680. F32 l = F32(mClip.point.x);
  681. F32 r = F32(mClip.point.x + mClip.extent.x);
  682. F32 b = F32(mClip.point.y + mClip.extent.y);
  683. F32 t = F32(mClip.point.y);
  684. // Set up projection matrix,
  685. //static Point4F pt;
  686. pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f);
  687. mProjectionMatrix.setColumn(0, pt);
  688. pt.set(0.0f, 2.0f / (t - b), 0.0f, 0.0f);
  689. mProjectionMatrix.setColumn(1, pt);
  690. pt.set(0.0f, 0.0f, 1.0f, 0.0f);
  691. mProjectionMatrix.setColumn(2, pt);
  692. pt.set((l + r) / (l - r), (t + b) / (b - t), 1.0f, 1.0f);
  693. mProjectionMatrix.setColumn(3, pt);
  694. MatrixF mTempMatrix(true);
  695. setViewMatrix( mTempMatrix );
  696. setWorldMatrix( mTempMatrix );
  697. // Set the viewport to the clip rect
  698. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  699. setViewport(viewport);
  700. }
  701. /// Creates a state block object based on the desc passed in. This object
  702. /// represents an immutable state.
  703. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  704. {
  705. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  706. }
  707. /// Activates a stateblock
  708. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  709. {
  710. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  711. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  712. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  713. if (force)
  714. glCurrent = NULL;
  715. glBlock->activate(glCurrent); // Doesn't use current yet.
  716. mCurrentGLStateBlock = glBlock;
  717. }
  718. //------------------------------------------------------------------------------
  719. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget(bool genMips)
  720. {
  721. GFXGLTextureTarget *targ = new GFXGLTextureTarget(genMips);
  722. targ->registerResourceWithDevice(this);
  723. return targ;
  724. }
  725. GFXFence * GFXGLDevice::createFence()
  726. {
  727. GFXFence* fence = _createPlatformSpecificFence();
  728. if(!fence)
  729. fence = new GFXGeneralFence( this );
  730. fence->registerResourceWithDevice(this);
  731. return fence;
  732. }
  733. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  734. {
  735. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  736. query->registerResourceWithDevice(this);
  737. return query;
  738. }
  739. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  740. {
  741. AssertFatal(type != GSTargetRestore, "");
  742. if( mGenericShader[GSColor] == NULL )
  743. {
  744. ShaderData *shaderData;
  745. shaderData = new ShaderData();
  746. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorV.glsl"));
  747. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorP.glsl"));
  748. shaderData->setField("pixVersion", "2.0");
  749. shaderData->registerObject();
  750. mGenericShader[GSColor] = shaderData->getShader();
  751. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  752. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  753. Sim::getRootGroup()->addObject(shaderData);
  754. shaderData = new ShaderData();
  755. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureV.glsl"));
  756. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureP.glsl"));
  757. shaderData->setSamplerName("$diffuseMap", 0);
  758. shaderData->setField("pixVersion", "2.0");
  759. shaderData->registerObject();
  760. mGenericShader[GSModColorTexture] = shaderData->getShader();
  761. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  762. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  763. Sim::getRootGroup()->addObject(shaderData);
  764. shaderData = new ShaderData();
  765. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureV.glsl"));
  766. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureP.glsl"));
  767. shaderData->setSamplerName("$diffuseMap", 0);
  768. shaderData->setField("pixVersion", "2.0");
  769. shaderData->registerObject();
  770. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  771. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  772. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  773. Sim::getRootGroup()->addObject(shaderData);
  774. shaderData = new ShaderData();
  775. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureV.glsl"));
  776. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureP.glsl"));
  777. shaderData->setSamplerName("$diffuseMap", 0);
  778. shaderData->setField("pixVersion", "2.0");
  779. shaderData->registerObject();
  780. mGenericShader[GSTexture] = shaderData->getShader();
  781. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  782. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  783. Sim::getRootGroup()->addObject(shaderData);
  784. }
  785. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  786. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  787. setShader( mGenericShader[type] );
  788. setShaderConstBuffer( mGenericShaderBuffer[type] );
  789. }
  790. GFXShader* GFXGLDevice::createShader()
  791. {
  792. GFXGLShader* shader = new GFXGLShader(this);
  793. shader->registerResourceWithDevice( this );
  794. return shader;
  795. }
  796. void GFXGLDevice::setShader(GFXShader *shader, bool force)
  797. {
  798. if(mCurrentShader == shader && !force)
  799. return;
  800. if ( shader )
  801. {
  802. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  803. glShader->useProgram();
  804. mCurrentShader = shader;
  805. }
  806. else
  807. {
  808. setupGenericShaders();
  809. }
  810. }
  811. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  812. {
  813. PROFILE_SCOPE(GFXGLDevice_setShaderConstBufferInternal);
  814. static_cast<GFXGLShaderConstBuffer*>(buffer)->activate();
  815. }
  816. U32 GFXGLDevice::getNumSamplers() const
  817. {
  818. return getMin((U32)GFX_TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  819. }
  820. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  821. {
  822. if(mWindowRT && mWindowRT->getPointer())
  823. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  824. return NULL;
  825. }
  826. U32 GFXGLDevice::getNumRenderTargets() const
  827. {
  828. return mMaxTRColors;
  829. }
  830. void GFXGLDevice::_updateRenderTargets()
  831. {
  832. if ( mRTDirty || mCurrentRT->isPendingState() )
  833. {
  834. if ( mRTDeactivate )
  835. {
  836. mRTDeactivate->deactivate();
  837. mRTDeactivate = NULL;
  838. }
  839. // NOTE: The render target changes is not really accurate
  840. // as the GFXTextureTarget supports MRT internally. So when
  841. // we activate a GFXTarget it could result in multiple calls
  842. // to SetRenderTarget on the actual device.
  843. mDeviceStatistics.mRenderTargetChanges++;
  844. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  845. if ( tex )
  846. {
  847. tex->applyState();
  848. tex->makeActive();
  849. }
  850. else
  851. {
  852. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  853. AssertFatal( win != NULL,
  854. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  855. win->makeActive();
  856. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  857. {
  858. mRTDirty = false;
  859. GFX->updateStates(true);
  860. }
  861. }
  862. mRTDirty = false;
  863. }
  864. if ( mViewportDirty )
  865. {
  866. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  867. mViewportDirty = false;
  868. }
  869. }
  870. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  871. const Vector<GFXFormat>& formats,
  872. bool texture,
  873. bool mustblend,
  874. bool mustfilter )
  875. {
  876. for(U32 i = 0; i < formats.size(); i++)
  877. {
  878. // Single channel textures are not supported by FBOs.
  879. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  880. continue;
  881. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  882. continue;
  883. return formats[i];
  884. }
  885. return GFXFormatR8G8B8A8;
  886. }
  887. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  888. {
  889. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  890. if( gglHasExtension(ATI_meminfo) )
  891. {
  892. GLint mem[4] = {0};
  893. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  894. /* With mem[0] i get only the total memory free in the pool in KB
  895. *
  896. * mem[0] - total memory free in the pool
  897. * mem[1] - largest available free block in the pool
  898. * mem[2] - total auxiliary memory free
  899. * mem[3] - largest auxiliary free block
  900. */
  901. return mem[0] / 1024;
  902. }
  903. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  904. else if( gglHasExtension(NVX_gpu_memory_info) )
  905. {
  906. GLint mem = 0;
  907. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  908. return mem / 1024;
  909. }
  910. #if defined(TORQUE_OS_WIN)
  911. else if( (gglHasWExtension(AMD_gpu_association)) )
  912. {
  913. // Just assume 1 AMD gpu. Who uses crossfire anyways now? And, crossfire doesn't double
  914. // vram anyways, so does it really matter?
  915. UINT id;
  916. if (wglGetGPUIDsAMD(1, &id) != 0)
  917. {
  918. S32 memorySize;
  919. if (wglGetGPUInfoAMD(id, WGL_GPU_RAM_AMD, GL_INT, 1, &memorySize) != -1)
  920. {
  921. // memory size is returned in MB
  922. return memorySize;
  923. }
  924. }
  925. }
  926. #endif
  927. #if defined(TORQUE_OS_LINUX)
  928. else if ( (gglHasXExtension(NULL, NULL, MESA_query_renderer)) )
  929. {
  930. // memory size is in mb
  931. U32 memorySize;
  932. glXQueryCurrentRendererIntegerMESA(GLX_RENDERER_VIDEO_MEMORY_MESA, &memorySize);
  933. return memorySize;
  934. }
  935. #endif
  936. // No other way, sad. Probably windows Intel.
  937. return 0;
  938. }
  939. //
  940. // Register this device with GFXInit
  941. //
  942. class GFXGLRegisterDevice
  943. {
  944. public:
  945. GFXGLRegisterDevice()
  946. {
  947. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  948. }
  949. };
  950. static GFXGLRegisterDevice pGLRegisterDevice;
  951. DefineEngineFunction(cycleResources, void, (),, "")
  952. {
  953. static_cast<GFXGLDevice*>(GFX)->zombify();
  954. static_cast<GFXGLDevice*>(GFX)->resurrect();
  955. }