gfxGLDevice.cpp 31 KB

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