gfxGLDevice.cpp 31 KB

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