gfxGLDevice.cpp 31 KB

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