gfxGLDevice.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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. {
  302. if(bufferType == GFXBufferTypeVolatile)
  303. return findVolatileVBO(numVerts, vertexFormat, vertSize);
  304. GFXGLVertexBuffer* buf = new GFXGLVertexBuffer( GFX, numVerts, vertexFormat, vertSize, bufferType );
  305. buf->registerResourceWithDevice(this);
  306. return buf;
  307. }
  308. GFXPrimitiveBuffer *GFXGLDevice::allocPrimitiveBuffer( U32 numIndices, U32 numPrimitives, GFXBufferType bufferType )
  309. {
  310. if(bufferType == GFXBufferTypeVolatile)
  311. return findVolatilePBO(numIndices, numPrimitives);
  312. GFXGLPrimitiveBuffer* buf = new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, bufferType);
  313. buf->registerResourceWithDevice(this);
  314. return buf;
  315. }
  316. void GFXGLDevice::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  317. {
  318. AssertFatal(stream <= 1, "GFXGLDevice::setVertexStream only support 2 stream (0: data, 1: instancing)");
  319. //if(mCurrentVB[stream] != buffer)
  320. {
  321. // Reset the state the old VB required, then set the state the new VB requires.
  322. if( mCurrentVB[stream] )
  323. {
  324. mCurrentVB[stream]->finish();
  325. }
  326. mCurrentVB[stream] = static_cast<GFXGLVertexBuffer*>( buffer );
  327. mNeedUpdateVertexAttrib = true;
  328. }
  329. }
  330. void GFXGLDevice::setVertexStreamFrequency( U32 stream, U32 frequency )
  331. {
  332. if( stream == 0 )
  333. {
  334. mCurrentVB_Divisor[stream] = 0; // non instanced, is vertex buffer
  335. mDrawInstancesCount = frequency; // instances count
  336. }
  337. else
  338. {
  339. AssertFatal(frequency <= 1, "GFXGLDevice::setVertexStreamFrequency only support 0/1 for this stream" );
  340. if( stream == 1 && frequency == 1 )
  341. mCurrentVB_Divisor[stream] = 1; // instances data need a frequency of 1
  342. else
  343. mCurrentVB_Divisor[stream] = 0;
  344. }
  345. mNeedUpdateVertexAttrib = true;
  346. }
  347. GFXCubemap* GFXGLDevice::createCubemap()
  348. {
  349. GFXGLCubemap* cube = new GFXGLCubemap();
  350. cube->registerResourceWithDevice(this);
  351. return cube;
  352. };
  353. void GFXGLDevice::endSceneInternal()
  354. {
  355. // nothing to do for opengl
  356. mCanCurrentlyRender = false;
  357. }
  358. void GFXGLDevice::clear(U32 flags, ColorI color, F32 z, U32 stencil)
  359. {
  360. // Make sure we have flushed our render target state.
  361. _updateRenderTargets();
  362. bool writeAllColors = true;
  363. bool zwrite = true;
  364. bool writeAllStencil = true;
  365. const GFXStateBlockDesc *desc = NULL;
  366. if (mCurrentGLStateBlock)
  367. {
  368. desc = &mCurrentGLStateBlock->getDesc();
  369. zwrite = desc->zWriteEnable;
  370. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  371. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  372. }
  373. glColorMask(true, true, true, true);
  374. glDepthMask(true);
  375. glStencilMask(0xFFFFFFFF);
  376. ColorF c = color;
  377. glClearColor(c.red, c.green, c.blue, c.alpha);
  378. glClearDepth(z);
  379. glClearStencil(stencil);
  380. GLbitfield clearflags = 0;
  381. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  382. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  383. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  384. glClear(clearflags);
  385. if(!writeAllColors)
  386. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  387. if(!zwrite)
  388. glDepthMask(false);
  389. if(!writeAllStencil)
  390. glStencilMask(desc->stencilWriteMask);
  391. }
  392. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  393. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  394. {
  395. switch (primType)
  396. {
  397. case GFXPointList :
  398. return primitiveCount;
  399. break;
  400. case GFXLineList :
  401. return primitiveCount * 2;
  402. break;
  403. case GFXLineStrip :
  404. return primitiveCount + 1;
  405. break;
  406. case GFXTriangleList :
  407. return primitiveCount * 3;
  408. break;
  409. case GFXTriangleStrip :
  410. return 2 + primitiveCount;
  411. break;
  412. case GFXTriangleFan :
  413. return 2 + primitiveCount;
  414. break;
  415. default:
  416. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  417. break;
  418. }
  419. return 0;
  420. }
  421. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  422. {
  423. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  424. static GFXGLVertexDeclMap declMap;
  425. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  426. if(itr != declMap.end())
  427. return &itr->value;
  428. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  429. decl.init(vertexFormat);
  430. return &decl;
  431. }
  432. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  433. {
  434. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  435. }
  436. inline void GFXGLDevice::preDrawPrimitive()
  437. {
  438. if( mStateDirty )
  439. {
  440. updateStates();
  441. }
  442. if(mCurrentShaderConstBuffer)
  443. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  444. if( mNeedUpdateVertexAttrib )
  445. {
  446. AssertFatal(mCurrVertexDecl, "");
  447. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  448. for(int i = 0; i < getNumVertexStreams(); ++i)
  449. {
  450. if(mCurrentVB[i])
  451. {
  452. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  453. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  454. }
  455. }
  456. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  457. }
  458. mNeedUpdateVertexAttrib = false;
  459. }
  460. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  461. {
  462. mDeviceStatistics.mDrawCalls++;
  463. mDeviceStatistics.mPolyCount += primitiveCount;
  464. }
  465. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  466. {
  467. preDrawPrimitive();
  468. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  469. if(mDrawInstancesCount)
  470. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  471. else
  472. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  473. postDrawPrimitive(primitiveCount);
  474. }
  475. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  476. U32 startVertex,
  477. U32 minIndex,
  478. U32 numVerts,
  479. U32 startIndex,
  480. U32 primitiveCount )
  481. {
  482. AssertFatal( startVertex == 0, "GFXGLDevice::drawIndexedPrimitive() - Non-zero startVertex unsupported!" );
  483. preDrawPrimitive();
  484. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex;
  485. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset;
  486. if(mDrawInstancesCount)
  487. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  488. else
  489. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  490. postDrawPrimitive(primitiveCount);
  491. }
  492. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  493. {
  494. if(mCurrentPB)
  495. mCurrentPB->finish();
  496. mCurrentPB = pb;
  497. }
  498. void GFXGLDevice::setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable)
  499. {
  500. // ONLY NEEDED ON FFP
  501. }
  502. void GFXGLDevice::setLightMaterialInternal(const GFXLightMaterial mat)
  503. {
  504. // ONLY NEEDED ON FFP
  505. }
  506. void GFXGLDevice::setGlobalAmbientInternal(ColorF color)
  507. {
  508. glLightModelfv(GL_LIGHT_MODEL_AMBIENT, (GLfloat*)&color);
  509. }
  510. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  511. {
  512. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  513. if (tex)
  514. {
  515. mActiveTextureType[textureUnit] = tex->getBinding();
  516. tex->bind(textureUnit);
  517. }
  518. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  519. {
  520. glActiveTexture(GL_TEXTURE0 + textureUnit);
  521. glBindTexture(mActiveTextureType[textureUnit], 0);
  522. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  523. mActiveTextureType[textureUnit] = GL_ZERO;
  524. }
  525. }
  526. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  527. {
  528. if(texture)
  529. {
  530. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  531. texture->bind(textureUnit);
  532. }
  533. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  534. {
  535. glActiveTexture(GL_TEXTURE0 + textureUnit);
  536. glBindTexture(mActiveTextureType[textureUnit], 0);
  537. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  538. mActiveTextureType[textureUnit] = GL_ZERO;
  539. }
  540. }
  541. void GFXGLDevice::setMatrix( GFXMatrixType mtype, const MatrixF &mat )
  542. {
  543. // ONLY NEEDED ON FFP
  544. }
  545. void GFXGLDevice::setClipRect( const RectI &inRect )
  546. {
  547. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  548. // Clip the rect against the renderable size.
  549. Point2I size = mCurrentRT->getSize();
  550. RectI maxRect(Point2I(0,0), size);
  551. mClip = inRect;
  552. mClip.intersect(maxRect);
  553. // Create projection matrix. See http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html
  554. const F32 left = mClip.point.x;
  555. const F32 right = mClip.point.x + mClip.extent.x;
  556. const F32 bottom = mClip.extent.y;
  557. const F32 top = 0.0f;
  558. const F32 near = 0.0f;
  559. const F32 far = 1.0f;
  560. const F32 tx = -(right + left)/(right - left);
  561. const F32 ty = -(top + bottom)/(top - bottom);
  562. const F32 tz = -(far + near)/(far - near);
  563. static Point4F pt;
  564. pt.set(2.0f / (right - left), 0.0f, 0.0f, 0.0f);
  565. mProjectionMatrix.setColumn(0, pt);
  566. pt.set(0.0f, 2.0f/(top - bottom), 0.0f, 0.0f);
  567. mProjectionMatrix.setColumn(1, pt);
  568. pt.set(0.0f, 0.0f, -2.0f/(far - near), 0.0f);
  569. mProjectionMatrix.setColumn(2, pt);
  570. pt.set(tx, ty, tz, 1.0f);
  571. mProjectionMatrix.setColumn(3, pt);
  572. // Translate projection matrix.
  573. static MatrixF translate(true);
  574. pt.set(0.0f, -mClip.point.y, 0.0f, 1.0f);
  575. translate.setColumn(3, pt);
  576. mProjectionMatrix *= translate;
  577. setMatrix(GFXMatrixProjection, mProjectionMatrix);
  578. MatrixF mTempMatrix(true);
  579. setViewMatrix( mTempMatrix );
  580. setWorldMatrix( mTempMatrix );
  581. // Set the viewport to the clip rect
  582. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  583. setViewport(viewport);
  584. }
  585. /// Creates a state block object based on the desc passed in. This object
  586. /// represents an immutable state.
  587. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  588. {
  589. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  590. }
  591. /// Activates a stateblock
  592. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  593. {
  594. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  595. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  596. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  597. if (force)
  598. glCurrent = NULL;
  599. glBlock->activate(glCurrent); // Doesn't use current yet.
  600. mCurrentGLStateBlock = glBlock;
  601. }
  602. //------------------------------------------------------------------------------
  603. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget()
  604. {
  605. GFXGLTextureTarget *targ = new GFXGLTextureTarget();
  606. targ->registerResourceWithDevice(this);
  607. return targ;
  608. }
  609. GFXFence * GFXGLDevice::createFence()
  610. {
  611. GFXFence* fence = _createPlatformSpecificFence();
  612. if(!fence)
  613. fence = new GFXGeneralFence( this );
  614. fence->registerResourceWithDevice(this);
  615. return fence;
  616. }
  617. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  618. {
  619. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  620. query->registerResourceWithDevice(this);
  621. return query;
  622. }
  623. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  624. {
  625. AssertFatal(type != GSTargetRestore, "");
  626. if( mGenericShader[GSColor] == NULL )
  627. {
  628. ShaderData *shaderData;
  629. shaderData = new ShaderData();
  630. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/colorV.glsl");
  631. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/colorP.glsl");
  632. shaderData->setField("pixVersion", "2.0");
  633. shaderData->registerObject();
  634. mGenericShader[GSColor] = shaderData->getShader();
  635. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  636. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  637. shaderData = new ShaderData();
  638. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/modColorTextureV.glsl");
  639. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/modColorTextureP.glsl");
  640. shaderData->setSamplerName("$diffuseMap", 0);
  641. shaderData->setField("pixVersion", "2.0");
  642. shaderData->registerObject();
  643. mGenericShader[GSModColorTexture] = shaderData->getShader();
  644. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  645. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  646. shaderData = new ShaderData();
  647. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/addColorTextureV.glsl");
  648. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/addColorTextureP.glsl");
  649. shaderData->setSamplerName("$diffuseMap", 0);
  650. shaderData->setField("pixVersion", "2.0");
  651. shaderData->registerObject();
  652. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  653. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  654. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  655. shaderData = new ShaderData();
  656. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/textureV.glsl");
  657. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/textureP.glsl");
  658. shaderData->setSamplerName("$diffuseMap", 0);
  659. shaderData->setField("pixVersion", "2.0");
  660. shaderData->registerObject();
  661. mGenericShader[GSTexture] = shaderData->getShader();
  662. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  663. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  664. }
  665. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  666. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  667. setShader( mGenericShader[type] );
  668. setShaderConstBuffer( mGenericShaderBuffer[type] );
  669. }
  670. GFXShader* GFXGLDevice::createShader()
  671. {
  672. GFXGLShader* shader = new GFXGLShader();
  673. shader->registerResourceWithDevice( this );
  674. return shader;
  675. }
  676. void GFXGLDevice::setShader( GFXShader *shader )
  677. {
  678. if(mCurrentShader == shader)
  679. return;
  680. if ( shader )
  681. {
  682. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  683. glShader->useProgram();
  684. mCurrentShader = shader;
  685. }
  686. else
  687. {
  688. setupGenericShaders();
  689. }
  690. }
  691. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  692. {
  693. static_cast<GFXGLShaderConstBuffer*>(buffer)->activate();
  694. }
  695. U32 GFXGLDevice::getNumSamplers() const
  696. {
  697. return getMin((U32)TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  698. }
  699. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  700. {
  701. if(mWindowRT && mWindowRT->getPointer())
  702. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  703. return NULL;
  704. }
  705. U32 GFXGLDevice::getNumRenderTargets() const
  706. {
  707. return mMaxTRColors;
  708. }
  709. void GFXGLDevice::_updateRenderTargets()
  710. {
  711. if ( mRTDirty || mCurrentRT->isPendingState() )
  712. {
  713. if ( mRTDeactivate )
  714. {
  715. mRTDeactivate->deactivate();
  716. mRTDeactivate = NULL;
  717. }
  718. // NOTE: The render target changes is not really accurate
  719. // as the GFXTextureTarget supports MRT internally. So when
  720. // we activate a GFXTarget it could result in multiple calls
  721. // to SetRenderTarget on the actual device.
  722. mDeviceStatistics.mRenderTargetChanges++;
  723. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  724. if ( tex )
  725. {
  726. tex->applyState();
  727. tex->makeActive();
  728. }
  729. else
  730. {
  731. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  732. AssertFatal( win != NULL,
  733. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  734. win->makeActive();
  735. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  736. {
  737. mRTDirty = false;
  738. GFX->updateStates(true);
  739. }
  740. }
  741. mRTDirty = false;
  742. }
  743. if ( mViewportDirty )
  744. {
  745. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  746. mViewportDirty = false;
  747. }
  748. }
  749. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  750. const Vector<GFXFormat>& formats,
  751. bool texture,
  752. bool mustblend,
  753. bool mustfilter )
  754. {
  755. for(U32 i = 0; i < formats.size(); i++)
  756. {
  757. // Single channel textures are not supported by FBOs.
  758. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  759. continue;
  760. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  761. continue;
  762. return formats[i];
  763. }
  764. return GFXFormatR8G8B8A8;
  765. }
  766. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  767. {
  768. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  769. if( gglHasExtension(ATI_meminfo) )
  770. {
  771. GLint mem[4] = {0};
  772. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  773. /* With mem[0] i get only the total memory free in the pool in KB
  774. *
  775. * mem[0] - total memory free in the pool
  776. * mem[1] - largest available free block in the pool
  777. * mem[2] - total auxiliary memory free
  778. * mem[3] - largest auxiliary free block
  779. */
  780. return mem[0] / 1024;
  781. }
  782. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  783. else if( gglHasExtension(NVX_gpu_memory_info) )
  784. {
  785. GLint mem = 0;
  786. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  787. return mem / 1024;
  788. }
  789. // TODO OPENGL, add supprt for INTEL cards.
  790. return 0;
  791. }
  792. //
  793. // Register this device with GFXInit
  794. //
  795. class GFXGLRegisterDevice
  796. {
  797. public:
  798. GFXGLRegisterDevice()
  799. {
  800. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  801. }
  802. };
  803. static GFXGLRegisterDevice pGLRegisterDevice;
  804. ConsoleFunction(cycleResources, void, 1, 1, "")
  805. {
  806. static_cast<GFXGLDevice*>(GFX)->zombify();
  807. static_cast<GFXGLDevice*>(GFX)->resurrect();
  808. }