CmGLRenderSystem.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in*
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.s
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmGLRenderSystem.h"
  25. #include "CmRenderSystem.h"
  26. #include "CmCamera.h"
  27. #include "CmGLTextureManager.h"
  28. #include "CmGLVertexBuffer.h"
  29. #include "CmGLIndexBuffer.h"
  30. #include "CmGLUtil.h"
  31. #include "CmGLSLGpuProgram.h"
  32. #include "CmGLSLProgram.h"
  33. #include "CmGLGpuProgramManager.h"
  34. #include "CmException.h"
  35. #include "CmGLSLExtSupport.h"
  36. #include "CmGLOcclusionQuery.h"
  37. #include "CmGLContext.h"
  38. #include "CmAsyncOp.h"
  39. #include "CmBlendState.h"
  40. #include "CmRasterizerState.h"
  41. #include "CmDepthStencilState.h"
  42. #include "CmGLRenderTexture.h"
  43. #include "CmGLRenderWindowManager.h"
  44. #include "CmGLBuiltinMaterialManager.h"
  45. #include "CmGLSLProgramPipelineManager.h"
  46. #include "CmRenderStateManager.h"
  47. #include "CmGpuParams.h"
  48. #include "CmGLGpuParamBlock.h"
  49. #include "CmDebug.h"
  50. #if CM_DEBUG_MODE
  51. #define THROW_IF_NOT_RENDER_THREAD throwIfNotRenderThread();
  52. #else
  53. #define THROW_IF_NOT_RENDER_THREAD
  54. #endif
  55. // Convenience macro from ARB_vertex_buffer_object spec
  56. #define VBO_BUFFER_OFFSET(i) ((char *)NULL + (i))
  57. #if CM_THREAD_SUPPORT != 1
  58. GLenum glewContextInit (CamelotEngine::GLSupport *glSupport);
  59. #endif
  60. namespace CamelotEngine
  61. {
  62. /************************************************************************/
  63. /* PUBLIC INTERFACE */
  64. /************************************************************************/
  65. GLRenderSystem::GLRenderSystem()
  66. : mDepthWrite(true),
  67. mGLSLProgramFactory(nullptr),
  68. mCgProgramFactory(nullptr),
  69. mProgramPipelineManager(nullptr),
  70. mActivePipeline(nullptr),
  71. mActiveTextureUnit(0),
  72. mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280),
  73. mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0),
  74. mStencilReadMask(0xFFFFFFFF),
  75. mStencilWriteMask(0xFFFFFFFF),
  76. mStencilCompareFront(CMPF_ALWAYS_PASS),
  77. mStencilCompareBack(CMPF_ALWAYS_PASS),
  78. mStencilRefValue(0),
  79. mFragmentTexOffset(0),
  80. mVertexTexOffset(0),
  81. mGeometryTexOffset(0),
  82. mTextureTypes(nullptr),
  83. mNumTextureTypes(0),
  84. mFragmentUBOffset(0),
  85. mVertexUBOffset(0),
  86. mGeometryUBOffset(0),
  87. mHullUBOffset(0),
  88. mDomainUBOffset(0),
  89. mComputeUBOffset(0),
  90. mDrawCallInProgress(false),
  91. mCurrentDrawOperation(DOT_TRIANGLE_LIST)
  92. {
  93. // Get our GLSupport
  94. mGLSupport = CamelotEngine::getGLSupport();
  95. mViewMatrix = Matrix4::IDENTITY;
  96. mColourWrite[0] = mColourWrite[1] = mColourWrite[2] = mColourWrite[3] = true;
  97. mCurrentContext = 0;
  98. mMainContext = 0;
  99. mGLInitialised = false;
  100. mMinFilter = FO_LINEAR;
  101. mMipFilter = FO_POINT;
  102. mProgramPipelineManager = CM_NEW(GLSLProgramPipelineManager, GenAlloc) GLSLProgramPipelineManager();
  103. }
  104. GLRenderSystem::~GLRenderSystem()
  105. {
  106. // This needs to be called from the child class, since destroy_internal is virtual
  107. queueCommand(boost::bind(&GLRenderSystem::destroy_internal, this), true);
  108. }
  109. const String& GLRenderSystem::getName(void) const
  110. {
  111. static String strName("GLRenderSystem");
  112. return strName;
  113. }
  114. const String& GLRenderSystem::getShadingLanguageName() const
  115. {
  116. static String strName("glsl");
  117. return strName;
  118. }
  119. void GLRenderSystem::initialize_internal()
  120. {
  121. THROW_IF_NOT_RENDER_THREAD;
  122. mGLSupport->start();
  123. RenderWindowManager::startUp(CM_NEW(GLRenderWindowManager, GenAlloc) GLRenderWindowManager(this));
  124. RenderStateManager::startUp(CM_NEW(RenderStateManager, GenAlloc) RenderStateManager());
  125. BuiltinMaterialManager::startUp(CM_NEW(GLBuiltinMaterialManager, GenAlloc) GLBuiltinMaterialManager());
  126. RenderSystem::initialize_internal();
  127. }
  128. void GLRenderSystem::destroy_internal()
  129. {
  130. RenderSystem::destroy_internal();
  131. // Deleting the GLSL program factory
  132. if (mGLSLProgramFactory)
  133. {
  134. // Remove from manager safely
  135. HighLevelGpuProgramManager::instance().removeFactory(mGLSLProgramFactory);
  136. CM_DELETE(mGLSLProgramFactory, GLSLProgramFactory, GenAlloc);
  137. mGLSLProgramFactory = nullptr;
  138. }
  139. // Deleting Cg GLSL program factory
  140. if (mCgProgramFactory)
  141. {
  142. // Remove from manager safely
  143. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  144. CM_DELETE(mCgProgramFactory, CgProgramFactory, GenAlloc);
  145. mCgProgramFactory = nullptr;
  146. }
  147. // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop().
  148. GpuProgramManager::shutDown();
  149. HardwareBufferManager::shutDown();
  150. GLRTTManager::shutDown();
  151. mBoundVertexBuffers.clear();
  152. mBoundVertexDeclaration = nullptr;
  153. mBoundIndexBuffer = nullptr;
  154. mCurrentVertexProgram = nullptr;
  155. mCurrentFragmentProgram = nullptr;
  156. mCurrentGeometryProgram = nullptr;
  157. mCurrentHullProgram = nullptr;
  158. mCurrentDomainProgram = nullptr;
  159. mGLSupport->stop();
  160. TextureManager::shutDown();
  161. BuiltinMaterialManager::shutDown();
  162. RenderWindowManager::shutDown();
  163. RenderStateManager::shutDown();
  164. // There will be a new initial window and so forth, thus any call to test
  165. // some params will access an invalid pointer, so it is best to reset
  166. // the whole state.
  167. mGLInitialised = 0;
  168. if(mProgramPipelineManager != nullptr)
  169. CM_DELETE(mProgramPipelineManager, GLSLProgramPipelineManager, GenAlloc);
  170. if(mGLSupport)
  171. CM_DELETE(mGLSupport, GLSupport, GenAlloc);
  172. if(mTextureTypes != nullptr)
  173. CM_DELETE_ARRAY(mTextureTypes, GLenum, mNumTextureTypes, GenAlloc);
  174. }
  175. //---------------------------------------------------------------------
  176. void GLRenderSystem::bindGpuProgram(HGpuProgram prg)
  177. {
  178. THROW_IF_NOT_RENDER_THREAD;
  179. GpuProgramPtr bindingPrg = prg->getBindingDelegate();
  180. GLSLGpuProgramPtr glprg = std::static_pointer_cast<GLSLGpuProgram>(bindingPrg);
  181. switch (glprg->getType())
  182. {
  183. case GPT_VERTEX_PROGRAM:
  184. if (mCurrentVertexProgram != glprg)
  185. {
  186. unbindGpuProgram(glprg->getType());
  187. mCurrentVertexProgram = glprg;
  188. }
  189. break;
  190. case GPT_FRAGMENT_PROGRAM:
  191. if (mCurrentFragmentProgram != glprg)
  192. {
  193. unbindGpuProgram(glprg->getType());
  194. mCurrentFragmentProgram = glprg;
  195. }
  196. break;
  197. case GPT_GEOMETRY_PROGRAM:
  198. if (mCurrentGeometryProgram != glprg)
  199. {
  200. unbindGpuProgram(glprg->getType());
  201. mCurrentGeometryProgram = glprg;
  202. }
  203. break;
  204. case GPT_DOMAIN_PROGRAM:
  205. if (mCurrentDomainProgram != glprg)
  206. {
  207. unbindGpuProgram(glprg->getType());
  208. mCurrentDomainProgram = glprg;
  209. }
  210. break;
  211. case GPT_HULL_PROGRAM:
  212. if (mCurrentHullProgram != glprg)
  213. {
  214. unbindGpuProgram(glprg->getType());
  215. mCurrentHullProgram = glprg;
  216. }
  217. break;
  218. }
  219. RenderSystem::bindGpuProgram(prg);
  220. }
  221. //---------------------------------------------------------------------
  222. void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype)
  223. {
  224. THROW_IF_NOT_RENDER_THREAD;
  225. setActiveProgram(gptype, nullptr);
  226. RenderSystem::unbindGpuProgram(gptype);
  227. }
  228. //-----------------------------------------------------------------------------
  229. void GLRenderSystem::bindGpuParams(GpuProgramType gptype, GpuParamsPtr params)
  230. {
  231. THROW_IF_NOT_RENDER_THREAD;
  232. const GpuParamDesc& paramDesc = params->getParamDesc();
  233. GLSLGpuProgramPtr activeProgram = getActiveProgram(gptype);
  234. GLuint glProgram = activeProgram->getGLSLProgram()->getGLHandle();
  235. for(auto iter = paramDesc.textures.begin(); iter != paramDesc.textures.end(); ++iter)
  236. {
  237. HTexture texture = params->getTexture(iter->second.slot);
  238. if(!texture.isLoaded())
  239. setTexture(gptype, iter->second.slot, false, nullptr);
  240. else
  241. setTexture(gptype, iter->second.slot, true, texture.getInternalPtr());
  242. }
  243. UINT32 texUnit = 0;
  244. for(auto iter = paramDesc.samplers.begin(); iter != paramDesc.samplers.end(); ++iter)
  245. {
  246. HSamplerState& samplerState = params->getSamplerState(iter->second.slot);
  247. if(samplerState == nullptr)
  248. setSamplerState(gptype, iter->second.slot, SamplerState::getDefault());
  249. else
  250. setSamplerState(gptype, iter->second.slot, samplerState.getInternalPtr());
  251. glProgramUniform1i(glProgram, iter->second.slot, getGLTextureUnit(gptype, texUnit));
  252. texUnit++;
  253. }
  254. UINT32 blockBinding = 0;
  255. for(auto iter = paramDesc.paramBlocks.begin(); iter != paramDesc.paramBlocks.end(); ++iter)
  256. {
  257. if(iter->second.slot == 0)
  258. continue;
  259. GpuParamBlockPtr paramBlock = params->getParamBlock(iter->second.slot);
  260. if(paramBlock == nullptr)
  261. continue;
  262. GLGpuParamBlockPtr glParamBlock = std::static_pointer_cast<GLGpuParamBlock>(paramBlock);
  263. const GpuParamBlockBuffer* paramBlockBuffer = glParamBlock->getBindableBuffer();
  264. const GLGpuParamBlockBuffer* glParamBlockBuffer = static_cast<const GLGpuParamBlockBuffer*>(paramBlockBuffer);
  265. UINT32 globalBlockBinding = getGLUniformBlockBinding(gptype, blockBinding);
  266. glUniformBlockBinding(glProgram, iter->second.slot - 1, globalBlockBinding);
  267. glBindBufferRange(GL_UNIFORM_BUFFER, globalBlockBinding, glParamBlockBuffer->getGLHandle(), 0, glParamBlockBuffer->getSize());
  268. blockBinding++;
  269. }
  270. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  271. {
  272. const GpuParamDataDesc& paramDesc = iter->second;
  273. GpuParamBlockPtr paramBlock = params->getParamBlock(paramDesc.paramBlockSlot);
  274. const GpuParamBlockBuffer* paramBlockBuffer = paramBlock->getBindableBuffer();
  275. if(paramDesc.paramBlockSlot != 0) // 0 means uniforms are not in a block
  276. continue;
  277. const UINT8* ptrData = paramBlockBuffer->getDataPtr(paramDesc.cpuMemOffset * sizeof(UINT32));
  278. switch(paramDesc.type)
  279. {
  280. case GCT_FLOAT1:
  281. glProgramUniform1fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  282. break;
  283. case GCT_FLOAT2:
  284. glProgramUniform2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  285. break;
  286. case GCT_FLOAT3:
  287. glProgramUniform3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  288. break;
  289. case GCT_FLOAT4:
  290. glProgramUniform4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  291. break;
  292. case GCT_MATRIX_2X2:
  293. glProgramUniformMatrix2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  294. GL_FALSE, (GLfloat*)ptrData);
  295. break;
  296. case GCT_MATRIX_2X3:
  297. glProgramUniformMatrix2x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  298. GL_FALSE, (GLfloat*)ptrData);
  299. break;
  300. case GCT_MATRIX_2X4:
  301. glProgramUniformMatrix2x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  302. GL_FALSE, (GLfloat*)ptrData);
  303. break;
  304. case GCT_MATRIX_3X2:
  305. glProgramUniformMatrix3x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  306. GL_FALSE, (GLfloat*)ptrData);
  307. break;
  308. case GCT_MATRIX_3X3:
  309. glProgramUniformMatrix3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  310. GL_FALSE, (GLfloat*)ptrData);
  311. break;
  312. case GCT_MATRIX_3X4:
  313. glProgramUniformMatrix3x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  314. GL_FALSE, (GLfloat*)ptrData);
  315. break;
  316. case GCT_MATRIX_4X2:
  317. glProgramUniformMatrix4x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  318. GL_FALSE, (GLfloat*)ptrData);
  319. break;
  320. case GCT_MATRIX_4X3:
  321. glProgramUniformMatrix4x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  322. GL_FALSE, (GLfloat*)ptrData);
  323. break;
  324. case GCT_MATRIX_4X4:
  325. glProgramUniformMatrix4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  326. GL_FALSE, (GLfloat*)ptrData);
  327. break;
  328. case GCT_INT1:
  329. glProgramUniform1iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  330. break;
  331. case GCT_INT2:
  332. glProgramUniform2iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  333. break;
  334. case GCT_INT3:
  335. glProgramUniform3iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  336. break;
  337. case GCT_INT4:
  338. glProgramUniform4iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  339. break;
  340. case GPDT_BOOL:
  341. glProgramUniform1uiv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLuint*)ptrData);
  342. break;
  343. case GCT_UNKNOWN:
  344. break;
  345. }
  346. }
  347. }
  348. //-----------------------------------------------------------------------------
  349. void GLRenderSystem::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr &texPtr)
  350. {
  351. THROW_IF_NOT_RENDER_THREAD;
  352. unit = getGLTextureUnit(gptype, unit);
  353. GLTexturePtr tex = std::static_pointer_cast<GLTexture>(texPtr);
  354. GLenum lastTextureType = mTextureTypes[unit];
  355. if (!activateGLTextureUnit(unit))
  356. return;
  357. if (enabled && tex)
  358. {
  359. mTextureTypes[unit] = tex->getGLTextureTarget();
  360. glBindTexture(mTextureTypes[unit], tex->getGLID());
  361. }
  362. else
  363. {
  364. // TODO - This doesn't actually disable all textures set on this image unit, only the 2D ones
  365. // - If a non-2D sampler is used, the texture will still be displayed
  366. // bind zero texture
  367. glBindTexture(GL_TEXTURE_2D, 0);
  368. }
  369. activateGLTextureUnit(0);
  370. }
  371. //-----------------------------------------------------------------------
  372. void GLRenderSystem::setSamplerState(GpuProgramType gptype, UINT16 unit, const SamplerStatePtr& state)
  373. {
  374. THROW_IF_NOT_RENDER_THREAD;
  375. unit = getGLTextureUnit(gptype, unit);
  376. // Set texture layer filtering
  377. setTextureFiltering(unit, FT_MIN, state->getTextureFiltering(FT_MIN));
  378. setTextureFiltering(unit, FT_MAG, state->getTextureFiltering(FT_MAG));
  379. setTextureFiltering(unit, FT_MIP, state->getTextureFiltering(FT_MIP));
  380. // Set texture anisotropy
  381. setTextureAnisotropy(unit, state->getTextureAnisotropy());
  382. // Set mipmap biasing
  383. setTextureMipmapBias(unit, state->getTextureMipmapBias());
  384. // Texture addressing mode
  385. const UVWAddressingMode& uvw = state->getTextureAddressingMode();
  386. setTextureAddressingMode(unit, uvw);
  387. // Set border color
  388. setTextureBorderColor(unit, state->getBorderColor());
  389. }
  390. //-----------------------------------------------------------------------------
  391. void GLRenderSystem::setBlendState(const BlendStatePtr& blendState)
  392. {
  393. THROW_IF_NOT_RENDER_THREAD;
  394. // Alpha to coverage
  395. setAlphaToCoverage(blendState->getAlphaToCoverageEnabled());
  396. // Blend states
  397. // DirectX 9 doesn't allow us to specify blend state per render target, so we just use the first one.
  398. if(blendState->getBlendEnabled(0))
  399. {
  400. setSceneBlending(blendState->getSrcBlend(0), blendState->getDstBlend(0), blendState->getAlphaSrcBlend(0), blendState->getAlphaDstBlend(0)
  401. , blendState->getBlendOperation(0), blendState->getAlphaBlendOperation(0));
  402. }
  403. else
  404. {
  405. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  406. }
  407. // Color write mask
  408. UINT8 writeMask = blendState->getRenderTargetWriteMask(0);
  409. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  410. }
  411. //----------------------------------------------------------------------
  412. void GLRenderSystem::setRasterizerState(const RasterizerStatePtr& rasterizerState)
  413. {
  414. THROW_IF_NOT_RENDER_THREAD;
  415. setDepthBias((float)rasterizerState->getDepthBias(), rasterizerState->getSlopeScaledDepthBias());
  416. setCullingMode(rasterizerState->getCullMode());
  417. setPolygonMode(rasterizerState->getPolygonMode());
  418. setScissorTestEnable(rasterizerState->getScissorEnable());
  419. }
  420. //---------------------------------------------------------------------
  421. void GLRenderSystem::setDepthStencilState(const DepthStencilStatePtr& depthStencilState, UINT32 stencilRefValue)
  422. {
  423. THROW_IF_NOT_RENDER_THREAD;
  424. // Set stencil buffer options
  425. setStencilCheckEnabled(depthStencilState->getStencilEnable());
  426. setStencilBufferOperations(depthStencilState->getStencilFrontFailOp(), depthStencilState->getStencilFrontZFailOp(), depthStencilState->getStencilFrontPassOp(), true);
  427. setStencilBufferFunc(depthStencilState->getStencilFrontCompFunc(), depthStencilState->getStencilReadMask(), true);
  428. setStencilBufferOperations(depthStencilState->getStencilBackFailOp(), depthStencilState->getStencilBackZFailOp(), depthStencilState->getStencilBackPassOp(), false);
  429. setStencilBufferFunc(depthStencilState->getStencilBackCompFunc(), depthStencilState->getStencilReadMask(), false);
  430. setStencilBufferWriteMask(depthStencilState->getStencilWriteMask());
  431. // Set depth buffer options
  432. setDepthBufferCheckEnabled(depthStencilState->getDepthReadEnable());
  433. setDepthBufferWriteEnabled(depthStencilState->getDepthWriteEnable());
  434. setDepthBufferFunction(depthStencilState->getDepthComparisonFunc());
  435. // Set stencil ref value
  436. setStencilRefValue(stencilRefValue);
  437. }
  438. //-----------------------------------------------------------------------------
  439. void GLRenderSystem::setViewport(ViewportPtr& vp)
  440. {
  441. THROW_IF_NOT_RENDER_THREAD;
  442. assert(vp != nullptr);
  443. RenderTargetPtr target;
  444. target = vp->getTarget();
  445. setRenderTarget(target);
  446. // Calculate the "lower-left" corner of the viewport
  447. mViewportWidth = vp->getWidth();
  448. mViewportHeight = vp->getHeight();
  449. mViewportLeft = vp->getLeft();
  450. mViewportTop = vp->getTop();
  451. if (!target->requiresTextureFlipping())
  452. {
  453. // Convert "upper-left" corner to "lower-left"
  454. mViewportTop = target->getHeight() - mViewportHeight - mViewportTop;
  455. }
  456. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  457. // Configure the viewport clipping
  458. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  459. }
  460. //---------------------------------------------------------------------
  461. void GLRenderSystem::setRenderTarget(RenderTargetPtr target)
  462. {
  463. THROW_IF_NOT_RENDER_THREAD;
  464. mActiveRenderTarget = target;
  465. // Switch context if different from current one
  466. GLContext *newContext = 0;
  467. target->getCustomAttribute("GLCONTEXT", &newContext);
  468. if(newContext && mCurrentContext != newContext)
  469. {
  470. switchContext(newContext);
  471. }
  472. GLFrameBufferObject *fbo = 0;
  473. target->getCustomAttribute("FBO", &fbo);
  474. if(fbo)
  475. fbo->bind();
  476. else
  477. // Old style context (window/pbuffer) or copying render texture
  478. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  479. if (GLEW_EXT_framebuffer_sRGB)
  480. {
  481. // Enable / disable sRGB states
  482. if (target->isHardwareGammaEnabled())
  483. {
  484. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  485. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  486. // enabling, but GL spec says incapable surfaces ignore the setting
  487. // anyway. We test the capability to enable isHardwareGammaEnabled.
  488. }
  489. else
  490. {
  491. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  492. }
  493. }
  494. }
  495. //-----------------------------------------------------------------------------
  496. void GLRenderSystem::beginFrame(void)
  497. {
  498. THROW_IF_NOT_RENDER_THREAD;
  499. // Activate the viewport clipping
  500. glEnable(GL_SCISSOR_TEST);
  501. }
  502. //-----------------------------------------------------------------------------
  503. void GLRenderSystem::endFrame(void)
  504. {
  505. THROW_IF_NOT_RENDER_THREAD;
  506. // Deactivate the viewport clipping.
  507. glDisable(GL_SCISSOR_TEST);
  508. // unbind GPU programs at end of frame
  509. // this is mostly to avoid holding bound programs that might get deleted
  510. // outside via the resource manager
  511. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  512. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  513. }
  514. //---------------------------------------------------------------------
  515. void GLRenderSystem::setVertexBuffer(UINT32 index, const VertexBufferPtr& buffer)
  516. {
  517. THROW_IF_NOT_RENDER_THREAD;
  518. mBoundVertexBuffers[index] = buffer;
  519. }
  520. //---------------------------------------------------------------------
  521. void GLRenderSystem::setVertexDeclaration(VertexDeclarationPtr vertexDeclaration)
  522. {
  523. THROW_IF_NOT_RENDER_THREAD;
  524. mBoundVertexDeclaration = vertexDeclaration;
  525. }
  526. //---------------------------------------------------------------------
  527. void GLRenderSystem::setDrawOperation(DrawOperationType op)
  528. {
  529. THROW_IF_NOT_RENDER_THREAD;
  530. mCurrentDrawOperation = op;
  531. }
  532. //---------------------------------------------------------------------
  533. void GLRenderSystem::setIndexBuffer(const IndexBufferPtr& buffer)
  534. {
  535. THROW_IF_NOT_RENDER_THREAD;
  536. mBoundIndexBuffer = buffer;
  537. }
  538. //---------------------------------------------------------------------
  539. void GLRenderSystem::draw(UINT32 vertexCount)
  540. {
  541. // Find the correct type to render
  542. GLint primType = getGLDrawMode();
  543. beginDraw();
  544. glDrawArrays(primType, 0, vertexCount);
  545. endDraw();
  546. }
  547. //---------------------------------------------------------------------
  548. void GLRenderSystem::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexCount)
  549. {
  550. if(mBoundIndexBuffer == nullptr)
  551. {
  552. LOGWRN("Cannot draw indexed because index buffer is not set.");
  553. return;
  554. }
  555. // Find the correct type to render
  556. GLint primType = getGLDrawMode();
  557. beginDraw();
  558. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,
  559. static_cast<GLIndexBuffer*>(mBoundIndexBuffer.get())->getGLBufferId());
  560. void* pBufferData = VBO_BUFFER_OFFSET(startIndex * mBoundIndexBuffer->getIndexSize());
  561. GLenum indexType = (mBoundIndexBuffer->getType() == IndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  562. glDrawElements(primType, indexCount, indexType, 0);
  563. endDraw();
  564. }
  565. //---------------------------------------------------------------------
  566. void GLRenderSystem::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  567. {
  568. THROW_IF_NOT_RENDER_THREAD;
  569. mScissorTop = top;
  570. mScissorBottom = bottom;
  571. mScissorLeft = left;
  572. mScissorRight = right;
  573. }
  574. //---------------------------------------------------------------------
  575. void GLRenderSystem::clear(RenderTargetPtr target, unsigned int buffers,
  576. const Color& colour, float depth, unsigned short stencil)
  577. {
  578. THROW_IF_NOT_RENDER_THREAD;
  579. RenderTargetPtr previousRenderTarget = mActiveRenderTarget;
  580. if(target != mActiveRenderTarget)
  581. {
  582. previousRenderTarget = mActiveRenderTarget;
  583. setRenderTarget(target);
  584. }
  585. bool colourMask = !mColourWrite[0] || !mColourWrite[1]
  586. || !mColourWrite[2] || !mColourWrite[3];
  587. GLbitfield flags = 0;
  588. if (buffers & FBT_COLOUR)
  589. {
  590. flags |= GL_COLOR_BUFFER_BIT;
  591. // Enable buffer for writing if it isn't
  592. if (colourMask)
  593. {
  594. glColorMask(true, true, true, true);
  595. }
  596. glClearColor(colour.r, colour.g, colour.b, colour.a);
  597. }
  598. if (buffers & FBT_DEPTH)
  599. {
  600. flags |= GL_DEPTH_BUFFER_BIT;
  601. // Enable buffer for writing if it isn't
  602. if (!mDepthWrite)
  603. {
  604. glDepthMask( GL_TRUE );
  605. }
  606. glClearDepth(depth);
  607. }
  608. if (buffers & FBT_STENCIL)
  609. {
  610. flags |= GL_STENCIL_BUFFER_BIT;
  611. // Enable buffer for writing if it isn't
  612. glStencilMask(0xFFFFFFFF);
  613. glClearStencil(stencil);
  614. }
  615. // Disable scissor test as we want to clear the entire render surface
  616. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  617. if (scissorTestEnabled)
  618. {
  619. glDisable(GL_SCISSOR_TEST);
  620. }
  621. // Clear buffers
  622. glClear(flags);
  623. // Restore scissor test
  624. if (scissorTestEnabled)
  625. {
  626. glEnable(GL_SCISSOR_TEST);
  627. }
  628. // Reset buffer write state
  629. if (!mDepthWrite && (buffers & FBT_DEPTH))
  630. {
  631. glDepthMask( GL_FALSE );
  632. }
  633. if (colourMask && (buffers & FBT_COLOUR))
  634. {
  635. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  636. }
  637. if (buffers & FBT_STENCIL)
  638. {
  639. glStencilMask(mStencilWriteMask);
  640. }
  641. if(target != previousRenderTarget)
  642. {
  643. setRenderTarget(previousRenderTarget);
  644. }
  645. }
  646. /************************************************************************/
  647. /* PRIVATE */
  648. /************************************************************************/
  649. //-----------------------------------------------------------------------------
  650. void GLRenderSystem::setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw)
  651. {
  652. if (!activateGLTextureUnit(stage))
  653. return;
  654. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  655. getTextureAddressingMode(uvw.u));
  656. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  657. getTextureAddressingMode(uvw.v));
  658. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  659. getTextureAddressingMode(uvw.w));
  660. activateGLTextureUnit(0);
  661. }
  662. //-----------------------------------------------------------------------------
  663. void GLRenderSystem::setTextureBorderColor(UINT16 stage, const Color& colour)
  664. {
  665. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  666. if (activateGLTextureUnit(stage))
  667. {
  668. glTexParameterfv( mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  669. activateGLTextureUnit(0);
  670. }
  671. }
  672. //-----------------------------------------------------------------------------
  673. void GLRenderSystem::setTextureMipmapBias(UINT16 stage, float bias)
  674. {
  675. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  676. {
  677. if (activateGLTextureUnit(stage))
  678. {
  679. glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, bias);
  680. activateGLTextureUnit(0);
  681. }
  682. }
  683. }
  684. void GLRenderSystem::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  685. {
  686. GLint sourceBlend = getBlendMode(sourceFactor);
  687. GLint destBlend = getBlendMode(destFactor);
  688. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  689. {
  690. glDisable(GL_BLEND);
  691. }
  692. else
  693. {
  694. glEnable(GL_BLEND);
  695. glBlendFunc(sourceBlend, destBlend);
  696. }
  697. GLint func = GL_FUNC_ADD;
  698. switch(op)
  699. {
  700. case BO_ADD:
  701. func = GL_FUNC_ADD;
  702. break;
  703. case BO_SUBTRACT:
  704. func = GL_FUNC_SUBTRACT;
  705. break;
  706. case BO_REVERSE_SUBTRACT:
  707. func = GL_FUNC_REVERSE_SUBTRACT;
  708. break;
  709. case BO_MIN:
  710. func = GL_MIN;
  711. break;
  712. case BO_MAX:
  713. func = GL_MAX;
  714. break;
  715. }
  716. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  717. {
  718. glBlendEquation(func);
  719. }
  720. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  721. {
  722. glBlendEquationEXT(func);
  723. }
  724. }
  725. //-----------------------------------------------------------------------------
  726. void GLRenderSystem::setSceneBlending(
  727. BlendFactor sourceFactor, BlendFactor destFactor,
  728. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha,
  729. BlendOperation op, BlendOperation alphaOp )
  730. {
  731. GLint sourceBlend = getBlendMode(sourceFactor);
  732. GLint destBlend = getBlendMode(destFactor);
  733. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  734. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  735. if(sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  736. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  737. {
  738. glDisable(GL_BLEND);
  739. }
  740. else
  741. {
  742. glEnable(GL_BLEND);
  743. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  744. }
  745. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  746. switch(op)
  747. {
  748. case BO_ADD:
  749. func = GL_FUNC_ADD;
  750. break;
  751. case BO_SUBTRACT:
  752. func = GL_FUNC_SUBTRACT;
  753. break;
  754. case BO_REVERSE_SUBTRACT:
  755. func = GL_FUNC_REVERSE_SUBTRACT;
  756. break;
  757. case BO_MIN:
  758. func = GL_MIN;
  759. break;
  760. case BO_MAX:
  761. func = GL_MAX;
  762. break;
  763. }
  764. switch(alphaOp)
  765. {
  766. case BO_ADD:
  767. alphaFunc = GL_FUNC_ADD;
  768. break;
  769. case BO_SUBTRACT:
  770. alphaFunc = GL_FUNC_SUBTRACT;
  771. break;
  772. case BO_REVERSE_SUBTRACT:
  773. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  774. break;
  775. case BO_MIN:
  776. alphaFunc = GL_MIN;
  777. break;
  778. case BO_MAX:
  779. alphaFunc = GL_MAX;
  780. break;
  781. }
  782. if(GLEW_VERSION_2_0) {
  783. glBlendEquationSeparate(func, alphaFunc);
  784. }
  785. else if(GLEW_EXT_blend_equation_separate) {
  786. glBlendEquationSeparateEXT(func, alphaFunc);
  787. }
  788. }
  789. //-----------------------------------------------------------------------------
  790. void GLRenderSystem::setAlphaTest(CompareFunction func, unsigned char value)
  791. {
  792. if(func == CMPF_ALWAYS_PASS)
  793. {
  794. glDisable(GL_ALPHA_TEST);
  795. }
  796. else
  797. {
  798. glEnable(GL_ALPHA_TEST);
  799. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  800. }
  801. }
  802. //-----------------------------------------------------------------------------
  803. void GLRenderSystem::setAlphaToCoverage(bool enable)
  804. {
  805. static bool lasta2c = false;
  806. if (enable != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  807. {
  808. if (enable)
  809. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  810. else
  811. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  812. lasta2c = enable;
  813. }
  814. }
  815. //---------------------------------------------------------------------
  816. void GLRenderSystem::setScissorTestEnable(bool enable)
  817. {
  818. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  819. bool flipping = mActiveRenderTarget->requiresTextureFlipping();
  820. // GL measures from the bottom, not the top
  821. UINT32 targetHeight = mActiveRenderTarget->getHeight();
  822. // Calculate the "lower-left" corner of the viewport
  823. GLsizei x = 0, y = 0, w = 0, h = 0;
  824. if (enable)
  825. {
  826. glEnable(GL_SCISSOR_TEST);
  827. // GL uses width / height rather than right / bottom
  828. x = mScissorLeft;
  829. if (flipping)
  830. y = mScissorTop;
  831. else
  832. y = targetHeight - mScissorBottom;
  833. w = mScissorRight - mScissorLeft;
  834. h = mScissorBottom - mScissorTop;
  835. glScissor(x, y, w, h);
  836. }
  837. else
  838. {
  839. glDisable(GL_SCISSOR_TEST);
  840. // GL requires you to reset the scissor when disabling
  841. w = mViewportWidth;
  842. h = mViewportHeight;
  843. x = mViewportLeft;
  844. if (flipping)
  845. y = mViewportTop;
  846. else
  847. y = targetHeight - mViewportTop - h;
  848. glScissor(x, y, w, h);
  849. }
  850. }
  851. //-----------------------------------------------------------------------------
  852. void GLRenderSystem::setCullingMode(CullingMode mode)
  853. {
  854. mCullingMode = mode;
  855. GLenum cullMode;
  856. switch( mode )
  857. {
  858. case CULL_NONE:
  859. glDisable( GL_CULL_FACE );
  860. return;
  861. default:
  862. case CULL_CLOCKWISE:
  863. if (mActiveRenderTarget &&
  864. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  865. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  866. {
  867. cullMode = GL_FRONT;
  868. }
  869. else
  870. {
  871. cullMode = GL_BACK;
  872. }
  873. break;
  874. case CULL_COUNTERCLOCKWISE:
  875. if (mActiveRenderTarget &&
  876. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  877. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  878. {
  879. cullMode = GL_BACK;
  880. }
  881. else
  882. {
  883. cullMode = GL_FRONT;
  884. }
  885. break;
  886. }
  887. glEnable( GL_CULL_FACE );
  888. glCullFace( cullMode );
  889. }
  890. //-----------------------------------------------------------------------------
  891. void GLRenderSystem::setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction)
  892. {
  893. setDepthBufferCheckEnabled(depthTest);
  894. setDepthBufferWriteEnabled(depthWrite);
  895. setDepthBufferFunction(depthFunction);
  896. }
  897. //-----------------------------------------------------------------------------
  898. void GLRenderSystem::setDepthBufferCheckEnabled(bool enabled)
  899. {
  900. if (enabled)
  901. {
  902. glClearDepth(1.0f);
  903. glEnable(GL_DEPTH_TEST);
  904. }
  905. else
  906. {
  907. glDisable(GL_DEPTH_TEST);
  908. }
  909. }
  910. //-----------------------------------------------------------------------------
  911. void GLRenderSystem::setDepthBufferWriteEnabled(bool enabled)
  912. {
  913. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  914. glDepthMask( flag );
  915. // Store for reference in _beginFrame
  916. mDepthWrite = enabled;
  917. }
  918. //-----------------------------------------------------------------------------
  919. void GLRenderSystem::setDepthBufferFunction(CompareFunction func)
  920. {
  921. glDepthFunc(convertCompareFunction(func));
  922. }
  923. //-----------------------------------------------------------------------------
  924. void GLRenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  925. {
  926. if (constantBias != 0 || slopeScaleBias != 0)
  927. {
  928. glEnable(GL_POLYGON_OFFSET_FILL);
  929. glEnable(GL_POLYGON_OFFSET_POINT);
  930. glEnable(GL_POLYGON_OFFSET_LINE);
  931. glPolygonOffset(-slopeScaleBias, -constantBias);
  932. }
  933. else
  934. {
  935. glDisable(GL_POLYGON_OFFSET_FILL);
  936. glDisable(GL_POLYGON_OFFSET_POINT);
  937. glDisable(GL_POLYGON_OFFSET_LINE);
  938. }
  939. }
  940. //-----------------------------------------------------------------------------
  941. void GLRenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  942. {
  943. glColorMask(red, green, blue, alpha);
  944. // record this
  945. mColourWrite[0] = red;
  946. mColourWrite[1] = blue;
  947. mColourWrite[2] = green;
  948. mColourWrite[3] = alpha;
  949. }
  950. //---------------------------------------------------------------------
  951. void GLRenderSystem::setPolygonMode(PolygonMode level)
  952. {
  953. GLenum glmode;
  954. switch(level)
  955. {
  956. case PM_WIREFRAME:
  957. glmode = GL_LINE;
  958. break;
  959. default:
  960. case PM_SOLID:
  961. glmode = GL_FILL;
  962. break;
  963. }
  964. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  965. }
  966. //---------------------------------------------------------------------
  967. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  968. {
  969. if (enabled)
  970. glEnable(GL_STENCIL_TEST);
  971. else
  972. glDisable(GL_STENCIL_TEST);
  973. }
  974. //---------------------------------------------------------------------
  975. void GLRenderSystem::setStencilBufferOperations(StencilOperation stencilFailOp,
  976. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  977. {
  978. if (front)
  979. {
  980. glStencilOpSeparate(GL_FRONT,
  981. convertStencilOp(stencilFailOp, mInvertVertexWinding),
  982. convertStencilOp(depthFailOp, mInvertVertexWinding),
  983. convertStencilOp(passOp, mInvertVertexWinding));
  984. }
  985. else
  986. {
  987. glStencilOpSeparate(GL_BACK,
  988. convertStencilOp(stencilFailOp, !mInvertVertexWinding),
  989. convertStencilOp(depthFailOp, !mInvertVertexWinding),
  990. convertStencilOp(passOp, !mInvertVertexWinding));
  991. }
  992. }
  993. //---------------------------------------------------------------------
  994. void GLRenderSystem::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  995. {
  996. mStencilReadMask = mask;
  997. if(front)
  998. {
  999. mStencilCompareFront = func;
  1000. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1001. }
  1002. else
  1003. {
  1004. mStencilCompareBack = func;
  1005. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1006. }
  1007. }
  1008. //---------------------------------------------------------------------
  1009. void GLRenderSystem::setStencilBufferWriteMask(UINT32 mask)
  1010. {
  1011. mStencilWriteMask = mask;
  1012. glStencilMask(mask);
  1013. }
  1014. //---------------------------------------------------------------------
  1015. void GLRenderSystem::setStencilRefValue(UINT32 refValue)
  1016. {
  1017. THROW_IF_NOT_RENDER_THREAD;
  1018. mStencilRefValue = refValue;
  1019. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1020. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1021. }
  1022. //---------------------------------------------------------------------
  1023. void GLRenderSystem::setTextureFiltering(UINT16 unit,
  1024. FilterType ftype, FilterOptions fo)
  1025. {
  1026. if (!activateGLTextureUnit(unit))
  1027. return;
  1028. switch(ftype)
  1029. {
  1030. case FT_MIN:
  1031. mMinFilter = fo;
  1032. // Combine with existing mip filter
  1033. glTexParameteri(
  1034. mTextureTypes[unit],
  1035. GL_TEXTURE_MIN_FILTER,
  1036. getCombinedMinMipFilter());
  1037. break;
  1038. case FT_MAG:
  1039. switch (fo)
  1040. {
  1041. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1042. case FO_LINEAR:
  1043. glTexParameteri(
  1044. mTextureTypes[unit],
  1045. GL_TEXTURE_MAG_FILTER,
  1046. GL_LINEAR);
  1047. break;
  1048. case FO_POINT:
  1049. case FO_NONE:
  1050. glTexParameteri(
  1051. mTextureTypes[unit],
  1052. GL_TEXTURE_MAG_FILTER,
  1053. GL_NEAREST);
  1054. break;
  1055. }
  1056. break;
  1057. case FT_MIP:
  1058. mMipFilter = fo;
  1059. // Combine with existing min filter
  1060. glTexParameteri(
  1061. mTextureTypes[unit],
  1062. GL_TEXTURE_MIN_FILTER,
  1063. getCombinedMinMipFilter());
  1064. break;
  1065. }
  1066. activateGLTextureUnit(0);
  1067. }
  1068. //---------------------------------------------------------------------
  1069. void GLRenderSystem::setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy)
  1070. {
  1071. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1072. return;
  1073. if (!activateGLTextureUnit(unit))
  1074. return;
  1075. GLfloat largest_supported_anisotropy = 0;
  1076. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1077. if (maxAnisotropy > largest_supported_anisotropy)
  1078. maxAnisotropy = largest_supported_anisotropy ?
  1079. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1080. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  1081. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1082. activateGLTextureUnit(0);
  1083. }
  1084. //-----------------------------------------------------------------------------
  1085. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1086. {
  1087. // A note on GL user clipping:
  1088. // When an ARB vertex program is enabled in GL, user clipping is completely
  1089. // disabled. There is no way around this, it's just turned off.
  1090. // When using GLSL, user clipping can work but you have to include a
  1091. // glClipVertex command in your vertex shader.
  1092. // Thus the planes set here may not actually be respected.
  1093. size_t i = 0;
  1094. size_t numClipPlanes;
  1095. GLdouble clipPlane[4];
  1096. // Save previous modelview
  1097. glMatrixMode(GL_MODELVIEW);
  1098. glPushMatrix();
  1099. // just load view matrix (identity world)
  1100. GLfloat mat[16];
  1101. makeGLMatrix(mat, mViewMatrix);
  1102. glLoadMatrixf(mat);
  1103. numClipPlanes = clipPlanes.size();
  1104. for (i = 0; i < numClipPlanes; ++i)
  1105. {
  1106. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1107. const Plane& plane = clipPlanes[i];
  1108. if (i >= 6/*GL_MAX_CLIP_PLANES*/)
  1109. {
  1110. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1111. }
  1112. clipPlane[0] = plane.normal.x;
  1113. clipPlane[1] = plane.normal.y;
  1114. clipPlane[2] = plane.normal.z;
  1115. clipPlane[3] = plane.d;
  1116. glClipPlane(clipPlaneId, clipPlane);
  1117. glEnable(clipPlaneId);
  1118. }
  1119. // disable remaining clip planes
  1120. for ( ; i < 6/*GL_MAX_CLIP_PLANES*/; ++i)
  1121. {
  1122. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1123. }
  1124. // restore matrices
  1125. glPopMatrix();
  1126. }
  1127. //---------------------------------------------------------------------
  1128. void GLRenderSystem::oneTimeContextInitialization()
  1129. {
  1130. if (GLEW_VERSION_1_2)
  1131. {
  1132. // Set nicer lighting model -- d3d9 has this by default
  1133. glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
  1134. glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  1135. }
  1136. if (GLEW_VERSION_1_4)
  1137. {
  1138. glEnable(GL_COLOR_SUM);
  1139. glDisable(GL_DITHER);
  1140. }
  1141. // Check for FSAA
  1142. // Enable the extension if it was enabled by the GLSupport
  1143. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  1144. {
  1145. int fsaa_active = false;
  1146. glGetIntegerv(GL_SAMPLE_BUFFERS_ARB,(GLint*)&fsaa_active);
  1147. if(fsaa_active)
  1148. {
  1149. glEnable(GL_MULTISAMPLE_ARB);
  1150. }
  1151. }
  1152. }
  1153. //---------------------------------------------------------------------
  1154. void GLRenderSystem::switchContext(GLContext *context)
  1155. {
  1156. // Unbind GPU programs and rebind to new context later, because
  1157. // scene manager treat render system as ONE 'context' ONLY, and it
  1158. // cached the GPU programs using state.
  1159. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1160. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1161. unbindGpuProgram(GPT_GEOMETRY_PROGRAM);
  1162. unbindGpuProgram(GPT_HULL_PROGRAM);
  1163. unbindGpuProgram(GPT_DOMAIN_PROGRAM);
  1164. // It's ready for switching
  1165. if (mCurrentContext)
  1166. mCurrentContext->endCurrent();
  1167. mCurrentContext = context;
  1168. mCurrentContext->setCurrent();
  1169. // Check if the context has already done one-time initialisation
  1170. if(!mCurrentContext->getInitialized())
  1171. {
  1172. oneTimeContextInitialization();
  1173. mCurrentContext->setInitialized();
  1174. }
  1175. // Must reset depth/colour write mask to according with user desired, otherwise,
  1176. // clearFrameBuffer would be wrong because the value we are recorded may be
  1177. // difference with the really state stored in GL context.
  1178. glDepthMask(mDepthWrite);
  1179. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  1180. glStencilMask(mStencilWriteMask);
  1181. }
  1182. //---------------------------------------------------------------------
  1183. void GLRenderSystem::registerContext(GLContext* context)
  1184. {
  1185. if (!mGLInitialised)
  1186. {
  1187. // set up glew and GLSupport
  1188. initialiseContext(context);
  1189. checkForErrors();
  1190. std::vector<CamelotEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  1191. if (!tokens.empty())
  1192. {
  1193. mDriverVersion.major = parseInt(tokens[0]);
  1194. if (tokens.size() > 1)
  1195. mDriverVersion.minor = parseInt(tokens[1]);
  1196. if (tokens.size() > 2)
  1197. mDriverVersion.release = parseInt(tokens[2]);
  1198. }
  1199. mDriverVersion.build = 0;
  1200. // Initialise GL after the first window has been created
  1201. // TODO: fire this from emulation options, and don't duplicate float and Current capabilities
  1202. mCurrentCapabilities = createRenderSystemCapabilities();
  1203. checkForErrors();
  1204. initialiseFromRenderSystemCapabilities(mCurrentCapabilities);
  1205. checkForErrors();
  1206. // Initialise the main context
  1207. oneTimeContextInitialization();
  1208. checkForErrors();
  1209. if(mCurrentContext)
  1210. {
  1211. mCurrentContext->setInitialized();
  1212. checkForErrors();
  1213. }
  1214. }
  1215. }
  1216. //---------------------------------------------------------------------
  1217. void GLRenderSystem::unregisterContext(GLContext *context)
  1218. {
  1219. if(mCurrentContext == context) {
  1220. // Change the context to something else so that a valid context
  1221. // remains active. When this is the main context being unregistered,
  1222. // we set the main context to 0.
  1223. if(mCurrentContext != mMainContext) {
  1224. switchContext(mMainContext);
  1225. } else {
  1226. /// No contexts remain
  1227. mCurrentContext->endCurrent();
  1228. mCurrentContext = 0;
  1229. mMainContext = 0;
  1230. }
  1231. }
  1232. }
  1233. //---------------------------------------------------------------------
  1234. bool GLRenderSystem::activateGLTextureUnit(UINT16 unit)
  1235. {
  1236. if (mActiveTextureUnit != unit)
  1237. {
  1238. if (unit < getCapabilities()->getNumCombinedTextureUnits())
  1239. {
  1240. glActiveTexture(GL_TEXTURE0 + unit);
  1241. mActiveTextureUnit = unit;
  1242. return true;
  1243. }
  1244. else if (!unit)
  1245. {
  1246. // always ok to use the first unit
  1247. return true;
  1248. }
  1249. else
  1250. {
  1251. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1252. ". Supported range: 0 .. " + toString(getCapabilities()->getNumCombinedTextureUnits() - 1));
  1253. return false;
  1254. }
  1255. }
  1256. else
  1257. {
  1258. return true;
  1259. }
  1260. }
  1261. //---------------------------------------------------------------------
  1262. GLfloat GLRenderSystem::_getCurrentAnisotropy(UINT16 unit)
  1263. {
  1264. GLfloat curAniso = 0;
  1265. glGetTexParameterfv(mTextureTypes[unit],
  1266. GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1267. return curAniso ? curAniso : 1;
  1268. }
  1269. //---------------------------------------------------------------------
  1270. GLuint GLRenderSystem::getCombinedMinMipFilter(void) const
  1271. {
  1272. switch(mMinFilter)
  1273. {
  1274. case FO_ANISOTROPIC:
  1275. case FO_LINEAR:
  1276. switch(mMipFilter)
  1277. {
  1278. case FO_ANISOTROPIC:
  1279. case FO_LINEAR:
  1280. // linear min, linear mip
  1281. return GL_LINEAR_MIPMAP_LINEAR;
  1282. case FO_POINT:
  1283. // linear min, point mip
  1284. return GL_LINEAR_MIPMAP_NEAREST;
  1285. case FO_NONE:
  1286. // linear min, no mip
  1287. return GL_LINEAR;
  1288. }
  1289. break;
  1290. case FO_POINT:
  1291. case FO_NONE:
  1292. switch(mMipFilter)
  1293. {
  1294. case FO_ANISOTROPIC:
  1295. case FO_LINEAR:
  1296. // nearest min, linear mip
  1297. return GL_NEAREST_MIPMAP_LINEAR;
  1298. case FO_POINT:
  1299. // nearest min, point mip
  1300. return GL_NEAREST_MIPMAP_NEAREST;
  1301. case FO_NONE:
  1302. // nearest min, no mip
  1303. return GL_NEAREST;
  1304. }
  1305. break;
  1306. }
  1307. // should never get here
  1308. return 0;
  1309. }
  1310. //---------------------------------------------------------------------
  1311. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1312. {
  1313. switch(op)
  1314. {
  1315. case SOP_KEEP:
  1316. return GL_KEEP;
  1317. case SOP_ZERO:
  1318. return GL_ZERO;
  1319. case SOP_REPLACE:
  1320. return GL_REPLACE;
  1321. case SOP_INCREMENT:
  1322. return invert ? GL_DECR : GL_INCR;
  1323. case SOP_DECREMENT:
  1324. return invert ? GL_INCR : GL_DECR;
  1325. case SOP_INCREMENT_WRAP:
  1326. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1327. case SOP_DECREMENT_WRAP:
  1328. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1329. case SOP_INVERT:
  1330. return GL_INVERT;
  1331. };
  1332. // to keep compiler happy
  1333. return SOP_KEEP;
  1334. }
  1335. //---------------------------------------------------------------------
  1336. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1337. {
  1338. switch(func)
  1339. {
  1340. case CMPF_ALWAYS_FAIL:
  1341. return GL_NEVER;
  1342. case CMPF_ALWAYS_PASS:
  1343. return GL_ALWAYS;
  1344. case CMPF_LESS:
  1345. return GL_LESS;
  1346. case CMPF_LESS_EQUAL:
  1347. return GL_LEQUAL;
  1348. case CMPF_EQUAL:
  1349. return GL_EQUAL;
  1350. case CMPF_NOT_EQUAL:
  1351. return GL_NOTEQUAL;
  1352. case CMPF_GREATER_EQUAL:
  1353. return GL_GEQUAL;
  1354. case CMPF_GREATER:
  1355. return GL_GREATER;
  1356. };
  1357. // to keep compiler happy
  1358. return GL_ALWAYS;
  1359. }
  1360. //-----------------------------------------------------------------------------
  1361. String GLRenderSystem::getErrorDescription(long errCode) const
  1362. {
  1363. const GLubyte *errString = gluErrorString (errCode);
  1364. return (errString != 0) ? String((const char*) errString) : StringUtil::BLANK;
  1365. }
  1366. //-----------------------------------------------------------------------------
  1367. GLint GLRenderSystem::getBlendMode(BlendFactor blendMode) const
  1368. {
  1369. switch(blendMode)
  1370. {
  1371. case BF_ONE:
  1372. return GL_ONE;
  1373. case BF_ZERO:
  1374. return GL_ZERO;
  1375. case BF_DEST_COLOR:
  1376. return GL_DST_COLOR;
  1377. case BF_SOURCE_COLOR:
  1378. return GL_SRC_COLOR;
  1379. case BF_INV_DEST_COLOR:
  1380. return GL_ONE_MINUS_DST_COLOR;
  1381. case BF_INV_SOURCE_COLOR:
  1382. return GL_ONE_MINUS_SRC_COLOR;
  1383. case BF_DEST_ALPHA:
  1384. return GL_DST_ALPHA;
  1385. case BF_SOURCE_ALPHA:
  1386. return GL_SRC_ALPHA;
  1387. case BF_INV_DEST_ALPHA:
  1388. return GL_ONE_MINUS_DST_ALPHA;
  1389. case BF_INV_SOURCE_ALPHA:
  1390. return GL_ONE_MINUS_SRC_ALPHA;
  1391. };
  1392. // to keep compiler happy
  1393. return GL_ONE;
  1394. }
  1395. //-----------------------------------------------------------------------------
  1396. GLint GLRenderSystem::getTextureAddressingMode(
  1397. TextureAddressingMode tam) const
  1398. {
  1399. switch(tam)
  1400. {
  1401. default:
  1402. case TAM_WRAP:
  1403. return GL_REPEAT;
  1404. case TAM_MIRROR:
  1405. return GL_MIRRORED_REPEAT;
  1406. case TAM_CLAMP:
  1407. return GL_CLAMP_TO_EDGE;
  1408. case TAM_BORDER:
  1409. return GL_CLAMP_TO_BORDER;
  1410. }
  1411. }
  1412. //-----------------------------------------------------------------------------
  1413. void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  1414. {
  1415. size_t x = 0;
  1416. for (size_t i = 0; i < 4; i++)
  1417. {
  1418. for (size_t j = 0; j < 4; j++)
  1419. {
  1420. gl_matrix[x] = m[j][i];
  1421. x++;
  1422. }
  1423. }
  1424. }
  1425. //-----------------------------------------------------------------------
  1426. void GLRenderSystem::beginDraw()
  1427. {
  1428. if(mDrawCallInProgress)
  1429. CM_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1430. mDrawCallInProgress = true;
  1431. if(mCurrentVertexProgram == nullptr)
  1432. {
  1433. LOGWRN("Cannot render without a set vertex shader.");
  1434. return;
  1435. }
  1436. if(mBoundVertexDeclaration == nullptr)
  1437. {
  1438. LOGWRN("Cannot render without a set vertex declaration.");
  1439. return;
  1440. }
  1441. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1442. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1443. if(mActivePipeline != pipeline)
  1444. {
  1445. glBindProgramPipeline(pipeline->glHandle);
  1446. mActivePipeline = pipeline;
  1447. }
  1448. void* pBufferData = 0;
  1449. const VertexDeclaration::VertexElementList& decl = mBoundVertexDeclaration->getElements();
  1450. VertexDeclaration::VertexElementList::const_iterator elem, elemEnd;
  1451. elemEnd = decl.end();
  1452. const VertexDeclaration::VertexElementList& inputAttributes = mCurrentVertexProgram->getGLSLProgram()->getInputAttributes().getElements();
  1453. for (elem = decl.begin(); elem != elemEnd; ++elem)
  1454. {
  1455. auto iterFind = mBoundVertexBuffers.find(elem->getSource());
  1456. if(iterFind == mBoundVertexBuffers.end() || iterFind->second == nullptr)
  1457. continue; // skip unbound elements
  1458. VertexBufferPtr vertexBuffer = iterFind->second;
  1459. bool foundSemantic = false;
  1460. GLint attribLocation = 0;
  1461. for(auto iter = inputAttributes.begin(); iter != inputAttributes.end(); ++iter)
  1462. {
  1463. if(iter->getSemantic() == elem->getSemantic() && iter->getIndex() == elem->getIndex())
  1464. {
  1465. foundSemantic = true;
  1466. attribLocation = iter->getOffset();
  1467. break;
  1468. }
  1469. }
  1470. if(!foundSemantic) // Shader needs to have a matching input attribute, otherwise we skip it
  1471. continue;
  1472. // TODO - We might also want to check the size of input and buffer, and make sure they match? Or does OpenGL handle that internally?
  1473. glBindBuffer(GL_ARRAY_BUFFER, static_cast<const GLVertexBuffer*>(vertexBuffer.get())->getGLBufferId());
  1474. pBufferData = VBO_BUFFER_OFFSET(elem->getOffset());
  1475. unsigned int i = 0;
  1476. VertexElementSemantic sem = elem->getSemantic();
  1477. unsigned short typeCount = VertexElement::getTypeCount(elem->getType());
  1478. GLboolean normalised = GL_FALSE;
  1479. switch(elem->getType())
  1480. {
  1481. case VET_COLOR:
  1482. case VET_COLOR_ABGR:
  1483. case VET_COLOR_ARGB:
  1484. normalised = GL_TRUE;
  1485. break;
  1486. default:
  1487. break;
  1488. };
  1489. glVertexAttribPointerARB(
  1490. attribLocation,
  1491. typeCount,
  1492. GLHardwareBufferManager::getGLType(elem->getType()),
  1493. normalised,
  1494. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1495. pBufferData);
  1496. glEnableVertexAttribArray(attribLocation);
  1497. mBoundAttributes.push_back(attribLocation);
  1498. }
  1499. }
  1500. //-----------------------------------------------------------------------
  1501. void GLRenderSystem::endDraw()
  1502. {
  1503. if(!mDrawCallInProgress)
  1504. return;
  1505. mDrawCallInProgress = false;
  1506. // unbind any custom attributes
  1507. for (auto ai = mBoundAttributes.begin(); ai != mBoundAttributes.end(); ++ai)
  1508. {
  1509. glDisableVertexAttribArray(*ai);
  1510. }
  1511. glColor4f(1,1,1,1);
  1512. }
  1513. //-----------------------------------------------------------------------
  1514. bool GLRenderSystem::checkForErrors() const
  1515. {
  1516. GLenum glErr = glGetError();
  1517. bool errorsFound = false;
  1518. String msg;
  1519. while (glErr != GL_NO_ERROR)
  1520. {
  1521. const char* glerrStr = (const char*)gluErrorString(glErr);
  1522. if (glerrStr)
  1523. {
  1524. msg += String(glerrStr);
  1525. }
  1526. glErr = glGetError();
  1527. errorsFound = true;
  1528. }
  1529. if(errorsFound)
  1530. LOGWRN("OpenGL error: " + msg);
  1531. return errorsFound;
  1532. }
  1533. //-----------------------------------------------------------------------
  1534. GLint GLRenderSystem::getGLDrawMode() const
  1535. {
  1536. GLint primType;
  1537. //Use adjacency if there is a geometry program and it requested adjacency info
  1538. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1539. switch (mCurrentDrawOperation)
  1540. {
  1541. case DOT_POINT_LIST:
  1542. primType = GL_POINTS;
  1543. break;
  1544. case DOT_LINE_LIST:
  1545. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1546. break;
  1547. case DOT_LINE_STRIP:
  1548. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1549. break;
  1550. default:
  1551. case DOT_TRIANGLE_LIST:
  1552. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1553. break;
  1554. case DOT_TRIANGLE_STRIP:
  1555. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1556. break;
  1557. case DOT_TRIANGLE_FAN:
  1558. primType = GL_TRIANGLE_FAN;
  1559. break;
  1560. }
  1561. return primType;
  1562. }
  1563. //-----------------------------------------------------------------------
  1564. void GLRenderSystem::initialiseContext(GLContext* primary)
  1565. {
  1566. // Set main and current context
  1567. mMainContext = primary;
  1568. mCurrentContext = mMainContext;
  1569. // Set primary context as active
  1570. if(mCurrentContext)
  1571. mCurrentContext->setCurrent();
  1572. // Setup GLSupport
  1573. mGLSupport->initialiseExtensions();
  1574. // Get extension function pointers
  1575. #if CM_THREAD_SUPPORT != 1
  1576. glewContextInit(mGLSupport);
  1577. #endif
  1578. }
  1579. void GLRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps)
  1580. {
  1581. if(caps->getRenderSystemName() != getName())
  1582. {
  1583. CM_EXCEPT(InvalidParametersException,
  1584. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  1585. }
  1586. if(caps->hasCapability(RSC_GL1_5_NOVBO))
  1587. {
  1588. // Assign ARB functions same to GL 1.5 version since
  1589. // interface identical
  1590. glBindBufferARB = glBindBuffer;
  1591. glBufferDataARB = glBufferData;
  1592. glBufferSubDataARB = glBufferSubData;
  1593. glDeleteBuffersARB = glDeleteBuffers;
  1594. glGenBuffersARB = glGenBuffers;
  1595. glGetBufferParameterivARB = glGetBufferParameteriv;
  1596. glGetBufferPointervARB = glGetBufferPointerv;
  1597. glGetBufferSubDataARB = glGetBufferSubData;
  1598. glIsBufferARB = glIsBuffer;
  1599. glMapBufferARB = glMapBuffer;
  1600. glUnmapBufferARB = glUnmapBuffer;
  1601. }
  1602. HardwareBufferManager::startUp(CM_NEW(GLHardwareBufferManager, GenAlloc) GLHardwareBufferManager);
  1603. checkForErrors();
  1604. // GPU Program Manager setup
  1605. GpuProgramManager::startUp(CM_NEW(GLGpuProgramManager, GenAlloc) GLGpuProgramManager());
  1606. checkForErrors();
  1607. if(caps->isShaderProfileSupported("glsl"))
  1608. {
  1609. mGLSLProgramFactory = CM_NEW(GLSLProgramFactory, GenAlloc) GLSLProgramFactory();
  1610. HighLevelGpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  1611. checkForErrors();
  1612. }
  1613. if(caps->isShaderProfileSupported("cg"))
  1614. {
  1615. mCgProgramFactory = CM_NEW(CgProgramFactory, GenAlloc) CgProgramFactory();
  1616. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  1617. checkForErrors();
  1618. }
  1619. if(caps->hasCapability(RSC_HWOCCLUSION))
  1620. {
  1621. if(caps->hasCapability(RSC_GL1_5_NOHWOCCLUSION))
  1622. {
  1623. // Assign ARB functions same to GL 1.5 version since
  1624. // interface identical
  1625. glBeginQueryARB = glBeginQuery;
  1626. glDeleteQueriesARB = glDeleteQueries;
  1627. glEndQueryARB = glEndQuery;
  1628. glGenQueriesARB = glGenQueries;
  1629. glGetQueryObjectivARB = glGetQueryObjectiv;
  1630. glGetQueryObjectuivARB = glGetQueryObjectuiv;
  1631. glGetQueryivARB = glGetQueryiv;
  1632. glIsQueryARB = glIsQuery;
  1633. }
  1634. }
  1635. // Check for framebuffer object extension
  1636. if(caps->hasCapability(RSC_FBO))
  1637. {
  1638. // Before GL version 2.0, we need to get one of the extensions
  1639. if(caps->hasCapability(RSC_FBO_ARB))
  1640. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersARB;
  1641. else if(caps->hasCapability(RSC_FBO_ATI))
  1642. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersATI;
  1643. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  1644. {
  1645. // Create FBO manager
  1646. GLRTTManager::startUp(CM_NEW(GLRTTManager, GenAlloc) GLRTTManager());
  1647. checkForErrors();
  1648. }
  1649. }
  1650. else
  1651. {
  1652. CM_EXCEPT(RenderingAPIException, "GPU doesn't support frame buffer objects. OpenGL versions lower than 3.0 are not supported.");
  1653. }
  1654. mFragmentTexOffset = 0;
  1655. mVertexTexOffset = caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1656. mGeometryTexOffset = mVertexTexOffset + caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1657. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  1658. UINT32 totalNumTexUnits = caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1659. totalNumTexUnits += caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1660. totalNumTexUnits += caps->getNumTextureUnits(GPT_GEOMETRY_PROGRAM);
  1661. totalNumTexUnits += caps->getNumTextureUnits(GPT_HULL_PROGRAM);
  1662. totalNumTexUnits += caps->getNumTextureUnits(GPT_DOMAIN_PROGRAM);
  1663. totalNumTexUnits += caps->getNumTextureUnits(GPT_COMPUTE_PROGRAM);
  1664. if(totalNumTexUnits > numCombinedTexUnits)
  1665. CM_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  1666. mNumTextureTypes = numCombinedTexUnits;
  1667. mTextureTypes = CM_NEW_ARRAY(GLenum, mNumTextureTypes, GenAlloc);
  1668. for(UINT16 i = 0; i < numCombinedTexUnits; i++)
  1669. mTextureTypes[i] = 0;
  1670. mVertexUBOffset = 0;
  1671. UINT32 totalNumUniformBlocks = caps->getNumUniformBlockBuffers(GPT_VERTEX_PROGRAM);
  1672. mFragmentUBOffset = totalNumUniformBlocks;
  1673. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_FRAGMENT_PROGRAM);
  1674. mGeometryUBOffset = totalNumUniformBlocks;
  1675. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_GEOMETRY_PROGRAM);
  1676. mHullUBOffset = totalNumUniformBlocks;
  1677. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_HULL_PROGRAM);
  1678. mDomainUBOffset = totalNumUniformBlocks;
  1679. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_DOMAIN_PROGRAM);
  1680. mComputeUBOffset = totalNumUniformBlocks;
  1681. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_COMPUTE_PROGRAM);
  1682. UINT16 numCombinedUniformBlocks = caps->getNumCombinedUniformBlockBuffers();
  1683. if(totalNumUniformBlocks > numCombinedUniformBlocks)
  1684. CM_EXCEPT(InternalErrorException, "Number of combined uniform block buffers less than the number of individual per-stage buffers!?");
  1685. /// Create the texture manager
  1686. TextureManager::startUp(CM_NEW(GLTextureManager, GenAlloc) GLTextureManager(*mGLSupport));
  1687. checkForErrors();
  1688. mGLInitialised = true;
  1689. }
  1690. RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const
  1691. {
  1692. RenderSystemCapabilities* rsc = CM_NEW(RenderSystemCapabilities, GenAlloc) RenderSystemCapabilities();
  1693. rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true);
  1694. rsc->setDriverVersion(mDriverVersion);
  1695. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  1696. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  1697. rsc->setDeviceName(deviceName);
  1698. rsc->setRenderSystemName(getName());
  1699. // determine vendor
  1700. if (strstr(vendorName, "NVIDIA"))
  1701. rsc->setVendor(GPU_NVIDIA);
  1702. else if (strstr(vendorName, "ATI"))
  1703. rsc->setVendor(GPU_ATI);
  1704. else if (strstr(vendorName, "Intel"))
  1705. rsc->setVendor(GPU_INTEL);
  1706. else if (strstr(vendorName, "S3"))
  1707. rsc->setVendor(GPU_S3);
  1708. else if (strstr(vendorName, "Matrox"))
  1709. rsc->setVendor(GPU_MATROX);
  1710. else if (strstr(vendorName, "3DLabs"))
  1711. rsc->setVendor(GPU_3DLABS);
  1712. else if (strstr(vendorName, "SiS"))
  1713. rsc->setVendor(GPU_SIS);
  1714. else
  1715. rsc->setVendor(GPU_UNKNOWN);
  1716. // Supports fixed-function
  1717. rsc->setCapability(RSC_FIXED_FUNCTION);
  1718. // Check for hardware mipmapping support.
  1719. if(GLEW_VERSION_1_4 || GLEW_SGIS_generate_mipmap)
  1720. {
  1721. bool disableAutoMip = false;
  1722. #if CM_PLATFORM == CM_PLATFORM_APPLE || CM_PLATFORM == CM_PLATFORM_LINUX
  1723. // Apple & Linux ATI drivers have faults in hardware mipmap generation
  1724. if (rsc->getVendor() == GPU_ATI)
  1725. disableAutoMip = true;
  1726. #endif
  1727. // The Intel 915G frequently corrupts textures when using hardware mip generation
  1728. // I'm not currently sure how many generations of hardware this affects,
  1729. // so for now, be safe.
  1730. if (rsc->getVendor() == GPU_INTEL)
  1731. disableAutoMip = true;
  1732. // SiS chipsets also seem to have problems with this
  1733. if (rsc->getVendor() == GPU_SIS)
  1734. disableAutoMip = true;
  1735. if (!disableAutoMip)
  1736. rsc->setCapability(RSC_AUTOMIPMAP);
  1737. }
  1738. // Check for blending support
  1739. if(GLEW_VERSION_1_3 ||
  1740. GLEW_ARB_texture_env_combine ||
  1741. GLEW_EXT_texture_env_combine)
  1742. {
  1743. rsc->setCapability(RSC_BLENDING);
  1744. }
  1745. // Check for Anisotropy support
  1746. if(GLEW_EXT_texture_filter_anisotropic)
  1747. {
  1748. rsc->setCapability(RSC_ANISOTROPY);
  1749. }
  1750. // Check for DOT3 support
  1751. if(GLEW_VERSION_1_3 ||
  1752. GLEW_ARB_texture_env_dot3 ||
  1753. GLEW_EXT_texture_env_dot3)
  1754. {
  1755. rsc->setCapability(RSC_DOT3);
  1756. }
  1757. // Check for cube mapping
  1758. if(GLEW_VERSION_1_3 ||
  1759. GLEW_ARB_texture_cube_map ||
  1760. GLEW_EXT_texture_cube_map)
  1761. {
  1762. rsc->setCapability(RSC_CUBEMAPPING);
  1763. }
  1764. // Point sprites
  1765. if (GLEW_VERSION_2_0 || GLEW_ARB_point_sprite)
  1766. {
  1767. rsc->setCapability(RSC_POINT_SPRITES);
  1768. }
  1769. // Check for point parameters
  1770. if (GLEW_VERSION_1_4)
  1771. {
  1772. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1773. }
  1774. if (GLEW_ARB_point_parameters)
  1775. {
  1776. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB);
  1777. }
  1778. if (GLEW_EXT_point_parameters)
  1779. {
  1780. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT);
  1781. }
  1782. // Check for hardware stencil support and set bit depth
  1783. GLint stencil;
  1784. glGetIntegerv(GL_STENCIL_BITS,&stencil);
  1785. if(stencil)
  1786. {
  1787. rsc->setCapability(RSC_HWSTENCIL);
  1788. rsc->setStencilBufferBitDepth(stencil);
  1789. }
  1790. if(GLEW_VERSION_1_5 || GLEW_ARB_vertex_buffer_object)
  1791. {
  1792. if (!GLEW_ARB_vertex_buffer_object)
  1793. {
  1794. rsc->setCapability(RSC_GL1_5_NOVBO);
  1795. }
  1796. rsc->setCapability(RSC_VBO);
  1797. }
  1798. rsc->setCapability(RSC_VERTEX_PROGRAM);
  1799. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  1800. rsc->addShaderProfile("cg");
  1801. // NFZ - Check if GLSL is supported
  1802. if ( GLEW_VERSION_2_0 ||
  1803. (GLEW_ARB_shading_language_100 &&
  1804. GLEW_ARB_shader_objects &&
  1805. GLEW_ARB_fragment_shader &&
  1806. GLEW_ARB_vertex_shader) )
  1807. {
  1808. rsc->addShaderProfile("glsl");
  1809. }
  1810. // Check if geometry shaders are supported
  1811. if (GLEW_VERSION_2_0 &&
  1812. GLEW_EXT_geometry_shader4)
  1813. {
  1814. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  1815. rsc->setGeometryProgramConstantBoolCount(0);
  1816. rsc->setGeometryProgramConstantIntCount(0);
  1817. GLint floatConstantCount = 0;
  1818. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  1819. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  1820. GLint maxOutputVertices;
  1821. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  1822. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  1823. }
  1824. //Check if render to vertex buffer (transform feedback in OpenGL)
  1825. if (GLEW_VERSION_2_0 &&
  1826. GLEW_NV_transform_feedback)
  1827. {
  1828. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  1829. }
  1830. // Check for texture compression
  1831. if(GLEW_VERSION_1_3 || GLEW_ARB_texture_compression)
  1832. {
  1833. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1834. // Check for dxt compression
  1835. if(GLEW_EXT_texture_compression_s3tc)
  1836. {
  1837. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1838. }
  1839. // Check for vtc compression
  1840. if(GLEW_NV_texture_compression_vtc)
  1841. {
  1842. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  1843. }
  1844. }
  1845. // Scissor test is standard in GL 1.2 (is it emulated on some cards though?)
  1846. rsc->setCapability(RSC_SCISSOR_TEST);
  1847. // As are user clipping planes
  1848. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1849. // 2-sided stencil?
  1850. if (GLEW_VERSION_2_0 || GLEW_EXT_stencil_two_side)
  1851. {
  1852. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1853. }
  1854. // stencil wrapping?
  1855. if (GLEW_VERSION_1_4 || GLEW_EXT_stencil_wrap)
  1856. {
  1857. rsc->setCapability(RSC_STENCIL_WRAP);
  1858. }
  1859. // Check for hardware occlusion support
  1860. if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query)
  1861. {
  1862. // Some buggy driver claim that it is GL 1.5 compliant and
  1863. // not support ARB_occlusion_query
  1864. if (!GLEW_ARB_occlusion_query)
  1865. {
  1866. rsc->setCapability(RSC_GL1_5_NOHWOCCLUSION);
  1867. }
  1868. rsc->setCapability(RSC_HWOCCLUSION);
  1869. }
  1870. else if (GLEW_NV_occlusion_query)
  1871. {
  1872. // Support NV extension too for old hardware
  1873. rsc->setCapability(RSC_HWOCCLUSION);
  1874. }
  1875. // UBYTE4 always supported
  1876. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1877. // Infinite far plane always supported
  1878. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1879. // Check for non-power-of-2 texture support
  1880. if(GLEW_ARB_texture_non_power_of_two)
  1881. {
  1882. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1883. }
  1884. // Check for Float textures
  1885. if(GLEW_ATI_texture_float || GLEW_ARB_texture_float)
  1886. {
  1887. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1888. }
  1889. // 3D textures should always be supported
  1890. rsc->setCapability(RSC_TEXTURE_3D);
  1891. // Check for framebuffer object extension
  1892. if(GLEW_EXT_framebuffer_object)
  1893. {
  1894. // Probe number of draw buffers
  1895. // Only makes sense with FBO support, so probe here
  1896. if(GLEW_VERSION_2_0 ||
  1897. GLEW_ARB_draw_buffers ||
  1898. GLEW_ATI_draw_buffers)
  1899. {
  1900. GLint buffers;
  1901. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  1902. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)CM_MAX_MULTIPLE_RENDER_TARGETS));
  1903. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1904. if(!GLEW_VERSION_2_0)
  1905. {
  1906. // Before GL version 2.0, we need to get one of the extensions
  1907. if(GLEW_ARB_draw_buffers)
  1908. rsc->setCapability(RSC_FBO_ARB);
  1909. if(GLEW_ATI_draw_buffers)
  1910. rsc->setCapability(RSC_FBO_ATI);
  1911. }
  1912. // Set FBO flag for all 3 'subtypes'
  1913. rsc->setCapability(RSC_FBO);
  1914. }
  1915. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1916. }
  1917. // Check GLSupport for PBuffer support
  1918. if(mGLSupport->supportsPBuffers())
  1919. {
  1920. // Use PBuffers
  1921. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1922. rsc->setCapability(RSC_PBUFFER);
  1923. }
  1924. // Point size
  1925. float ps;
  1926. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  1927. rsc->setMaxPointSize(ps);
  1928. // Max number of fragment shader textures
  1929. GLint units;
  1930. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  1931. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  1932. // Max number of vertex shader textures
  1933. GLint vUnits;
  1934. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  1935. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  1936. if (vUnits > 0)
  1937. {
  1938. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1939. }
  1940. GLint numUniformBlocks;
  1941. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  1942. rsc->setNumUniformBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  1943. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  1944. rsc->setNumUniformBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  1945. if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
  1946. {
  1947. GLint geomUnits;
  1948. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  1949. rsc->setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  1950. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  1951. rsc->setNumUniformBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  1952. }
  1953. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  1954. {
  1955. rsc->setCapability(RSC_TESSELLATION_PROGRAM);
  1956. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  1957. rsc->setNumUniformBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  1958. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  1959. rsc->setNumUniformBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  1960. }
  1961. if (mGLSupport->checkExtension("GL_ARB_compute_shader")) // Enable once I include GL 4.3
  1962. {
  1963. //rsc->setCapability(RSC_COMPUTE_PROGRAM);
  1964. //GLint computeUnits;
  1965. //glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  1966. //rsc->setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  1967. //glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  1968. //rsc->setNumUniformBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  1969. }
  1970. GLint combinedTexUnits;
  1971. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  1972. rsc->setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  1973. GLint combinedUniformBlockUnits;
  1974. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  1975. rsc->setNumCombinedUniformBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  1976. // Mipmap LOD biasing
  1977. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1978. // These are Cg supported profiles, not really used in OpenGL itself in any way
  1979. rsc->addShaderProfile("glslf");
  1980. rsc->addShaderProfile("glslv");
  1981. rsc->addShaderProfile("glslg");
  1982. rsc->addGpuProgramProfile(GPP_PS_1_1, "glslf");
  1983. rsc->addGpuProgramProfile(GPP_PS_1_2, "glslf");
  1984. rsc->addGpuProgramProfile(GPP_PS_1_3, "glslf");
  1985. rsc->addGpuProgramProfile(GPP_PS_1_4, "glslf");
  1986. rsc->addGpuProgramProfile(GPP_PS_2_0, "glslf");
  1987. rsc->addGpuProgramProfile(GPP_PS_2_x, "glslf");
  1988. rsc->addGpuProgramProfile(GPP_PS_2_a, "glslf");
  1989. rsc->addGpuProgramProfile(GPP_PS_2_b, "glslf");
  1990. rsc->addGpuProgramProfile(GPP_PS_3_0, "glslf");
  1991. rsc->addGpuProgramProfile(GPP_PS_3_x, "glslf");
  1992. rsc->addGpuProgramProfile(GPP_VS_1_1, "glslv");
  1993. rsc->addGpuProgramProfile(GPP_VS_2_0, "glslv");
  1994. rsc->addGpuProgramProfile(GPP_VS_2_x, "glslv");
  1995. rsc->addGpuProgramProfile(GPP_VS_2_a, "glslv");
  1996. rsc->addGpuProgramProfile(GPP_VS_3_0, "glslv");
  1997. rsc->addGpuProgramProfile(GPP_PS_4_0, "glslf");
  1998. rsc->addGpuProgramProfile(GPP_VS_4_0, "glslv");
  1999. rsc->addGpuProgramProfile(GPP_GS_4_0, "glslg");
  2000. rsc->addGpuProgramProfile(GPP_PS_4_0, "glslf");
  2001. rsc->addGpuProgramProfile(GPP_VS_4_0, "glslv");
  2002. rsc->addGpuProgramProfile(GPP_GS_4_0, "glslg");
  2003. rsc->addGpuProgramProfile(GPP_PS_4_1, "glslf");
  2004. rsc->addGpuProgramProfile(GPP_VS_4_1, "glslv");
  2005. rsc->addGpuProgramProfile(GPP_GS_4_1, "glslg");
  2006. // No SM5 support for Cg as right now it only supports NV extensions, which isn't very useful
  2007. // Alpha to coverage?
  2008. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  2009. {
  2010. // Alpha to coverage always 'supported' when MSAA is available
  2011. // although card may ignore it if it doesn't specifically support A2C
  2012. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  2013. }
  2014. // Advanced blending operations
  2015. if(GLEW_VERSION_2_0)
  2016. {
  2017. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  2018. }
  2019. return rsc;
  2020. }
  2021. //---------------------------------------------------------------------
  2022. UINT32 GLRenderSystem::getGLTextureUnit(GpuProgramType gptype, UINT32 unit)
  2023. {
  2024. if(gptype != GPT_VERTEX_PROGRAM && gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_GEOMETRY_PROGRAM)
  2025. {
  2026. CM_EXCEPT(InvalidParametersException, "OpenGL cannot assign textures to this gpu program type: " + toString(gptype));
  2027. }
  2028. UINT32 numSupportedUnits = mCurrentCapabilities->getNumTextureUnits(gptype);
  2029. if(unit < 0 || unit >= numSupportedUnits)
  2030. {
  2031. CM_EXCEPT(InvalidParametersException, "Invalid texture unit index for the provided stage. Unit index: " + toString(unit) + ". Stage: " +
  2032. toString(gptype) + ". Supported range is 0 .. " + toString(numSupportedUnits - 1));
  2033. }
  2034. switch(gptype)
  2035. {
  2036. case GPT_FRAGMENT_PROGRAM:
  2037. return mFragmentTexOffset + unit;
  2038. case GPT_VERTEX_PROGRAM:
  2039. return mVertexTexOffset + unit;
  2040. case GPT_GEOMETRY_PROGRAM:
  2041. return mGeometryTexOffset + unit;
  2042. default:
  2043. CM_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  2044. }
  2045. }
  2046. //---------------------------------------------------------------------
  2047. UINT32 GLRenderSystem::getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding)
  2048. {
  2049. UINT32 maxNumBindings = mCurrentCapabilities->getNumUniformBlockBuffers(gptype);
  2050. if(binding < 0 || binding >= maxNumBindings)
  2051. {
  2052. CM_EXCEPT(InvalidParametersException, "Invalid buffer binding for the provided stage. Buffer binding: " + toString(binding) + ". Stage: " +
  2053. toString(gptype) + ". Supported range is 0 .. " + toString(maxNumBindings - 1));
  2054. }
  2055. switch(gptype)
  2056. {
  2057. case GPT_FRAGMENT_PROGRAM:
  2058. return mFragmentUBOffset + binding;
  2059. case GPT_VERTEX_PROGRAM:
  2060. return mVertexUBOffset + binding;
  2061. case GPT_GEOMETRY_PROGRAM:
  2062. return mGeometryUBOffset + binding;
  2063. case GPT_HULL_PROGRAM:
  2064. return mHullUBOffset + binding;
  2065. case GPT_DOMAIN_PROGRAM:
  2066. return mDomainUBOffset + binding;
  2067. case GPT_COMPUTE_PROGRAM:
  2068. return mComputeUBOffset + binding;
  2069. default:
  2070. CM_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  2071. }
  2072. }
  2073. void GLRenderSystem::setActiveProgram(GpuProgramType gptype, GLSLGpuProgramPtr program)
  2074. {
  2075. switch (gptype)
  2076. {
  2077. case GPT_VERTEX_PROGRAM:
  2078. mCurrentVertexProgram = program;
  2079. break;
  2080. case GPT_FRAGMENT_PROGRAM:
  2081. mCurrentFragmentProgram = program;
  2082. break;
  2083. case GPT_GEOMETRY_PROGRAM:
  2084. mCurrentGeometryProgram = program;
  2085. break;
  2086. case GPT_DOMAIN_PROGRAM:
  2087. mCurrentDomainProgram = program;
  2088. break;
  2089. case GPT_HULL_PROGRAM:
  2090. mCurrentHullProgram = program;
  2091. break;
  2092. }
  2093. }
  2094. GLSLGpuProgramPtr GLRenderSystem::getActiveProgram(GpuProgramType gptype) const
  2095. {
  2096. switch (gptype)
  2097. {
  2098. case GPT_VERTEX_PROGRAM:
  2099. return mCurrentVertexProgram;
  2100. break;
  2101. case GPT_FRAGMENT_PROGRAM:
  2102. return mCurrentFragmentProgram;
  2103. break;
  2104. case GPT_GEOMETRY_PROGRAM:
  2105. return mCurrentGeometryProgram;
  2106. break;
  2107. case GPT_DOMAIN_PROGRAM:
  2108. return mCurrentDomainProgram;
  2109. break;
  2110. case GPT_HULL_PROGRAM:
  2111. return mCurrentHullProgram;
  2112. break;
  2113. default:
  2114. CM_EXCEPT(InvalidParametersException, "Insupported gpu program type: " + toString(gptype));
  2115. }
  2116. }
  2117. /************************************************************************/
  2118. /* UTILITY */
  2119. /************************************************************************/
  2120. float GLRenderSystem::getMinimumDepthInputValue(void)
  2121. {
  2122. // Range [-1.0f, 1.0f]
  2123. return -1.0f;
  2124. }
  2125. //---------------------------------------------------------------------
  2126. float GLRenderSystem::getMaximumDepthInputValue(void)
  2127. {
  2128. // Range [-1.0f, 1.0f]
  2129. return 1.0f;
  2130. }
  2131. //---------------------------------------------------------------------
  2132. float GLRenderSystem::getHorizontalTexelOffset(void)
  2133. {
  2134. // No offset in GL
  2135. return 0.0f;
  2136. }
  2137. //---------------------------------------------------------------------
  2138. float GLRenderSystem::getVerticalTexelOffset(void)
  2139. {
  2140. // No offset in GL
  2141. return 0.0f;
  2142. }
  2143. VertexElementType GLRenderSystem::getColorVertexElementType(void) const
  2144. {
  2145. return VET_COLOR_ABGR;
  2146. }
  2147. //---------------------------------------------------------------------
  2148. void GLRenderSystem::convertProjectionMatrix(const Matrix4& matrix,
  2149. Matrix4& dest, bool forGpuProgram)
  2150. {
  2151. // no any conversion request for OpenGL
  2152. dest = matrix;
  2153. }
  2154. }
  2155. #undef THROW_IF_NOT_RENDER_THREAD