gfxGLDevice.cpp 37 KB

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