CmGLRenderSystem.cpp 71 KB

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