CmGLRenderSystem.cpp 74 KB

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