2
0

gfxGLDevice.cpp 33 KB

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