gfxGLDevice.cpp 32 KB

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