CmGLRenderSystem.cpp 75 KB

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