CmGLRenderSystem.cpp 73 KB

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