CmGLRenderSystem.cpp 74 KB

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