CmGLRenderSystem.cpp 75 KB

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