gfxGLDevice.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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 "platform/platformGL.h"
  25. #include "gfx/gfxCubemap.h"
  26. #include "gfx/screenshot.h"
  27. #include "gfx/gfxDrawUtil.h"
  28. #include "gfx/gl/gfxGLEnumTranslate.h"
  29. #include "gfx/gl/gfxGLVertexBuffer.h"
  30. #include "gfx/gl/gfxGLPrimitiveBuffer.h"
  31. #include "gfx/gl/gfxGLTextureTarget.h"
  32. #include "gfx/gl/gfxGLTextureManager.h"
  33. #include "gfx/gl/gfxGLTextureObject.h"
  34. #include "gfx/gl/gfxGLCubemap.h"
  35. #include "gfx/gl/gfxGLCardProfiler.h"
  36. #include "gfx/gl/gfxGLWindowTarget.h"
  37. #include "platform/platformDlibrary.h"
  38. #include "gfx/gl/gfxGLShader.h"
  39. #include "gfx/primBuilder.h"
  40. #include "console/console.h"
  41. #include "gfx/gl/gfxGLOcclusionQuery.h"
  42. #include "materials/shaderData.h"
  43. #include "gfx/gl/gfxGLStateCache.h"
  44. #include "gfx/gl/gfxGLVertexAttribLocation.h"
  45. #include "gfx/gl/gfxGLVertexDecl.h"
  46. GFXAdapter::CreateDeviceInstanceDelegate GFXGLDevice::mCreateDeviceInstance(GFXGLDevice::createInstance);
  47. GFXDevice *GFXGLDevice::createInstance( U32 adapterIndex )
  48. {
  49. return new GFXGLDevice(adapterIndex);
  50. }
  51. namespace GL
  52. {
  53. extern void gglPerformBinds();
  54. extern void gglPerformExtensionBinds(void *context);
  55. }
  56. void loadGLCore()
  57. {
  58. static bool coreLoaded = false; // Guess what this is for.
  59. if(coreLoaded)
  60. return;
  61. coreLoaded = true;
  62. // Make sure we've got our GL bindings.
  63. GL::gglPerformBinds();
  64. }
  65. void loadGLExtensions(void *context)
  66. {
  67. static bool extensionsLoaded = false;
  68. if(extensionsLoaded)
  69. return;
  70. extensionsLoaded = true;
  71. GL::gglPerformExtensionBinds(context);
  72. }
  73. void STDCALL glDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  74. const GLchar *message, const void *userParam)
  75. {
  76. if (severity == GL_DEBUG_SEVERITY_HIGH)
  77. Con::errorf("OPENGL: %s", message);
  78. else if (severity == GL_DEBUG_SEVERITY_MEDIUM)
  79. Con::warnf("OPENGL: %s", message);
  80. else if (severity == GL_DEBUG_SEVERITY_LOW)
  81. Con::printf("OPENGL: %s", message);
  82. }
  83. void STDCALL glAmdDebugCallback(GLuint id, GLenum category, GLenum severity, GLsizei length,
  84. const GLchar* message, GLvoid* userParam)
  85. {
  86. if (severity == GL_DEBUG_SEVERITY_HIGH)
  87. Con::errorf("AMDOPENGL: %s", message);
  88. else if (severity == GL_DEBUG_SEVERITY_MEDIUM)
  89. Con::warnf("AMDOPENGL: %s", message);
  90. else if (severity == GL_DEBUG_SEVERITY_LOW)
  91. Con::printf("AMDOPENGL: %s", message);
  92. }
  93. // >>>> OPENGL INTEL WORKAROUND @todo OPENGL INTEL remove
  94. PFNGLBINDFRAMEBUFFERPROC __openglBindFramebuffer = NULL;
  95. void STDCALL _t3d_glBindFramebuffer(GLenum target, GLuint framebuffer)
  96. {
  97. if( target == GL_FRAMEBUFFER )
  98. {
  99. if( GFXGL->getOpenglCache()->getCacheBinded( GL_DRAW_FRAMEBUFFER ) == framebuffer
  100. && GFXGL->getOpenglCache()->getCacheBinded( GL_READ_FRAMEBUFFER ) == framebuffer )
  101. return;
  102. }
  103. else if( GFXGL->getOpenglCache()->getCacheBinded( target ) == framebuffer )
  104. return;
  105. __openglBindFramebuffer(target, framebuffer);
  106. GFXGL->getOpenglCache()->setCacheBinded( target, framebuffer);
  107. }
  108. // <<<< OPENGL INTEL WORKAROUND
  109. void GFXGLDevice::initGLState()
  110. {
  111. // We don't currently need to sync device state with a known good place because we are
  112. // going to set everything in GFXGLStateBlock, but if we change our GFXGLStateBlock strategy, this may
  113. // need to happen.
  114. // Deal with the card profiler here when we know we have a valid context.
  115. mCardProfiler = new GFXGLCardProfiler();
  116. mCardProfiler->init();
  117. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint*)&mMaxShaderTextures);
  118. glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint*)&mMaxFFTextures);
  119. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, (GLint*)&mMaxTRColors);
  120. mMaxTRColors = getMin( mMaxTRColors, (U32)(GFXTextureTarget::MaxRenderSlotId-1) );
  121. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  122. // [JTH 5/6/2016] GLSL 1.50 is really SM 4.0
  123. // Setting mPixelShaderVersion to 3.0 will allow Advanced Lighting to run.
  124. mPixelShaderVersion = 3.0;
  125. // Set capability extensions.
  126. mCapabilities.anisotropicFiltering = mCardProfiler->queryProfile("GL_EXT_texture_filter_anisotropic");
  127. mCapabilities.bufferStorage = mCardProfiler->queryProfile("GL_ARB_buffer_storage");
  128. mCapabilities.shaderModel5 = mCardProfiler->queryProfile("GL_ARB_gpu_shader5");
  129. mCapabilities.textureStorage = mCardProfiler->queryProfile("GL_ARB_texture_storage");
  130. mCapabilities.samplerObjects = mCardProfiler->queryProfile("GL_ARB_sampler_objects");
  131. mCapabilities.copyImage = mCardProfiler->queryProfile("GL_ARB_copy_image");
  132. mCapabilities.vertexAttributeBinding = mCardProfiler->queryProfile("GL_ARB_vertex_attrib_binding");
  133. String vendorStr = (const char*)glGetString( GL_VENDOR );
  134. if( vendorStr.find("NVIDIA", 0, String::NoCase | String::Left) != String::NPos)
  135. mUseGlMap = false;
  136. if( vendorStr.find("INTEL", 0, String::NoCase | String::Left ) != String::NPos)
  137. {
  138. // @todo OPENGL INTEL - This is a workaround for a warning spam or even crashes with actual framebuffer code, remove when implemented TGL layer.
  139. __openglBindFramebuffer = glBindFramebuffer;
  140. glBindFramebuffer = &_t3d_glBindFramebuffer;
  141. }
  142. #ifdef TORQUE_NSIGHT_WORKAROUND
  143. __GLEW_ARB_buffer_storage = false;
  144. #endif
  145. #if TORQUE_DEBUG
  146. if( gglHasExtension(ARB_debug_output) )
  147. {
  148. glEnable(GL_DEBUG_OUTPUT);
  149. glDebugMessageCallbackARB(glDebugCallback, NULL);
  150. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  151. GLuint unusedIds = 0;
  152. glDebugMessageControlARB(GL_DONT_CARE,
  153. GL_DONT_CARE,
  154. GL_DONT_CARE,
  155. 0,
  156. &unusedIds,
  157. GL_TRUE);
  158. }
  159. else if(gglHasExtension(AMD_debug_output))
  160. {
  161. glEnable(GL_DEBUG_OUTPUT);
  162. glDebugMessageCallbackAMD(glAmdDebugCallback, NULL);
  163. //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  164. GLuint unusedIds = 0;
  165. glDebugMessageEnableAMD(GL_DONT_CARE, GL_DONT_CARE, 0,&unusedIds, GL_TRUE);
  166. }
  167. #endif
  168. PlatformGL::setVSync(smDisableVSync ? 0 : 1);
  169. //OpenGL 3 need a binded VAO for render
  170. GLuint vao;
  171. glGenVertexArrays(1, &vao);
  172. glBindVertexArray(vao);
  173. }
  174. GFXGLDevice::GFXGLDevice(U32 adapterIndex) :
  175. mAdapterIndex(adapterIndex),
  176. mCurrentPB(NULL),
  177. mDrawInstancesCount(0),
  178. m_mCurrentWorld(true),
  179. m_mCurrentView(true),
  180. mContext(NULL),
  181. mPixelFormat(NULL),
  182. mPixelShaderVersion(0.0f),
  183. mMaxShaderTextures(2),
  184. mMaxFFTextures(2),
  185. mMaxTRColors(1),
  186. mClip(0, 0, 0, 0),
  187. mCurrentShader( NULL ),
  188. mNeedUpdateVertexAttrib(false),
  189. mWindowRT(NULL),
  190. mUseGlMap(true)
  191. {
  192. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  193. {
  194. mCurrentVB[i] = NULL;
  195. mCurrentVB_Divisor[i] = 0;
  196. }
  197. // Initiailize capabilities to false.
  198. memset(&mCapabilities, 0, sizeof(GLCapabilities));
  199. loadGLCore();
  200. GFXGLEnumTranslate::init();
  201. GFXVertexColor::setSwizzle( &Swizzles::rgba );
  202. // OpenGL have native RGB, no need swizzle
  203. mDeviceSwizzle32 = &Swizzles::rgba;
  204. mDeviceSwizzle24 = &Swizzles::rgb;
  205. mTextureManager = new GFXGLTextureManager();
  206. gScreenShot = new ScreenShot();
  207. for(U32 i = 0; i < TEXTURE_STAGE_COUNT; i++)
  208. mActiveTextureType[i] = GL_ZERO;
  209. mNumVertexStream = 2;
  210. for(int i = 0; i < GS_COUNT; ++i)
  211. mModelViewProjSC[i] = NULL;
  212. mOpenglStateCache = new GFXGLStateCache;
  213. }
  214. GFXGLDevice::~GFXGLDevice()
  215. {
  216. mCurrentStateBlock = NULL;
  217. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  218. mCurrentVB[i] = NULL;
  219. mCurrentPB = NULL;
  220. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  221. mVolatileVBs[i] = NULL;
  222. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  223. mVolatilePBs[i] = NULL;
  224. // Clear out our current texture references
  225. for (U32 i = 0; i < TEXTURE_STAGE_COUNT; i++)
  226. {
  227. mCurrentTexture[i] = NULL;
  228. mNewTexture[i] = NULL;
  229. mCurrentCubemap[i] = NULL;
  230. mNewCubemap[i] = NULL;
  231. }
  232. mRTStack.clear();
  233. mCurrentRT = NULL;
  234. if( mTextureManager )
  235. {
  236. mTextureManager->zombify();
  237. mTextureManager->kill();
  238. }
  239. GFXResource* walk = mResourceListHead;
  240. while(walk)
  241. {
  242. walk->zombify();
  243. walk = walk->getNextResource();
  244. }
  245. if( mCardProfiler )
  246. SAFE_DELETE( mCardProfiler );
  247. SAFE_DELETE( gScreenShot );
  248. SAFE_DELETE( mOpenglStateCache );
  249. }
  250. void GFXGLDevice::zombify()
  251. {
  252. mTextureManager->zombify();
  253. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  254. if(mCurrentVB[i])
  255. mCurrentVB[i]->finish();
  256. if(mCurrentPB)
  257. mCurrentPB->finish();
  258. //mVolatileVBs.clear();
  259. //mVolatilePBs.clear();
  260. GFXResource* walk = mResourceListHead;
  261. while(walk)
  262. {
  263. walk->zombify();
  264. walk = walk->getNextResource();
  265. }
  266. }
  267. void GFXGLDevice::resurrect()
  268. {
  269. GFXResource* walk = mResourceListHead;
  270. while(walk)
  271. {
  272. walk->resurrect();
  273. walk = walk->getNextResource();
  274. }
  275. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  276. if(mCurrentVB[i])
  277. mCurrentVB[i]->prepare();
  278. if(mCurrentPB)
  279. mCurrentPB->prepare();
  280. mTextureManager->resurrect();
  281. }
  282. GFXVertexBuffer* GFXGLDevice::findVolatileVBO(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize)
  283. {
  284. PROFILE_SCOPE(GFXGLDevice_findVBPool);
  285. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  286. if ( mVolatileVBs[i]->mNumVerts >= numVerts &&
  287. mVolatileVBs[i]->mVertexFormat.isEqual( *vertexFormat ) &&
  288. mVolatileVBs[i]->mVertexSize == vertSize &&
  289. mVolatileVBs[i]->getRefCount() == 1 )
  290. return mVolatileVBs[i];
  291. // No existing VB, so create one
  292. PROFILE_SCOPE(GFXGLDevice_createVBPool);
  293. StrongRefPtr<GFXGLVertexBuffer> buf(new GFXGLVertexBuffer(GFX, numVerts, vertexFormat, vertSize, GFXBufferTypeVolatile));
  294. buf->registerResourceWithDevice(this);
  295. mVolatileVBs.push_back(buf);
  296. return buf.getPointer();
  297. }
  298. GFXPrimitiveBuffer* GFXGLDevice::findVolatilePBO(U32 numIndices, U32 numPrimitives)
  299. {
  300. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  301. if((mVolatilePBs[i]->mIndexCount >= numIndices) && (mVolatilePBs[i]->getRefCount() == 1))
  302. return mVolatilePBs[i];
  303. // No existing PB, so create one
  304. StrongRefPtr<GFXGLPrimitiveBuffer> buf(new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, GFXBufferTypeVolatile));
  305. buf->registerResourceWithDevice(this);
  306. mVolatilePBs.push_back(buf);
  307. return buf.getPointer();
  308. }
  309. GFXVertexBuffer *GFXGLDevice::allocVertexBuffer( U32 numVerts,
  310. const GFXVertexFormat *vertexFormat,
  311. U32 vertSize,
  312. GFXBufferType bufferType,
  313. void* data )
  314. {
  315. PROFILE_SCOPE(GFXGLDevice_allocVertexBuffer);
  316. if(bufferType == GFXBufferTypeVolatile)
  317. return findVolatileVBO(numVerts, vertexFormat, vertSize);
  318. GFXGLVertexBuffer* buf = new GFXGLVertexBuffer( GFX, numVerts, vertexFormat, vertSize, bufferType );
  319. buf->registerResourceWithDevice(this);
  320. if(data)
  321. {
  322. void* dest;
  323. buf->lock(0, numVerts, &dest);
  324. dMemcpy(dest, data, vertSize * numVerts);
  325. buf->unlock();
  326. }
  327. return buf;
  328. }
  329. GFXPrimitiveBuffer *GFXGLDevice::allocPrimitiveBuffer( U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void* data )
  330. {
  331. GFXPrimitiveBuffer* buf;
  332. if(bufferType == GFXBufferTypeVolatile)
  333. {
  334. buf = findVolatilePBO(numIndices, numPrimitives);
  335. }
  336. else
  337. {
  338. buf = new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, bufferType);
  339. buf->registerResourceWithDevice(this);
  340. }
  341. if(data)
  342. {
  343. void* dest;
  344. buf->lock(0, numIndices, &dest);
  345. dMemcpy(dest, data, sizeof(U16) * numIndices);
  346. buf->unlock();
  347. }
  348. return buf;
  349. }
  350. void GFXGLDevice::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  351. {
  352. AssertFatal(stream <= 1, "GFXGLDevice::setVertexStream only support 2 stream (0: data, 1: instancing)");
  353. //if(mCurrentVB[stream] != buffer)
  354. {
  355. // Reset the state the old VB required, then set the state the new VB requires.
  356. if( mCurrentVB[stream] )
  357. {
  358. mCurrentVB[stream]->finish();
  359. }
  360. mCurrentVB[stream] = static_cast<GFXGLVertexBuffer*>( buffer );
  361. mNeedUpdateVertexAttrib = true;
  362. }
  363. }
  364. void GFXGLDevice::setVertexStreamFrequency( U32 stream, U32 frequency )
  365. {
  366. if( stream == 0 )
  367. {
  368. mCurrentVB_Divisor[stream] = 0; // non instanced, is vertex buffer
  369. mDrawInstancesCount = frequency; // instances count
  370. }
  371. else
  372. {
  373. AssertFatal(frequency <= 1, "GFXGLDevice::setVertexStreamFrequency only support 0/1 for this stream" );
  374. if( stream == 1 && frequency == 1 )
  375. mCurrentVB_Divisor[stream] = 1; // instances data need a frequency of 1
  376. else
  377. mCurrentVB_Divisor[stream] = 0;
  378. }
  379. mNeedUpdateVertexAttrib = true;
  380. }
  381. GFXCubemap* GFXGLDevice::createCubemap()
  382. {
  383. GFXGLCubemap* cube = new GFXGLCubemap();
  384. cube->registerResourceWithDevice(this);
  385. return cube;
  386. };
  387. void GFXGLDevice::endSceneInternal()
  388. {
  389. // nothing to do for opengl
  390. mCanCurrentlyRender = false;
  391. }
  392. void GFXGLDevice::clear(U32 flags, ColorI color, F32 z, U32 stencil)
  393. {
  394. // Make sure we have flushed our render target state.
  395. _updateRenderTargets();
  396. bool writeAllColors = true;
  397. bool zwrite = true;
  398. bool writeAllStencil = true;
  399. const GFXStateBlockDesc *desc = NULL;
  400. if (mCurrentGLStateBlock)
  401. {
  402. desc = &mCurrentGLStateBlock->getDesc();
  403. zwrite = desc->zWriteEnable;
  404. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  405. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  406. }
  407. glColorMask(true, true, true, true);
  408. glDepthMask(true);
  409. glStencilMask(0xFFFFFFFF);
  410. ColorF c = color;
  411. glClearColor(c.red, c.green, c.blue, c.alpha);
  412. glClearDepth(z);
  413. glClearStencil(stencil);
  414. GLbitfield clearflags = 0;
  415. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  416. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  417. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  418. glClear(clearflags);
  419. if(!writeAllColors)
  420. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  421. if(!zwrite)
  422. glDepthMask(false);
  423. if(!writeAllStencil)
  424. glStencilMask(desc->stencilWriteMask);
  425. }
  426. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  427. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  428. {
  429. switch (primType)
  430. {
  431. case GFXPointList :
  432. return primitiveCount;
  433. break;
  434. case GFXLineList :
  435. return primitiveCount * 2;
  436. break;
  437. case GFXLineStrip :
  438. return primitiveCount + 1;
  439. break;
  440. case GFXTriangleList :
  441. return primitiveCount * 3;
  442. break;
  443. case GFXTriangleStrip :
  444. return 2 + primitiveCount;
  445. break;
  446. default:
  447. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  448. break;
  449. }
  450. return 0;
  451. }
  452. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  453. {
  454. PROFILE_SCOPE(GFXGLDevice_allocVertexDecl);
  455. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  456. static GFXGLVertexDeclMap declMap;
  457. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  458. if(itr != declMap.end())
  459. return &itr->value;
  460. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  461. decl.init(vertexFormat);
  462. return &decl;
  463. }
  464. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  465. {
  466. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  467. }
  468. inline void GFXGLDevice::preDrawPrimitive()
  469. {
  470. if( mStateDirty )
  471. {
  472. updateStates();
  473. }
  474. if(mCurrentShaderConstBuffer)
  475. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  476. if( mNeedUpdateVertexAttrib )
  477. {
  478. AssertFatal(mCurrVertexDecl, "");
  479. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  480. for(int i = 0; i < getNumVertexStreams(); ++i)
  481. {
  482. if(mCurrentVB[i])
  483. {
  484. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  485. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  486. }
  487. }
  488. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  489. }
  490. mNeedUpdateVertexAttrib = false;
  491. }
  492. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  493. {
  494. mDeviceStatistics.mDrawCalls++;
  495. mDeviceStatistics.mPolyCount += primitiveCount;
  496. }
  497. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  498. {
  499. preDrawPrimitive();
  500. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  501. if(mDrawInstancesCount)
  502. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  503. else
  504. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  505. postDrawPrimitive(primitiveCount);
  506. }
  507. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  508. U32 startVertex,
  509. U32 minIndex,
  510. U32 numVerts,
  511. U32 startIndex,
  512. U32 primitiveCount )
  513. {
  514. AssertFatal( startVertex == 0, "GFXGLDevice::drawIndexedPrimitive() - Non-zero startVertex unsupported!" );
  515. preDrawPrimitive();
  516. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex;
  517. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset;
  518. if(mDrawInstancesCount)
  519. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  520. else
  521. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  522. postDrawPrimitive(primitiveCount);
  523. }
  524. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  525. {
  526. if(mCurrentPB)
  527. mCurrentPB->finish();
  528. mCurrentPB = pb;
  529. }
  530. void GFXGLDevice::setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable)
  531. {
  532. // ONLY NEEDED ON FFP
  533. }
  534. void GFXGLDevice::setLightMaterialInternal(const GFXLightMaterial mat)
  535. {
  536. // ONLY NEEDED ON FFP
  537. }
  538. void GFXGLDevice::setGlobalAmbientInternal(ColorF color)
  539. {
  540. glLightModelfv(GL_LIGHT_MODEL_AMBIENT, (GLfloat*)&color);
  541. }
  542. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  543. {
  544. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  545. if (tex)
  546. {
  547. mActiveTextureType[textureUnit] = tex->getBinding();
  548. tex->bind(textureUnit);
  549. }
  550. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  551. {
  552. glActiveTexture(GL_TEXTURE0 + textureUnit);
  553. glBindTexture(mActiveTextureType[textureUnit], 0);
  554. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  555. mActiveTextureType[textureUnit] = GL_ZERO;
  556. }
  557. }
  558. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  559. {
  560. if(texture)
  561. {
  562. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  563. texture->bind(textureUnit);
  564. }
  565. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  566. {
  567. glActiveTexture(GL_TEXTURE0 + textureUnit);
  568. glBindTexture(mActiveTextureType[textureUnit], 0);
  569. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  570. mActiveTextureType[textureUnit] = GL_ZERO;
  571. }
  572. }
  573. void GFXGLDevice::setMatrix( GFXMatrixType mtype, const MatrixF &mat )
  574. {
  575. // ONLY NEEDED ON FFP
  576. }
  577. void GFXGLDevice::setClipRect( const RectI &inRect )
  578. {
  579. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  580. // Clip the rect against the renderable size.
  581. Point2I size = mCurrentRT->getSize();
  582. RectI maxRect(Point2I(0,0), size);
  583. mClip = inRect;
  584. mClip.intersect(maxRect);
  585. // Create projection matrix. See http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html
  586. const F32 left = mClip.point.x;
  587. const F32 right = mClip.point.x + mClip.extent.x;
  588. const F32 bottom = mClip.extent.y;
  589. const F32 top = 0.0f;
  590. const F32 near = 0.0f;
  591. const F32 far = 1.0f;
  592. const F32 tx = -(right + left)/(right - left);
  593. const F32 ty = -(top + bottom)/(top - bottom);
  594. const F32 tz = -(far + near)/(far - near);
  595. static Point4F pt;
  596. pt.set(2.0f / (right - left), 0.0f, 0.0f, 0.0f);
  597. mProjectionMatrix.setColumn(0, pt);
  598. pt.set(0.0f, 2.0f/(top - bottom), 0.0f, 0.0f);
  599. mProjectionMatrix.setColumn(1, pt);
  600. pt.set(0.0f, 0.0f, -2.0f/(far - near), 0.0f);
  601. mProjectionMatrix.setColumn(2, pt);
  602. pt.set(tx, ty, tz, 1.0f);
  603. mProjectionMatrix.setColumn(3, pt);
  604. // Translate projection matrix.
  605. static MatrixF translate(true);
  606. pt.set(0.0f, -mClip.point.y, 0.0f, 1.0f);
  607. translate.setColumn(3, pt);
  608. mProjectionMatrix *= translate;
  609. setMatrix(GFXMatrixProjection, mProjectionMatrix);
  610. MatrixF mTempMatrix(true);
  611. setViewMatrix( mTempMatrix );
  612. setWorldMatrix( mTempMatrix );
  613. // Set the viewport to the clip rect
  614. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  615. setViewport(viewport);
  616. }
  617. /// Creates a state block object based on the desc passed in. This object
  618. /// represents an immutable state.
  619. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  620. {
  621. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  622. }
  623. /// Activates a stateblock
  624. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  625. {
  626. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  627. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  628. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  629. if (force)
  630. glCurrent = NULL;
  631. glBlock->activate(glCurrent); // Doesn't use current yet.
  632. mCurrentGLStateBlock = glBlock;
  633. }
  634. //------------------------------------------------------------------------------
  635. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget()
  636. {
  637. GFXGLTextureTarget *targ = new GFXGLTextureTarget();
  638. targ->registerResourceWithDevice(this);
  639. return targ;
  640. }
  641. GFXFence * GFXGLDevice::createFence()
  642. {
  643. GFXFence* fence = _createPlatformSpecificFence();
  644. if(!fence)
  645. fence = new GFXGeneralFence( this );
  646. fence->registerResourceWithDevice(this);
  647. return fence;
  648. }
  649. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  650. {
  651. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  652. query->registerResourceWithDevice(this);
  653. return query;
  654. }
  655. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  656. {
  657. AssertFatal(type != GSTargetRestore, "");
  658. if( mGenericShader[GSColor] == NULL )
  659. {
  660. ShaderData *shaderData;
  661. shaderData = new ShaderData();
  662. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/colorV.glsl");
  663. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/colorP.glsl");
  664. shaderData->setField("pixVersion", "2.0");
  665. shaderData->registerObject();
  666. mGenericShader[GSColor] = shaderData->getShader();
  667. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  668. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  669. Sim::getRootGroup()->addObject(shaderData);
  670. shaderData = new ShaderData();
  671. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/modColorTextureV.glsl");
  672. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/modColorTextureP.glsl");
  673. shaderData->setSamplerName("$diffuseMap", 0);
  674. shaderData->setField("pixVersion", "2.0");
  675. shaderData->registerObject();
  676. mGenericShader[GSModColorTexture] = shaderData->getShader();
  677. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  678. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  679. Sim::getRootGroup()->addObject(shaderData);
  680. shaderData = new ShaderData();
  681. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/addColorTextureV.glsl");
  682. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/addColorTextureP.glsl");
  683. shaderData->setSamplerName("$diffuseMap", 0);
  684. shaderData->setField("pixVersion", "2.0");
  685. shaderData->registerObject();
  686. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  687. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  688. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  689. Sim::getRootGroup()->addObject(shaderData);
  690. shaderData = new ShaderData();
  691. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/textureV.glsl");
  692. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/textureP.glsl");
  693. shaderData->setSamplerName("$diffuseMap", 0);
  694. shaderData->setField("pixVersion", "2.0");
  695. shaderData->registerObject();
  696. mGenericShader[GSTexture] = shaderData->getShader();
  697. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  698. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  699. Sim::getRootGroup()->addObject(shaderData);
  700. }
  701. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  702. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  703. setShader( mGenericShader[type] );
  704. setShaderConstBuffer( mGenericShaderBuffer[type] );
  705. }
  706. GFXShader* GFXGLDevice::createShader()
  707. {
  708. GFXGLShader* shader = new GFXGLShader();
  709. shader->registerResourceWithDevice( this );
  710. return shader;
  711. }
  712. void GFXGLDevice::setShader(GFXShader *shader, bool force)
  713. {
  714. if(mCurrentShader == shader && !force)
  715. return;
  716. if ( shader )
  717. {
  718. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  719. glShader->useProgram();
  720. mCurrentShader = shader;
  721. }
  722. else
  723. {
  724. setupGenericShaders();
  725. }
  726. }
  727. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  728. {
  729. PROFILE_SCOPE(GFXGLDevice_setShaderConstBufferInternal);
  730. static_cast<GFXGLShaderConstBuffer*>(buffer)->activate();
  731. }
  732. U32 GFXGLDevice::getNumSamplers() const
  733. {
  734. return getMin((U32)TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  735. }
  736. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  737. {
  738. if(mWindowRT && mWindowRT->getPointer())
  739. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  740. return NULL;
  741. }
  742. U32 GFXGLDevice::getNumRenderTargets() const
  743. {
  744. return mMaxTRColors;
  745. }
  746. void GFXGLDevice::_updateRenderTargets()
  747. {
  748. if ( mRTDirty || mCurrentRT->isPendingState() )
  749. {
  750. if ( mRTDeactivate )
  751. {
  752. mRTDeactivate->deactivate();
  753. mRTDeactivate = NULL;
  754. }
  755. // NOTE: The render target changes is not really accurate
  756. // as the GFXTextureTarget supports MRT internally. So when
  757. // we activate a GFXTarget it could result in multiple calls
  758. // to SetRenderTarget on the actual device.
  759. mDeviceStatistics.mRenderTargetChanges++;
  760. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  761. if ( tex )
  762. {
  763. tex->applyState();
  764. tex->makeActive();
  765. }
  766. else
  767. {
  768. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  769. AssertFatal( win != NULL,
  770. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  771. win->makeActive();
  772. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  773. {
  774. mRTDirty = false;
  775. GFX->updateStates(true);
  776. }
  777. }
  778. mRTDirty = false;
  779. }
  780. if ( mViewportDirty )
  781. {
  782. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  783. mViewportDirty = false;
  784. }
  785. }
  786. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  787. const Vector<GFXFormat>& formats,
  788. bool texture,
  789. bool mustblend,
  790. bool mustfilter )
  791. {
  792. for(U32 i = 0; i < formats.size(); i++)
  793. {
  794. // Single channel textures are not supported by FBOs.
  795. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  796. continue;
  797. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  798. continue;
  799. return formats[i];
  800. }
  801. return GFXFormatR8G8B8A8;
  802. }
  803. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  804. {
  805. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  806. if( gglHasExtension(ATI_meminfo) )
  807. {
  808. GLint mem[4] = {0};
  809. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  810. /* With mem[0] i get only the total memory free in the pool in KB
  811. *
  812. * mem[0] - total memory free in the pool
  813. * mem[1] - largest available free block in the pool
  814. * mem[2] - total auxiliary memory free
  815. * mem[3] - largest auxiliary free block
  816. */
  817. return mem[0] / 1024;
  818. }
  819. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  820. else if( gglHasExtension(NVX_gpu_memory_info) )
  821. {
  822. GLint mem = 0;
  823. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  824. return mem / 1024;
  825. }
  826. // TODO OPENGL, add supprt for INTEL cards.
  827. return 0;
  828. }
  829. //
  830. // Register this device with GFXInit
  831. //
  832. class GFXGLRegisterDevice
  833. {
  834. public:
  835. GFXGLRegisterDevice()
  836. {
  837. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  838. }
  839. };
  840. static GFXGLRegisterDevice pGLRegisterDevice;
  841. ConsoleFunction(cycleResources, void, 1, 1, "")
  842. {
  843. static_cast<GFXGLDevice*>(GFX)->zombify();
  844. static_cast<GFXGLDevice*>(GFX)->resurrect();
  845. }