BsGLRenderAPI.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsGLRenderAPI.h"
  4. #include "BsRenderAPI.h"
  5. #include "BsGLTextureManager.h"
  6. #include "BsGLIndexBuffer.h"
  7. #include "BsGLUtil.h"
  8. #include "BsGLSLGpuProgram.h"
  9. #include "BsException.h"
  10. #include "BsGLContext.h"
  11. #include "BsGLSupport.h"
  12. #include "BsBlendState.h"
  13. #include "BsRasterizerState.h"
  14. #include "BsDepthStencilState.h"
  15. #include "BsGLRenderTexture.h"
  16. #include "BsGLRenderWindowManager.h"
  17. #include "BsGLSLProgramPipelineManager.h"
  18. #include "BsGLVertexArrayObjectManager.h"
  19. #include "BsRenderStateManager.h"
  20. #include "BsGpuParams.h"
  21. #include "BsGLGpuParamBlockBuffer.h"
  22. #include "BsCoreThread.h"
  23. #include "BsGLQueryManager.h"
  24. #include "BsDebug.h"
  25. #include "BsRenderStats.h"
  26. #include "BsGpuParamDesc.h"
  27. namespace BansheeEngine
  28. {
  29. const char* MODULE_NAME = "BansheeGLRenderAPI.dll";
  30. void __stdcall openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam);
  31. /************************************************************************/
  32. /* PUBLIC INTERFACE */
  33. /************************************************************************/
  34. GLRenderAPI::GLRenderAPI()
  35. : mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
  36. , mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280)
  37. , mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0)
  38. , mStencilReadMask(0xFFFFFFFF)
  39. , mStencilWriteMask(0xFFFFFFFF)
  40. , mStencilRefValue(0)
  41. , mStencilCompareFront(CMPF_ALWAYS_PASS)
  42. , mStencilCompareBack(CMPF_ALWAYS_PASS)
  43. , mNumTextureTypes(0)
  44. , mTextureTypes(nullptr)
  45. , mDepthWrite(true)
  46. , mGLSLProgramFactory(nullptr)
  47. , mProgramPipelineManager(nullptr)
  48. , mActivePipeline(nullptr)
  49. , mFragmentTexOffset(0)
  50. , mVertexTexOffset(0)
  51. , mGeometryTexOffset(0)
  52. , mFragmentUBOffset(0)
  53. , mVertexUBOffset(0)
  54. , mGeometryUBOffset(0)
  55. , mHullUBOffset(0)
  56. , mDomainUBOffset(0)
  57. , mComputeUBOffset(0)
  58. , mCurrentDrawOperation(DOT_TRIANGLE_LIST)
  59. , mDrawCallInProgress(false)
  60. , mActiveTextureUnit(0)
  61. {
  62. // Get our GLSupport
  63. mGLSupport = BansheeEngine::getGLSupport();
  64. mViewMatrix = Matrix4::IDENTITY;
  65. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  66. mCurrentContext = 0;
  67. mMainContext = 0;
  68. mGLInitialised = false;
  69. mMinFilter = FO_LINEAR;
  70. mMipFilter = FO_POINT;
  71. mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
  72. }
  73. GLRenderAPI::~GLRenderAPI()
  74. {
  75. }
  76. const StringID& GLRenderAPI::getName() const
  77. {
  78. static StringID strName("GLRenderAPI");
  79. return strName;
  80. }
  81. const String& GLRenderAPI::getShadingLanguageName() const
  82. {
  83. static String strName("glsl");
  84. return strName;
  85. }
  86. void GLRenderAPI::initializePrepare()
  87. {
  88. THROW_IF_NOT_CORE_THREAD;
  89. mGLSupport->start();
  90. mVideoModeInfo = mGLSupport->getVideoModeInfo();
  91. RenderWindowManager::startUp<GLRenderWindowManager>(this);
  92. RenderWindowCoreManager::startUp<GLRenderWindowCoreManager>(this);
  93. RenderStateCoreManager::startUp();
  94. QueryManager::startUp<GLQueryManager>();
  95. RenderAPICore::initializePrepare();
  96. }
  97. void GLRenderAPI::initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow)
  98. {
  99. // Get the context from the window and finish initialization
  100. SPtr<GLContext> context;
  101. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  102. // Set main and current context
  103. mMainContext = context;
  104. mCurrentContext = mMainContext;
  105. // Set primary context as active
  106. if (mCurrentContext)
  107. mCurrentContext->setCurrent();
  108. checkForErrors();
  109. // Setup GLSupport
  110. mGLSupport->initializeExtensions();
  111. checkForErrors();
  112. Vector<BansheeEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  113. if (!tokens.empty())
  114. {
  115. mDriverVersion.major = parseINT32(tokens[0]);
  116. if (tokens.size() > 1)
  117. mDriverVersion.minor = parseINT32(tokens[1]);
  118. if (tokens.size() > 2)
  119. mDriverVersion.release = parseINT32(tokens[2]);
  120. }
  121. mDriverVersion.build = 0;
  122. mCurrentCapabilities = createRenderSystemCapabilities();
  123. initFromCaps(mCurrentCapabilities);
  124. GLVertexArrayObjectManager::startUp();
  125. glFrontFace(GL_CW);
  126. mGLInitialised = true;
  127. RenderAPICore::initializeFinalize(primaryWindow);
  128. }
  129. void GLRenderAPI::destroyCore()
  130. {
  131. RenderAPICore::destroyCore();
  132. // Deleting the GLSL program factory
  133. if (mGLSLProgramFactory)
  134. {
  135. // Remove from manager safely
  136. GpuProgramCoreManager::instance().removeFactory(mGLSLProgramFactory);
  137. bs_delete(mGLSLProgramFactory);
  138. mGLSLProgramFactory = nullptr;
  139. }
  140. // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
  141. HardwareBufferCoreManager::shutDown();
  142. HardwareBufferManager::shutDown();
  143. GLRTTManager::shutDown();
  144. mBoundVertexBuffers.clear();
  145. mBoundVertexDeclaration = nullptr;
  146. mBoundIndexBuffer = nullptr;
  147. mCurrentVertexProgram = nullptr;
  148. mCurrentFragmentProgram = nullptr;
  149. mCurrentGeometryProgram = nullptr;
  150. mCurrentHullProgram = nullptr;
  151. mCurrentDomainProgram = nullptr;
  152. mCurrentComputeProgram = nullptr;
  153. mGLSupport->stop();
  154. TextureCoreManager::shutDown();
  155. TextureManager::shutDown();
  156. QueryManager::shutDown();
  157. RenderWindowCoreManager::shutDown();
  158. RenderWindowManager::shutDown();
  159. RenderStateCoreManager::shutDown();
  160. GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
  161. mGLInitialised = false;
  162. if(mProgramPipelineManager != nullptr)
  163. bs_delete(mProgramPipelineManager);
  164. if(mGLSupport)
  165. bs_delete(mGLSupport);
  166. if(mTextureTypes != nullptr)
  167. bs_deleteN(mTextureTypes, mNumTextureTypes);
  168. }
  169. void GLRenderAPI::bindGpuProgram(const SPtr<GpuProgramCore>& prg)
  170. {
  171. THROW_IF_NOT_CORE_THREAD;
  172. SPtr<GLSLGpuProgramCore> glprg = std::static_pointer_cast<GLSLGpuProgramCore>(prg);
  173. switch (glprg->getProperties().getType())
  174. {
  175. case GPT_VERTEX_PROGRAM:
  176. mCurrentVertexProgram = glprg;
  177. break;
  178. case GPT_FRAGMENT_PROGRAM:
  179. mCurrentFragmentProgram = glprg;
  180. break;
  181. case GPT_GEOMETRY_PROGRAM:
  182. mCurrentGeometryProgram = glprg;
  183. break;
  184. case GPT_DOMAIN_PROGRAM:
  185. mCurrentDomainProgram = glprg;
  186. break;
  187. case GPT_HULL_PROGRAM:
  188. mCurrentHullProgram = glprg;
  189. break;
  190. case GPT_COMPUTE_PROGRAM:
  191. mCurrentComputeProgram = glprg;
  192. }
  193. RenderAPICore::bindGpuProgram(prg);
  194. }
  195. void GLRenderAPI::unbindGpuProgram(GpuProgramType gptype)
  196. {
  197. THROW_IF_NOT_CORE_THREAD;
  198. setActiveProgram(gptype, nullptr);
  199. RenderAPICore::unbindGpuProgram(gptype);
  200. }
  201. void GLRenderAPI::setConstantBuffers(GpuProgramType gptype, const SPtr<GpuParamsCore>& bindableParams)
  202. {
  203. THROW_IF_NOT_CORE_THREAD;
  204. bindableParams->updateHardwareBuffers();
  205. const GpuParamDesc& paramDesc = bindableParams->getParamDesc();
  206. SPtr<GLSLGpuProgramCore> activeProgram = getActiveProgram(gptype);
  207. GLuint glProgram = activeProgram->getGLHandle();
  208. UINT8* uniformBufferData = nullptr;
  209. UINT32 blockBinding = 0;
  210. for(auto iter = paramDesc.paramBlocks.begin(); iter != paramDesc.paramBlocks.end(); ++iter)
  211. {
  212. SPtr<GpuParamBlockBufferCore> paramBlockBuffer = bindableParams->getParamBlockBuffer(iter->second.slot);
  213. if(paramBlockBuffer == nullptr)
  214. continue;
  215. if(iter->second.slot == 0)
  216. {
  217. // 0 means uniforms are not in block, in which case we handle it specially
  218. if (uniformBufferData == nullptr && paramBlockBuffer->getSize() > 0)
  219. {
  220. uniformBufferData = (UINT8*)bs_alloc(paramBlockBuffer->getSize());
  221. paramBlockBuffer->readFromGPU(uniformBufferData); // TODO - Don't read from GPU!? Just read the cached version
  222. }
  223. continue;
  224. }
  225. const GLGpuParamBlockBufferCore* glParamBlockBuffer = static_cast<const GLGpuParamBlockBufferCore*>(paramBlockBuffer.get());
  226. UINT32 globalBlockBinding = getGLUniformBlockBinding(gptype, blockBinding);
  227. glUniformBlockBinding(glProgram, iter->second.slot - 1, globalBlockBinding);
  228. glBindBufferRange(GL_UNIFORM_BUFFER, globalBlockBinding, glParamBlockBuffer->getGLHandle(), 0, glParamBlockBuffer->getSize());
  229. blockBinding++;
  230. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  231. }
  232. bool hasBoundAtLeastOne = false;
  233. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  234. {
  235. const GpuParamDataDesc& paramDesc = iter->second;
  236. if(paramDesc.paramBlockSlot != 0) // 0 means uniforms are not in a block
  237. continue;
  238. const UINT8* ptrData = uniformBufferData + paramDesc.cpuMemOffset * sizeof(UINT32);
  239. hasBoundAtLeastOne = true;
  240. // Note: We don't transpose matrices here even though we don't use column major format
  241. // because they are assumed to be pre-transposed in the GpuParams buffer
  242. switch(paramDesc.type)
  243. {
  244. case GPDT_FLOAT1:
  245. glProgramUniform1fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  246. break;
  247. case GPDT_FLOAT2:
  248. glProgramUniform2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  249. break;
  250. case GPDT_FLOAT3:
  251. glProgramUniform3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  252. break;
  253. case GPDT_FLOAT4:
  254. glProgramUniform4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  255. break;
  256. case GPDT_MATRIX_2X2:
  257. glProgramUniformMatrix2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  258. GL_FALSE, (GLfloat*)ptrData);
  259. break;
  260. case GPDT_MATRIX_2X3:
  261. glProgramUniformMatrix3x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  262. GL_FALSE, (GLfloat*)ptrData);
  263. break;
  264. case GPDT_MATRIX_2X4:
  265. glProgramUniformMatrix4x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  266. GL_FALSE, (GLfloat*)ptrData);
  267. break;
  268. case GPDT_MATRIX_3X2:
  269. glProgramUniformMatrix2x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  270. GL_FALSE, (GLfloat*)ptrData);
  271. break;
  272. case GPDT_MATRIX_3X3:
  273. glProgramUniformMatrix3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  274. GL_FALSE, (GLfloat*)ptrData);
  275. break;
  276. case GPDT_MATRIX_3X4:
  277. glProgramUniformMatrix4x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  278. GL_FALSE, (GLfloat*)ptrData);
  279. break;
  280. case GPDT_MATRIX_4X2:
  281. glProgramUniformMatrix2x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  282. GL_FALSE, (GLfloat*)ptrData);
  283. break;
  284. case GPDT_MATRIX_4X3:
  285. glProgramUniformMatrix3x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  286. GL_FALSE, (GLfloat*)ptrData);
  287. break;
  288. case GPDT_MATRIX_4X4:
  289. glProgramUniformMatrix4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  290. GL_FALSE, (GLfloat*)ptrData);
  291. break;
  292. case GPDT_INT1:
  293. glProgramUniform1iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  294. break;
  295. case GPDT_INT2:
  296. glProgramUniform2iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  297. break;
  298. case GPDT_INT3:
  299. glProgramUniform3iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  300. break;
  301. case GPDT_INT4:
  302. glProgramUniform4iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  303. break;
  304. case GPDT_BOOL:
  305. glProgramUniform1uiv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLuint*)ptrData);
  306. break;
  307. default:
  308. case GPDT_UNKNOWN:
  309. break;
  310. }
  311. }
  312. if (hasBoundAtLeastOne)
  313. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  314. if(uniformBufferData != nullptr)
  315. {
  316. bs_free(uniformBufferData);
  317. }
  318. }
  319. void GLRenderAPI::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr)
  320. {
  321. THROW_IF_NOT_CORE_THREAD;
  322. unit = getGLTextureUnit(gptype, unit);
  323. if (!activateGLTextureUnit(unit))
  324. return;
  325. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  326. if (enabled && tex)
  327. {
  328. mTextureTypes[unit] = tex->getGLTextureTarget();
  329. glBindTexture(mTextureTypes[unit], tex->getGLID());
  330. }
  331. else
  332. {
  333. // TODO - This doesn't actually disable all textures set on this image unit, only the 2D ones
  334. // - If a non-2D sampler is used, the texture will still be displayed
  335. glBindTexture(GL_TEXTURE_2D, 0);
  336. }
  337. activateGLTextureUnit(0);
  338. BS_INC_RENDER_STAT(NumTextureBinds);
  339. }
  340. void GLRenderAPI::setSamplerState(GpuProgramType gptype, UINT16 unit, const SPtr<SamplerStateCore>& state)
  341. {
  342. THROW_IF_NOT_CORE_THREAD;
  343. const SamplerProperties& stateProps = state->getProperties();
  344. unit = getGLTextureUnit(gptype, unit);
  345. // Set texture layer filtering
  346. setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
  347. setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
  348. setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
  349. // Set texture anisotropy
  350. setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
  351. // Set mipmap biasing
  352. setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
  353. // Texture addressing mode
  354. const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
  355. setTextureAddressingMode(unit, uvw);
  356. // Set border color
  357. setTextureBorderColor(unit, stateProps.getBorderColor());
  358. SPtr<GLSLGpuProgramCore> activeProgram = getActiveProgram(gptype);
  359. GLuint glProgram = activeProgram->getGLHandle();
  360. glProgramUniform1i(glProgram, unit, getGLTextureUnit(gptype, unit));
  361. BS_INC_RENDER_STAT(NumSamplerBinds);
  362. }
  363. void GLRenderAPI::setLoadStoreTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr,
  364. const TextureSurface& surface)
  365. {
  366. THROW_IF_NOT_CORE_THREAD;
  367. // TODO - OpenGL can't bind a certain subset of faces like DX11, only zero, one or all, so I'm ignoring numSlices parameter
  368. if (texPtr != nullptr)
  369. {
  370. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  371. glBindImageTexture(unit, tex->getGLID(), surface.mipLevel, surface.numArraySlices > 1,
  372. surface.arraySlice, tex->getGLFormat(), GL_READ_WRITE);
  373. }
  374. else
  375. glBindImageTexture(unit, 0, 0, false, 0, 0, GL_READ_WRITE);
  376. BS_INC_RENDER_STAT(NumTextureBinds);
  377. }
  378. void GLRenderAPI::setBlendState(const SPtr<BlendStateCore>& blendState)
  379. {
  380. THROW_IF_NOT_CORE_THREAD;
  381. const BlendProperties& stateProps = blendState->getProperties();
  382. // Alpha to coverage
  383. setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
  384. // Blend states
  385. // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
  386. if (stateProps.getBlendEnabled(0))
  387. {
  388. setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
  389. stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
  390. }
  391. else
  392. {
  393. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  394. }
  395. // Color write mask
  396. UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
  397. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  398. BS_INC_RENDER_STAT(NumBlendStateChanges);
  399. }
  400. void GLRenderAPI::setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState)
  401. {
  402. THROW_IF_NOT_CORE_THREAD;
  403. const RasterizerProperties& stateProps = rasterizerState->getProperties();
  404. setDepthBias(stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
  405. setCullingMode(stateProps.getCullMode());
  406. setPolygonMode(stateProps.getPolygonMode());
  407. setScissorTestEnable(stateProps.getScissorEnable());
  408. setMultisamplingEnable(stateProps.getMultisampleEnable());
  409. setDepthClipEnable(stateProps.getDepthClipEnable());
  410. setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
  411. BS_INC_RENDER_STAT(NumRasterizerStateChanges);
  412. }
  413. void GLRenderAPI::setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue)
  414. {
  415. THROW_IF_NOT_CORE_THREAD;
  416. const DepthStencilProperties& stateProps = depthStencilState->getProperties();
  417. // Set stencil buffer options
  418. setStencilCheckEnabled(stateProps.getStencilEnable());
  419. setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
  420. setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
  421. setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
  422. setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
  423. setStencilBufferWriteMask(stateProps.getStencilWriteMask());
  424. // Set depth buffer options
  425. setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
  426. setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
  427. setDepthBufferFunction(stateProps.getDepthComparisonFunc());
  428. // Set stencil ref value
  429. setStencilRefValue(stencilRefValue);
  430. BS_INC_RENDER_STAT(NumDepthStencilStateChanges);
  431. }
  432. void GLRenderAPI::setViewport(const Rect2& area)
  433. {
  434. THROW_IF_NOT_CORE_THREAD;
  435. mViewportNorm = area;
  436. applyViewport();
  437. }
  438. void GLRenderAPI::setRenderTarget(const SPtr<RenderTargetCore>& target, bool readOnlyDepthStencil)
  439. {
  440. THROW_IF_NOT_CORE_THREAD;
  441. // Switch context if different from current one
  442. if (target != nullptr)
  443. {
  444. SPtr<GLContext> newContext;
  445. target->getCustomAttribute("GLCONTEXT", &newContext);
  446. if (newContext && mCurrentContext != newContext)
  447. {
  448. switchContext(newContext);
  449. }
  450. }
  451. // This must happen after context switch to ensure previous context is still alive
  452. mActiveRenderTarget = target;
  453. GLFrameBufferObject* fbo = nullptr;
  454. if(target != nullptr)
  455. target->getCustomAttribute("FBO", &fbo);
  456. if (fbo != nullptr)
  457. {
  458. fbo->bind();
  459. if (GLEW_EXT_framebuffer_sRGB)
  460. {
  461. // Enable / disable sRGB states
  462. if (target->getProperties().isHwGammaEnabled())
  463. {
  464. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  465. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  466. // enabling, but GL spec says incapable surfaces ignore the setting
  467. // anyway. We test the capability to enable isHardwareGammaEnabled.
  468. }
  469. else
  470. {
  471. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  472. }
  473. }
  474. }
  475. else
  476. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  477. applyViewport();
  478. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  479. }
  480. void GLRenderAPI::beginFrame()
  481. {
  482. THROW_IF_NOT_CORE_THREAD;
  483. // Activate the viewport clipping
  484. glEnable(GL_SCISSOR_TEST);
  485. }
  486. void GLRenderAPI::endFrame()
  487. {
  488. THROW_IF_NOT_CORE_THREAD;
  489. // Deactivate the viewport clipping.
  490. glDisable(GL_SCISSOR_TEST);
  491. }
  492. void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers)
  493. {
  494. THROW_IF_NOT_CORE_THREAD;
  495. if ((index + numBuffers) > (UINT32)mBoundVertexBuffers.size())
  496. mBoundVertexBuffers.resize(index + numBuffers);
  497. for(UINT32 i = 0; i < numBuffers; i++)
  498. {
  499. mBoundVertexBuffers[index + i] = buffers[i];
  500. }
  501. }
  502. void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration)
  503. {
  504. THROW_IF_NOT_CORE_THREAD;
  505. mBoundVertexDeclaration = vertexDeclaration;
  506. }
  507. void GLRenderAPI::setDrawOperation(DrawOperationType op)
  508. {
  509. THROW_IF_NOT_CORE_THREAD;
  510. mCurrentDrawOperation = op;
  511. }
  512. void GLRenderAPI::setIndexBuffer(const SPtr<IndexBufferCore>& buffer)
  513. {
  514. THROW_IF_NOT_CORE_THREAD;
  515. mBoundIndexBuffer = buffer;
  516. }
  517. void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount)
  518. {
  519. // Find the correct type to render
  520. GLint primType = getGLDrawMode();
  521. beginDraw();
  522. if (instanceCount <= 1)
  523. glDrawArrays(primType, vertexOffset, vertexCount);
  524. else
  525. glDrawArraysInstanced(primType, vertexOffset, vertexCount, instanceCount);
  526. endDraw();
  527. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  528. BS_INC_RENDER_STAT(NumDrawCalls);
  529. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  530. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  531. }
  532. void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  533. UINT32 instanceCount)
  534. {
  535. if (mBoundIndexBuffer == nullptr)
  536. {
  537. LOGWRN("Cannot draw indexed because index buffer is not set.");
  538. return;
  539. }
  540. // Find the correct type to render
  541. GLint primType = getGLDrawMode();
  542. beginDraw();
  543. SPtr<GLIndexBufferCore> indexBuffer = std::static_pointer_cast<GLIndexBufferCore>(mBoundIndexBuffer);
  544. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  545. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  546. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  547. if (instanceCount <= 1)
  548. {
  549. glDrawElementsBaseVertex(primType, indexCount, indexType,
  550. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex), vertexOffset);
  551. }
  552. else
  553. {
  554. glDrawElementsInstancedBaseVertex(primType, indexCount, indexType,
  555. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex), instanceCount, vertexOffset);
  556. }
  557. endDraw();
  558. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  559. BS_INC_RENDER_STAT(NumDrawCalls);
  560. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  561. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  562. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  563. }
  564. void GLRenderAPI::dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ)
  565. {
  566. if (mCurrentComputeProgram == nullptr)
  567. {
  568. LOGWRN("Cannot dispatch compute without a set compute program.");
  569. return;
  570. }
  571. glUseProgram(mCurrentComputeProgram->getGLHandle());
  572. glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);
  573. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  574. BS_INC_RENDER_STAT(NumComputeCalls);
  575. }
  576. void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  577. {
  578. THROW_IF_NOT_CORE_THREAD;
  579. mScissorTop = top;
  580. mScissorBottom = bottom;
  581. mScissorLeft = left;
  582. mScissorRight = right;
  583. }
  584. void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  585. {
  586. if(mActiveRenderTarget == nullptr)
  587. return;
  588. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  589. Rect2I clearRect(0, 0, rtProps.getWidth(), rtProps.getHeight());
  590. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  591. }
  592. void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  593. {
  594. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  595. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  596. }
  597. void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect,
  598. UINT8 targetMask)
  599. {
  600. THROW_IF_NOT_CORE_THREAD;
  601. if(mActiveRenderTarget == nullptr)
  602. return;
  603. bool colorMask = !mColorWrite[0] || !mColorWrite[1]
  604. || !mColorWrite[2] || !mColorWrite[3];
  605. // Disable scissor test as we want to clear the entire render surface
  606. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  607. UINT32 oldScissorTop = mScissorTop;
  608. UINT32 oldScissorBottom = mScissorBottom;
  609. UINT32 oldScissorLeft = mScissorLeft;
  610. UINT32 oldScissorRight = mScissorRight;
  611. if (scissorTestEnabled)
  612. {
  613. glDisable(GL_SCISSOR_TEST);
  614. }
  615. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  616. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  617. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.getWidth() && clearRect.height == rtProps.getHeight());
  618. if (!clearEntireTarget)
  619. {
  620. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  621. setScissorTestEnable(true);
  622. }
  623. if (buffers & FBT_COLOR)
  624. {
  625. // Enable buffer for writing if it isn't
  626. if (colorMask)
  627. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  628. }
  629. if (buffers & FBT_DEPTH)
  630. {
  631. // Enable buffer for writing if it isn't
  632. if (!mDepthWrite)
  633. glDepthMask(GL_TRUE);
  634. }
  635. if (buffers & FBT_STENCIL)
  636. {
  637. // Enable buffer for writing if it isn't
  638. glStencilMask(0xFFFFFFFF);
  639. }
  640. if (targetMask == 0xFF)
  641. {
  642. GLbitfield flags = 0;
  643. if (buffers & FBT_COLOR)
  644. {
  645. flags |= GL_COLOR_BUFFER_BIT;
  646. glClearColor(color.r, color.g, color.b, color.a);
  647. }
  648. if (buffers & FBT_DEPTH)
  649. {
  650. flags |= GL_DEPTH_BUFFER_BIT;
  651. glClearDepth(depth);
  652. }
  653. if (buffers & FBT_STENCIL)
  654. {
  655. flags |= GL_STENCIL_BUFFER_BIT;
  656. glClearStencil(stencil);
  657. }
  658. // Clear buffers
  659. glClear(flags);
  660. }
  661. else
  662. {
  663. GLFrameBufferObject* fbo = nullptr;
  664. mActiveRenderTarget->getCustomAttribute("FBO", &fbo);
  665. if (buffers & FBT_COLOR)
  666. {
  667. for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
  668. {
  669. if (fbo->hasColorBuffer(i) && ((1 << i) & targetMask) != 0)
  670. glClearBufferfv(GL_COLOR, i, (GLfloat*)&color);
  671. }
  672. }
  673. if (buffers & FBT_DEPTH)
  674. {
  675. if (buffers & FBT_STENCIL)
  676. {
  677. glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
  678. }
  679. else
  680. {
  681. glClearBufferfv(GL_DEPTH, 0, &depth);
  682. }
  683. }
  684. else if (buffers & FBT_STENCIL)
  685. {
  686. INT32 stencilClear = (INT32)stencil;
  687. glClearBufferiv(GL_STENCIL, 0, &stencilClear);
  688. }
  689. }
  690. if (!clearEntireTarget)
  691. {
  692. setScissorTestEnable(false);
  693. }
  694. // Restore scissor test
  695. if (scissorTestEnabled)
  696. {
  697. glEnable(GL_SCISSOR_TEST);
  698. mScissorTop = oldScissorTop;
  699. mScissorBottom = oldScissorBottom;
  700. mScissorLeft = oldScissorLeft;
  701. mScissorRight = oldScissorRight;
  702. }
  703. // Reset buffer write state
  704. if (!mDepthWrite && (buffers & FBT_DEPTH))
  705. {
  706. glDepthMask(GL_FALSE);
  707. }
  708. if (colorMask && (buffers & FBT_COLOR))
  709. {
  710. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  711. }
  712. if (buffers & FBT_STENCIL)
  713. {
  714. glStencilMask(mStencilWriteMask);
  715. }
  716. BS_INC_RENDER_STAT(NumClears);
  717. }
  718. /************************************************************************/
  719. /* PRIVATE */
  720. /************************************************************************/
  721. void GLRenderAPI::setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw)
  722. {
  723. if (!activateGLTextureUnit(stage))
  724. return;
  725. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  726. getTextureAddressingMode(uvw.u));
  727. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  728. getTextureAddressingMode(uvw.v));
  729. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  730. getTextureAddressingMode(uvw.w));
  731. activateGLTextureUnit(0);
  732. }
  733. void GLRenderAPI::setTextureBorderColor(UINT16 stage, const Color& colour)
  734. {
  735. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  736. if (activateGLTextureUnit(stage))
  737. {
  738. glTexParameterfv(mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  739. activateGLTextureUnit(0);
  740. }
  741. }
  742. void GLRenderAPI::setTextureMipmapBias(UINT16 stage, float bias)
  743. {
  744. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  745. {
  746. if (activateGLTextureUnit(stage))
  747. {
  748. glTexParameterf(mTextureTypes[stage], GL_TEXTURE_LOD_BIAS, bias);
  749. activateGLTextureUnit(0);
  750. }
  751. }
  752. }
  753. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  754. {
  755. GLint sourceBlend = getBlendMode(sourceFactor);
  756. GLint destBlend = getBlendMode(destFactor);
  757. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  758. {
  759. glDisable(GL_BLEND);
  760. }
  761. else
  762. {
  763. glEnable(GL_BLEND);
  764. glBlendFunc(sourceBlend, destBlend);
  765. }
  766. GLint func = GL_FUNC_ADD;
  767. switch(op)
  768. {
  769. case BO_ADD:
  770. func = GL_FUNC_ADD;
  771. break;
  772. case BO_SUBTRACT:
  773. func = GL_FUNC_SUBTRACT;
  774. break;
  775. case BO_REVERSE_SUBTRACT:
  776. func = GL_FUNC_REVERSE_SUBTRACT;
  777. break;
  778. case BO_MIN:
  779. func = GL_MIN;
  780. break;
  781. case BO_MAX:
  782. func = GL_MAX;
  783. break;
  784. }
  785. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  786. {
  787. glBlendEquation(func);
  788. }
  789. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  790. {
  791. glBlendEquationEXT(func);
  792. }
  793. }
  794. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  795. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  796. {
  797. GLint sourceBlend = getBlendMode(sourceFactor);
  798. GLint destBlend = getBlendMode(destFactor);
  799. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  800. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  801. if(sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  802. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  803. {
  804. glDisable(GL_BLEND);
  805. }
  806. else
  807. {
  808. glEnable(GL_BLEND);
  809. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  810. }
  811. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  812. switch(op)
  813. {
  814. case BO_ADD:
  815. func = GL_FUNC_ADD;
  816. break;
  817. case BO_SUBTRACT:
  818. func = GL_FUNC_SUBTRACT;
  819. break;
  820. case BO_REVERSE_SUBTRACT:
  821. func = GL_FUNC_REVERSE_SUBTRACT;
  822. break;
  823. case BO_MIN:
  824. func = GL_MIN;
  825. break;
  826. case BO_MAX:
  827. func = GL_MAX;
  828. break;
  829. }
  830. switch(alphaOp)
  831. {
  832. case BO_ADD:
  833. alphaFunc = GL_FUNC_ADD;
  834. break;
  835. case BO_SUBTRACT:
  836. alphaFunc = GL_FUNC_SUBTRACT;
  837. break;
  838. case BO_REVERSE_SUBTRACT:
  839. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  840. break;
  841. case BO_MIN:
  842. alphaFunc = GL_MIN;
  843. break;
  844. case BO_MAX:
  845. alphaFunc = GL_MAX;
  846. break;
  847. }
  848. if(GLEW_VERSION_2_0) {
  849. glBlendEquationSeparate(func, alphaFunc);
  850. }
  851. else if(GLEW_EXT_blend_equation_separate) {
  852. glBlendEquationSeparateEXT(func, alphaFunc);
  853. }
  854. }
  855. void GLRenderAPI::setAlphaTest(CompareFunction func, unsigned char value)
  856. {
  857. if(func == CMPF_ALWAYS_PASS)
  858. {
  859. glDisable(GL_ALPHA_TEST);
  860. }
  861. else
  862. {
  863. glEnable(GL_ALPHA_TEST);
  864. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  865. }
  866. }
  867. void GLRenderAPI::setAlphaToCoverage(bool enable)
  868. {
  869. static bool lasta2c = false;
  870. if (enable != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  871. {
  872. if (enable)
  873. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  874. else
  875. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  876. lasta2c = enable;
  877. }
  878. }
  879. void GLRenderAPI::setScissorTestEnable(bool enable)
  880. {
  881. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  882. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  883. bool flipping = rtProps.requiresTextureFlipping();
  884. // GL measures from the bottom, not the top
  885. UINT32 targetHeight = rtProps.getHeight();
  886. // Calculate the "lower-left" corner of the viewport
  887. GLsizei x = 0, y = 0, w = 0, h = 0;
  888. if (enable)
  889. {
  890. glEnable(GL_SCISSOR_TEST);
  891. // GL uses width / height rather than right / bottom
  892. x = mScissorLeft;
  893. if (flipping)
  894. y = targetHeight - mScissorBottom - 1;
  895. else
  896. y = mScissorTop;
  897. w = mScissorRight - mScissorLeft;
  898. h = mScissorBottom - mScissorTop;
  899. glScissor(x, y, w, h);
  900. }
  901. else
  902. {
  903. glDisable(GL_SCISSOR_TEST);
  904. // GL requires you to reset the scissor when disabling
  905. w = mViewportWidth;
  906. h = mViewportHeight;
  907. x = mViewportLeft;
  908. y = mViewportTop;
  909. glScissor(x, y, w, h);
  910. }
  911. }
  912. void GLRenderAPI::setMultisamplingEnable(bool enable)
  913. {
  914. if (enable)
  915. glEnable(GL_MULTISAMPLE);
  916. else
  917. glDisable(GL_MULTISAMPLE);
  918. }
  919. void GLRenderAPI::setDepthClipEnable(bool enable)
  920. {
  921. if (enable)
  922. glEnable(GL_DEPTH_CLAMP);
  923. else
  924. glDisable(GL_DEPTH_CLAMP);
  925. }
  926. void GLRenderAPI::setAntialiasedLineEnable(bool enable)
  927. {
  928. if (enable)
  929. glEnable(GL_LINE_SMOOTH);
  930. else
  931. glDisable(GL_LINE_SMOOTH);
  932. }
  933. void GLRenderAPI::setCullingMode(CullingMode mode)
  934. {
  935. mCullingMode = mode;
  936. GLenum cullMode;
  937. switch( mode )
  938. {
  939. case CULL_NONE:
  940. glDisable(GL_CULL_FACE);
  941. return;
  942. default:
  943. case CULL_CLOCKWISE:
  944. cullMode = GL_FRONT;
  945. break;
  946. case CULL_COUNTERCLOCKWISE:
  947. cullMode = GL_BACK;
  948. break;
  949. }
  950. glEnable(GL_CULL_FACE);
  951. glCullFace(cullMode);
  952. }
  953. void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
  954. {
  955. if (enabled)
  956. {
  957. glClearDepth(1.0f);
  958. glEnable(GL_DEPTH_TEST);
  959. }
  960. else
  961. {
  962. glDisable(GL_DEPTH_TEST);
  963. }
  964. }
  965. void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
  966. {
  967. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  968. glDepthMask(flag);
  969. mDepthWrite = enabled;
  970. }
  971. void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
  972. {
  973. glDepthFunc(convertCompareFunction(func));
  974. }
  975. void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
  976. {
  977. if (constantBias != 0 || slopeScaleBias != 0)
  978. {
  979. glEnable(GL_POLYGON_OFFSET_FILL);
  980. glEnable(GL_POLYGON_OFFSET_POINT);
  981. glEnable(GL_POLYGON_OFFSET_LINE);
  982. float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
  983. glPolygonOffset(slopeScaleBias, scaledConstantBias);
  984. }
  985. else
  986. {
  987. glDisable(GL_POLYGON_OFFSET_FILL);
  988. glDisable(GL_POLYGON_OFFSET_POINT);
  989. glDisable(GL_POLYGON_OFFSET_LINE);
  990. }
  991. }
  992. void GLRenderAPI::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  993. {
  994. glColorMask(red, green, blue, alpha);
  995. // record this
  996. mColorWrite[0] = red;
  997. mColorWrite[1] = blue;
  998. mColorWrite[2] = green;
  999. mColorWrite[3] = alpha;
  1000. }
  1001. void GLRenderAPI::setPolygonMode(PolygonMode level)
  1002. {
  1003. GLenum glmode;
  1004. switch(level)
  1005. {
  1006. case PM_WIREFRAME:
  1007. glmode = GL_LINE;
  1008. break;
  1009. default:
  1010. case PM_SOLID:
  1011. glmode = GL_FILL;
  1012. break;
  1013. }
  1014. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1015. }
  1016. void GLRenderAPI::setStencilCheckEnabled(bool enabled)
  1017. {
  1018. if (enabled)
  1019. glEnable(GL_STENCIL_TEST);
  1020. else
  1021. glDisable(GL_STENCIL_TEST);
  1022. }
  1023. void GLRenderAPI::setStencilBufferOperations(StencilOperation stencilFailOp,
  1024. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  1025. {
  1026. if (front)
  1027. {
  1028. glStencilOpSeparate(GL_FRONT,
  1029. convertStencilOp(stencilFailOp),
  1030. convertStencilOp(depthFailOp),
  1031. convertStencilOp(passOp));
  1032. }
  1033. else
  1034. {
  1035. glStencilOpSeparate(GL_BACK,
  1036. convertStencilOp(stencilFailOp, true),
  1037. convertStencilOp(depthFailOp, true),
  1038. convertStencilOp(passOp, true));
  1039. }
  1040. }
  1041. void GLRenderAPI::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  1042. {
  1043. mStencilReadMask = mask;
  1044. if(front)
  1045. {
  1046. mStencilCompareFront = func;
  1047. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1048. }
  1049. else
  1050. {
  1051. mStencilCompareBack = func;
  1052. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1053. }
  1054. }
  1055. void GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
  1056. {
  1057. mStencilWriteMask = mask;
  1058. glStencilMask(mask);
  1059. }
  1060. void GLRenderAPI::setStencilRefValue(UINT32 refValue)
  1061. {
  1062. THROW_IF_NOT_CORE_THREAD;
  1063. mStencilRefValue = refValue;
  1064. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1065. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1066. }
  1067. void GLRenderAPI::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  1068. {
  1069. if (!activateGLTextureUnit(unit))
  1070. return;
  1071. switch(ftype)
  1072. {
  1073. case FT_MIN:
  1074. mMinFilter = fo;
  1075. // Combine with existing mip filter
  1076. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1077. break;
  1078. case FT_MAG:
  1079. switch (fo)
  1080. {
  1081. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1082. case FO_LINEAR:
  1083. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1084. break;
  1085. case FO_POINT:
  1086. case FO_NONE:
  1087. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1088. break;
  1089. default:
  1090. break;
  1091. }
  1092. break;
  1093. case FT_MIP:
  1094. mMipFilter = fo;
  1095. // Combine with existing min filter
  1096. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1097. break;
  1098. }
  1099. activateGLTextureUnit(0);
  1100. }
  1101. void GLRenderAPI::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1102. {
  1103. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1104. return;
  1105. if (!activateGLTextureUnit(unit))
  1106. return;
  1107. GLfloat largest_supported_anisotropy = 0;
  1108. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1109. if (maxAnisotropy > largest_supported_anisotropy)
  1110. maxAnisotropy = largest_supported_anisotropy ?
  1111. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1112. if(maxAnisotropy < 1)
  1113. maxAnisotropy = 1;
  1114. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1115. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1116. activateGLTextureUnit(0);
  1117. }
  1118. void GLRenderAPI::setClipPlanesImpl(const PlaneList& clipPlanes)
  1119. {
  1120. size_t i = 0;
  1121. size_t numClipPlanes;
  1122. GLdouble clipPlane[4];
  1123. numClipPlanes = clipPlanes.size();
  1124. for (i = 0; i < numClipPlanes; ++i)
  1125. {
  1126. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1127. const Plane& plane = clipPlanes[i];
  1128. if (i >= 6)
  1129. {
  1130. BS_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1131. }
  1132. clipPlane[0] = plane.normal.x;
  1133. clipPlane[1] = plane.normal.y;
  1134. clipPlane[2] = plane.normal.z;
  1135. clipPlane[3] = plane.d;
  1136. glClipPlane(clipPlaneId, clipPlane);
  1137. glEnable(clipPlaneId);
  1138. }
  1139. // Disable remaining clip planes
  1140. for (; i < 6; ++i)
  1141. {
  1142. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1143. }
  1144. }
  1145. bool GLRenderAPI::activateGLTextureUnit(UINT16 unit)
  1146. {
  1147. if (mActiveTextureUnit != unit)
  1148. {
  1149. if (unit < getCapabilities()->getNumCombinedTextureUnits())
  1150. {
  1151. glActiveTexture(GL_TEXTURE0 + unit);
  1152. mActiveTextureUnit = unit;
  1153. return true;
  1154. }
  1155. else if (!unit)
  1156. {
  1157. // always ok to use the first unit
  1158. return true;
  1159. }
  1160. else
  1161. {
  1162. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1163. ". Supported range: 0 .. " + toString(getCapabilities()->getNumCombinedTextureUnits() - 1));
  1164. return false;
  1165. }
  1166. }
  1167. else
  1168. {
  1169. return true;
  1170. }
  1171. }
  1172. void GLRenderAPI::beginDraw()
  1173. {
  1174. if(mDrawCallInProgress)
  1175. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1176. mDrawCallInProgress = true;
  1177. if(mCurrentVertexProgram == nullptr)
  1178. {
  1179. LOGWRN("Cannot render without a set vertex shader.");
  1180. return;
  1181. }
  1182. if(mBoundVertexDeclaration == nullptr)
  1183. {
  1184. LOGWRN("Cannot render without a set vertex declaration.");
  1185. return;
  1186. }
  1187. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1188. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1189. if(mActivePipeline != pipeline)
  1190. {
  1191. glBindProgramPipeline(pipeline->glHandle);
  1192. mActivePipeline = pipeline;
  1193. }
  1194. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(mCurrentVertexProgram, mBoundVertexDeclaration, mBoundVertexBuffers);
  1195. glBindVertexArray(vao.getGLHandle());
  1196. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1197. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  1198. }
  1199. void GLRenderAPI::endDraw()
  1200. {
  1201. if(!mDrawCallInProgress)
  1202. return;
  1203. mDrawCallInProgress = false;
  1204. }
  1205. GLfloat GLRenderAPI::getCurrentAnisotropy(UINT16 unit)
  1206. {
  1207. GLfloat curAniso = 0;
  1208. glGetTexParameterfv(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1209. return curAniso ? curAniso : 1;
  1210. }
  1211. GLint GLRenderAPI::convertStencilOp(StencilOperation op, bool invert) const
  1212. {
  1213. switch (op)
  1214. {
  1215. case SOP_KEEP:
  1216. return GL_KEEP;
  1217. case SOP_ZERO:
  1218. return GL_ZERO;
  1219. case SOP_REPLACE:
  1220. return GL_REPLACE;
  1221. case SOP_INCREMENT:
  1222. return invert ? GL_DECR : GL_INCR;
  1223. case SOP_DECREMENT:
  1224. return invert ? GL_INCR : GL_DECR;
  1225. case SOP_INCREMENT_WRAP:
  1226. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1227. case SOP_DECREMENT_WRAP:
  1228. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1229. case SOP_INVERT:
  1230. return GL_INVERT;
  1231. };
  1232. // to keep compiler happy
  1233. return SOP_KEEP;
  1234. }
  1235. GLint GLRenderAPI::convertCompareFunction(CompareFunction func) const
  1236. {
  1237. switch (func)
  1238. {
  1239. case CMPF_ALWAYS_FAIL:
  1240. return GL_NEVER;
  1241. case CMPF_ALWAYS_PASS:
  1242. return GL_ALWAYS;
  1243. case CMPF_LESS:
  1244. return GL_LESS;
  1245. case CMPF_LESS_EQUAL:
  1246. return GL_LEQUAL;
  1247. case CMPF_EQUAL:
  1248. return GL_EQUAL;
  1249. case CMPF_NOT_EQUAL:
  1250. return GL_NOTEQUAL;
  1251. case CMPF_GREATER_EQUAL:
  1252. return GL_GEQUAL;
  1253. case CMPF_GREATER:
  1254. return GL_GREATER;
  1255. };
  1256. return GL_ALWAYS;
  1257. }
  1258. GLuint GLRenderAPI::getCombinedMinMipFilter() const
  1259. {
  1260. switch (mMinFilter)
  1261. {
  1262. case FO_ANISOTROPIC:
  1263. case FO_LINEAR:
  1264. switch (mMipFilter)
  1265. {
  1266. case FO_ANISOTROPIC:
  1267. case FO_LINEAR:
  1268. // Linear min, linear mip
  1269. return GL_LINEAR_MIPMAP_LINEAR;
  1270. case FO_POINT:
  1271. // Linear min, point mip
  1272. return GL_LINEAR_MIPMAP_NEAREST;
  1273. case FO_NONE:
  1274. // Linear min, no mip
  1275. return GL_LINEAR;
  1276. default:
  1277. break;
  1278. }
  1279. break;
  1280. case FO_POINT:
  1281. case FO_NONE:
  1282. switch (mMipFilter)
  1283. {
  1284. case FO_ANISOTROPIC:
  1285. case FO_LINEAR:
  1286. // Nearest min, linear mip
  1287. return GL_NEAREST_MIPMAP_LINEAR;
  1288. case FO_POINT:
  1289. // Nearest min, point mip
  1290. return GL_NEAREST_MIPMAP_NEAREST;
  1291. case FO_NONE:
  1292. // Nearest min, no mip
  1293. return GL_NEAREST;
  1294. default:
  1295. break;
  1296. }
  1297. break;
  1298. default:
  1299. break;
  1300. }
  1301. // Should never get here
  1302. return 0;
  1303. }
  1304. GLint GLRenderAPI::getBlendMode(BlendFactor blendMode) const
  1305. {
  1306. switch (blendMode)
  1307. {
  1308. case BF_ONE:
  1309. return GL_ONE;
  1310. case BF_ZERO:
  1311. return GL_ZERO;
  1312. case BF_DEST_COLOR:
  1313. return GL_DST_COLOR;
  1314. case BF_SOURCE_COLOR:
  1315. return GL_SRC_COLOR;
  1316. case BF_INV_DEST_COLOR:
  1317. return GL_ONE_MINUS_DST_COLOR;
  1318. case BF_INV_SOURCE_COLOR:
  1319. return GL_ONE_MINUS_SRC_COLOR;
  1320. case BF_DEST_ALPHA:
  1321. return GL_DST_ALPHA;
  1322. case BF_SOURCE_ALPHA:
  1323. return GL_SRC_ALPHA;
  1324. case BF_INV_DEST_ALPHA:
  1325. return GL_ONE_MINUS_DST_ALPHA;
  1326. case BF_INV_SOURCE_ALPHA:
  1327. return GL_ONE_MINUS_SRC_ALPHA;
  1328. };
  1329. return GL_ONE;
  1330. }
  1331. GLint GLRenderAPI::getTextureAddressingMode(TextureAddressingMode tam) const
  1332. {
  1333. switch (tam)
  1334. {
  1335. default:
  1336. case TAM_WRAP:
  1337. return GL_REPEAT;
  1338. case TAM_MIRROR:
  1339. return GL_MIRRORED_REPEAT;
  1340. case TAM_CLAMP:
  1341. return GL_CLAMP_TO_EDGE;
  1342. case TAM_BORDER:
  1343. return GL_CLAMP_TO_BORDER;
  1344. }
  1345. }
  1346. GLint GLRenderAPI::getGLDrawMode() const
  1347. {
  1348. GLint primType;
  1349. // Use adjacency if there is a geometry program and it requested adjacency info
  1350. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1351. switch (mCurrentDrawOperation)
  1352. {
  1353. case DOT_POINT_LIST:
  1354. primType = GL_POINTS;
  1355. break;
  1356. case DOT_LINE_LIST:
  1357. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1358. break;
  1359. case DOT_LINE_STRIP:
  1360. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1361. break;
  1362. default:
  1363. case DOT_TRIANGLE_LIST:
  1364. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1365. break;
  1366. case DOT_TRIANGLE_STRIP:
  1367. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1368. break;
  1369. case DOT_TRIANGLE_FAN:
  1370. primType = GL_TRIANGLE_FAN;
  1371. break;
  1372. }
  1373. return primType;
  1374. }
  1375. UINT32 GLRenderAPI::getGLTextureUnit(GpuProgramType gptype, UINT32 unit)
  1376. {
  1377. if (gptype != GPT_VERTEX_PROGRAM && gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_GEOMETRY_PROGRAM)
  1378. {
  1379. BS_EXCEPT(InvalidParametersException, "OpenGL cannot assign textures to this gpu program type: " + toString(gptype));
  1380. }
  1381. UINT32 numSupportedUnits = mCurrentCapabilities->getNumTextureUnits(gptype);
  1382. if (unit >= numSupportedUnits)
  1383. {
  1384. BS_EXCEPT(InvalidParametersException, "Invalid texture unit index for the provided stage. Unit index: " + toString(unit) + ". Stage: " +
  1385. toString(gptype) + ". Supported range is 0 .. " + toString(numSupportedUnits - 1));
  1386. }
  1387. switch (gptype)
  1388. {
  1389. case GPT_FRAGMENT_PROGRAM:
  1390. return mFragmentTexOffset + unit;
  1391. case GPT_VERTEX_PROGRAM:
  1392. return mVertexTexOffset + unit;
  1393. case GPT_GEOMETRY_PROGRAM:
  1394. return mGeometryTexOffset + unit;
  1395. default:
  1396. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1397. }
  1398. return 0;
  1399. }
  1400. UINT32 GLRenderAPI::getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding)
  1401. {
  1402. UINT32 maxNumBindings = mCurrentCapabilities->getNumGpuParamBlockBuffers(gptype);
  1403. if (binding >= maxNumBindings)
  1404. {
  1405. BS_EXCEPT(InvalidParametersException, "Invalid buffer binding for the provided stage. Buffer binding: " + toString(binding) + ". Stage: " +
  1406. toString(gptype) + ". Supported range is 0 .. " + toString(maxNumBindings - 1));
  1407. }
  1408. switch (gptype)
  1409. {
  1410. case GPT_FRAGMENT_PROGRAM:
  1411. return mFragmentUBOffset + binding;
  1412. case GPT_VERTEX_PROGRAM:
  1413. return mVertexUBOffset + binding;
  1414. case GPT_GEOMETRY_PROGRAM:
  1415. return mGeometryUBOffset + binding;
  1416. case GPT_HULL_PROGRAM:
  1417. return mHullUBOffset + binding;
  1418. case GPT_DOMAIN_PROGRAM:
  1419. return mDomainUBOffset + binding;
  1420. case GPT_COMPUTE_PROGRAM:
  1421. return mComputeUBOffset + binding;
  1422. default:
  1423. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1424. }
  1425. return 0;
  1426. }
  1427. void GLRenderAPI::setActiveProgram(GpuProgramType gptype, const SPtr<GLSLGpuProgramCore>& program)
  1428. {
  1429. switch (gptype)
  1430. {
  1431. case GPT_VERTEX_PROGRAM:
  1432. mCurrentVertexProgram = program;
  1433. break;
  1434. case GPT_FRAGMENT_PROGRAM:
  1435. mCurrentFragmentProgram = program;
  1436. break;
  1437. case GPT_GEOMETRY_PROGRAM:
  1438. mCurrentGeometryProgram = program;
  1439. break;
  1440. case GPT_DOMAIN_PROGRAM:
  1441. mCurrentDomainProgram = program;
  1442. break;
  1443. case GPT_HULL_PROGRAM:
  1444. mCurrentHullProgram = program;
  1445. break;
  1446. case GPT_COMPUTE_PROGRAM:
  1447. mCurrentComputeProgram = program;
  1448. break;
  1449. }
  1450. }
  1451. SPtr<GLSLGpuProgramCore> GLRenderAPI::getActiveProgram(GpuProgramType gptype) const
  1452. {
  1453. switch (gptype)
  1454. {
  1455. case GPT_VERTEX_PROGRAM:
  1456. return mCurrentVertexProgram;
  1457. case GPT_FRAGMENT_PROGRAM:
  1458. return mCurrentFragmentProgram;
  1459. case GPT_GEOMETRY_PROGRAM:
  1460. return mCurrentGeometryProgram;
  1461. case GPT_DOMAIN_PROGRAM:
  1462. return mCurrentDomainProgram;
  1463. case GPT_HULL_PROGRAM:
  1464. return mCurrentHullProgram;
  1465. case GPT_COMPUTE_PROGRAM:
  1466. return mCurrentComputeProgram;
  1467. default:
  1468. BS_EXCEPT(InvalidParametersException, "Insupported gpu program type: " + toString(gptype));
  1469. }
  1470. return nullptr;
  1471. }
  1472. void GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
  1473. {
  1474. if(caps->getRenderAPIName() != getName())
  1475. {
  1476. BS_EXCEPT(InvalidParametersException,
  1477. "Trying to initialize GLRenderAPI from RenderSystemCapabilities that do not support OpenGL");
  1478. }
  1479. #if BS_DEBUG_MODE
  1480. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  1481. {
  1482. glDebugMessageCallback(&openGlErrorCallback, 0);
  1483. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  1484. }
  1485. #endif
  1486. HardwareBufferManager::startUp();
  1487. HardwareBufferCoreManager::startUp<GLHardwareBufferCoreManager>();
  1488. // GPU Program Manager setup
  1489. if(caps->isShaderProfileSupported("glsl"))
  1490. {
  1491. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  1492. GpuProgramCoreManager::instance().addFactory(mGLSLProgramFactory);
  1493. }
  1494. // Check for framebuffer object extension
  1495. if(caps->hasCapability(RSC_FBO))
  1496. {
  1497. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  1498. {
  1499. // Create FBO manager
  1500. GLRTTManager::startUp<GLRTTManager>();
  1501. }
  1502. }
  1503. else
  1504. {
  1505. BS_EXCEPT(RenderingAPIException, "GPU doesn't support frame buffer objects. OpenGL versions lower than 3.0 are not supported.");
  1506. }
  1507. mFragmentTexOffset = 0;
  1508. mVertexTexOffset = caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1509. mGeometryTexOffset = mVertexTexOffset + caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1510. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  1511. UINT32 totalNumTexUnits = caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1512. totalNumTexUnits += caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1513. totalNumTexUnits += caps->getNumTextureUnits(GPT_GEOMETRY_PROGRAM);
  1514. totalNumTexUnits += caps->getNumTextureUnits(GPT_HULL_PROGRAM);
  1515. totalNumTexUnits += caps->getNumTextureUnits(GPT_DOMAIN_PROGRAM);
  1516. totalNumTexUnits += caps->getNumTextureUnits(GPT_COMPUTE_PROGRAM);
  1517. if(totalNumTexUnits > numCombinedTexUnits)
  1518. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  1519. mNumTextureTypes = numCombinedTexUnits;
  1520. mTextureTypes = bs_newN<GLenum>(mNumTextureTypes);
  1521. for(UINT16 i = 0; i < numCombinedTexUnits; i++)
  1522. mTextureTypes[i] = GL_TEXTURE_2D;
  1523. mVertexUBOffset = 0;
  1524. UINT32 totalNumUniformBlocks = caps->getNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM);
  1525. mFragmentUBOffset = totalNumUniformBlocks;
  1526. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM);
  1527. mGeometryUBOffset = totalNumUniformBlocks;
  1528. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM);
  1529. mHullUBOffset = totalNumUniformBlocks;
  1530. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_HULL_PROGRAM);
  1531. mDomainUBOffset = totalNumUniformBlocks;
  1532. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM);
  1533. mComputeUBOffset = totalNumUniformBlocks;
  1534. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM);
  1535. UINT16 numCombinedUniformBlocks = caps->getNumCombinedGpuParamBlockBuffers();
  1536. if(totalNumUniformBlocks > numCombinedUniformBlocks)
  1537. BS_EXCEPT(InternalErrorException, "Number of combined uniform block buffers less than the number of individual per-stage buffers!?");
  1538. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  1539. TextureCoreManager::startUp<GLTextureCoreManager>(std::ref(*mGLSupport));
  1540. }
  1541. void GLRenderAPI::switchContext(const SPtr<GLContext>& context)
  1542. {
  1543. // Unbind GPU programs and rebind to new context later, because
  1544. // scene manager treat render system as ONE 'context' ONLY, and it
  1545. // cached the GPU programs using state.
  1546. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1547. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1548. unbindGpuProgram(GPT_GEOMETRY_PROGRAM);
  1549. unbindGpuProgram(GPT_HULL_PROGRAM);
  1550. unbindGpuProgram(GPT_DOMAIN_PROGRAM);
  1551. unbindGpuProgram(GPT_COMPUTE_PROGRAM);
  1552. // It's ready for switching
  1553. if (mCurrentContext)
  1554. mCurrentContext->endCurrent();
  1555. mCurrentContext = context;
  1556. mCurrentContext->setCurrent();
  1557. // Must reset depth/colour write mask to according with user desired, otherwise,
  1558. // clearFrameBuffer would be wrong because the value we are recorded may be
  1559. // difference with the really state stored in GL context.
  1560. glDepthMask(mDepthWrite);
  1561. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1562. glStencilMask(mStencilWriteMask);
  1563. }
  1564. RenderAPICapabilities* GLRenderAPI::createRenderSystemCapabilities() const
  1565. {
  1566. RenderAPICapabilities* rsc = bs_new<RenderAPICapabilities>();
  1567. rsc->setDriverVersion(mDriverVersion);
  1568. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  1569. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  1570. rsc->setDeviceName(deviceName);
  1571. rsc->setRenderAPIName(getName());
  1572. // determine vendor
  1573. if (strstr(vendorName, "NVIDIA"))
  1574. rsc->setVendor(GPU_NVIDIA);
  1575. else if (strstr(vendorName, "ATI"))
  1576. rsc->setVendor(GPU_AMD);
  1577. else if (strstr(vendorName, "AMD"))
  1578. rsc->setVendor(GPU_AMD);
  1579. else if (strstr(vendorName, "Intel"))
  1580. rsc->setVendor(GPU_INTEL);
  1581. else
  1582. rsc->setVendor(GPU_UNKNOWN);
  1583. // Check for hardware mipmapping support.
  1584. if(GLEW_VERSION_1_4)
  1585. {
  1586. rsc->setCapability(RSC_AUTOMIPMAP);
  1587. }
  1588. // Check for Anisotropy support
  1589. if (getGLSupport()->checkExtension("GL_EXT_texture_filter_anisotropic"))
  1590. {
  1591. rsc->setCapability(RSC_ANISOTROPY);
  1592. }
  1593. // Check for cube mapping
  1594. if(GLEW_VERSION_1_3 ||
  1595. getGLSupport()->checkExtension("GL_ARB_texture_cube_map") ||
  1596. getGLSupport()->checkExtension("GL_EXT_texture_cube_map"))
  1597. {
  1598. rsc->setCapability(RSC_CUBEMAPPING);
  1599. }
  1600. // Point sprites
  1601. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_ARB_point_sprite"))
  1602. {
  1603. rsc->setCapability(RSC_POINT_SPRITES);
  1604. }
  1605. // Check for hardware stencil support and set bit depth
  1606. GLint stencil;
  1607. glGetIntegerv(GL_STENCIL_BITS, &stencil);
  1608. if(stencil)
  1609. {
  1610. rsc->setStencilBufferBitDepth(stencil);
  1611. }
  1612. if (GLEW_VERSION_2_0 ||
  1613. (getGLSupport()->checkExtension("GL_ARB_shading_language_100") &&
  1614. getGLSupport()->checkExtension("GL_ARB_shader_objects") &&
  1615. getGLSupport()->checkExtension("GL_ARB_fragment_shader") &&
  1616. getGLSupport()->checkExtension("GL_ARB_vertex_shader")))
  1617. {
  1618. rsc->addShaderProfile("glsl");
  1619. }
  1620. // Check if geometry shaders are supported
  1621. if (GLEW_VERSION_2_0 &&
  1622. getGLSupport()->checkExtension("GL_EXT_geometry_shader4"))
  1623. {
  1624. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  1625. rsc->setGeometryProgramConstantBoolCount(0);
  1626. rsc->setGeometryProgramConstantIntCount(0);
  1627. GLint floatConstantCount = 0;
  1628. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  1629. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  1630. GLint maxOutputVertices;
  1631. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  1632. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  1633. }
  1634. //Check if render to vertex buffer (transform feedback in OpenGL)
  1635. if (GLEW_VERSION_2_0 && getGLSupport()->checkExtension("GL_EXT_transform_feedback"))
  1636. {
  1637. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  1638. }
  1639. // Check for texture compression
  1640. if (GLEW_VERSION_1_3 || getGLSupport()->checkExtension("GL_ARB_texture_compression"))
  1641. {
  1642. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1643. // Check for dxt compression
  1644. if (getGLSupport()->checkExtension("GL_EXT_texture_compression_s3tc"))
  1645. {
  1646. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1647. }
  1648. // Check for vtc compression
  1649. if (getGLSupport()->checkExtension("GL_NV_texture_compression_vtc"))
  1650. {
  1651. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  1652. }
  1653. }
  1654. // As are user clipping planes
  1655. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1656. // 2-sided stencil?
  1657. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_EXT_stencil_two_side"))
  1658. {
  1659. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1660. }
  1661. // stencil wrapping?
  1662. if (GLEW_VERSION_1_4 || getGLSupport()->checkExtension("GL_EXT_stencil_wrap"))
  1663. {
  1664. rsc->setCapability(RSC_STENCIL_WRAP);
  1665. }
  1666. // Check for hardware occlusion support
  1667. if (GLEW_VERSION_1_5 || getGLSupport()->checkExtension("GL_ARB_occlusion_query"))
  1668. {
  1669. rsc->setCapability(RSC_HWOCCLUSION);
  1670. }
  1671. // UBYTE4 always supported
  1672. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1673. // Infinite far plane always supported
  1674. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1675. // Check for non-power-of-2 texture support
  1676. if (getGLSupport()->checkExtension("GL_ARB_texture_non_power_of_two"))
  1677. {
  1678. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1679. }
  1680. // Check for Float textures
  1681. if (getGLSupport()->checkExtension("GL_ATI_texture_float") || getGLSupport()->checkExtension("GL_ARB_texture_float"))
  1682. {
  1683. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1684. }
  1685. // 3D textures should always be supported
  1686. rsc->setCapability(RSC_TEXTURE_3D);
  1687. // Check for framebuffer object extension
  1688. if (getGLSupport()->checkExtension("GL_ARB_framebuffer_object"))
  1689. {
  1690. // Probe number of draw buffers
  1691. // Only makes sense with FBO support, so probe here
  1692. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_ARB_draw_buffers") || getGLSupport()->checkExtension("GL_ATI_draw_buffers"))
  1693. {
  1694. GLint buffers;
  1695. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  1696. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)BS_MAX_MULTIPLE_RENDER_TARGETS));
  1697. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1698. rsc->setCapability(RSC_FBO);
  1699. }
  1700. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1701. }
  1702. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1703. rsc->setCapability(RSC_PBUFFER);
  1704. // Point size
  1705. float ps;
  1706. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  1707. rsc->setMaxPointSize(ps);
  1708. // Max number of fragment shader textures
  1709. GLint units;
  1710. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  1711. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  1712. // Max number of vertex shader textures
  1713. GLint vUnits;
  1714. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  1715. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  1716. if (vUnits > 0)
  1717. {
  1718. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1719. }
  1720. GLint numUniformBlocks;
  1721. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  1722. rsc->setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  1723. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  1724. rsc->setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  1725. if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
  1726. {
  1727. GLint geomUnits;
  1728. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  1729. rsc->setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  1730. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  1731. rsc->setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  1732. }
  1733. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  1734. {
  1735. rsc->setCapability(RSC_TESSELLATION_PROGRAM);
  1736. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  1737. rsc->setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  1738. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  1739. rsc->setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  1740. }
  1741. if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
  1742. {
  1743. rsc->setCapability(RSC_COMPUTE_PROGRAM);
  1744. GLint computeUnits;
  1745. glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  1746. rsc->setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  1747. glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  1748. rsc->setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  1749. }
  1750. GLint combinedTexUnits;
  1751. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  1752. rsc->setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  1753. GLint combinedUniformBlockUnits;
  1754. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  1755. rsc->setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  1756. // Mipmap LOD biasing
  1757. if (mGLSupport->checkExtension("GL_EXT_texture_lod_bias"))
  1758. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1759. // Alpha to coverage?
  1760. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  1761. {
  1762. // Alpha to coverage always 'supported' when MSAA is available
  1763. // although card may ignore it if it doesn't specifically support A2C
  1764. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1765. }
  1766. // Advanced blending operations
  1767. if(GLEW_VERSION_2_0)
  1768. {
  1769. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1770. }
  1771. return rsc;
  1772. }
  1773. bool GLRenderAPI::checkForErrors() const
  1774. {
  1775. GLenum glErr = glGetError();
  1776. bool errorsFound = false;
  1777. String msg;
  1778. while (glErr != GL_NO_ERROR)
  1779. {
  1780. const char* glerrStr = (const char*)gluErrorString(glErr);
  1781. if (glerrStr)
  1782. {
  1783. msg += String(glerrStr);
  1784. }
  1785. glErr = glGetError();
  1786. errorsFound = true;
  1787. }
  1788. if (errorsFound)
  1789. LOGWRN("OpenGL error: " + msg);
  1790. return errorsFound;
  1791. }
  1792. void GLRenderAPI::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  1793. {
  1794. UINT32 x = 0;
  1795. for (UINT32 i = 0; i < 4; i++)
  1796. {
  1797. for (UINT32 j = 0; j < 4; j++)
  1798. {
  1799. gl_matrix[x] = m[j][i];
  1800. x++;
  1801. }
  1802. }
  1803. }
  1804. void GLRenderAPI::applyViewport()
  1805. {
  1806. if (mActiveRenderTarget == nullptr)
  1807. return;
  1808. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1809. // Calculate the "lower-left" corner of the viewport
  1810. mViewportLeft = (UINT32)(rtProps.getWidth() * mViewportNorm.x);
  1811. mViewportTop = (UINT32)(rtProps.getHeight() * mViewportNorm.y);
  1812. mViewportWidth = (UINT32)(rtProps.getWidth() * mViewportNorm.width);
  1813. mViewportHeight = (UINT32)(rtProps.getHeight() * mViewportNorm.height);
  1814. if (rtProps.requiresTextureFlipping())
  1815. {
  1816. // Convert "upper-left" corner to "lower-left"
  1817. mViewportTop = rtProps.getHeight() - (mViewportTop + mViewportHeight) - 1;
  1818. }
  1819. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1820. // Configure the viewport clipping
  1821. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1822. }
  1823. /************************************************************************/
  1824. /* UTILITY */
  1825. /************************************************************************/
  1826. void GLRenderAPI::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  1827. {
  1828. dest = matrix;
  1829. }
  1830. const RenderAPIInfo& GLRenderAPI::getAPIInfo() const
  1831. {
  1832. static RenderAPIInfo info(0.0f, 0.0f, -1.0f, 1.0f, VET_COLOR_ABGR, false, false, true);
  1833. return info;
  1834. }
  1835. GpuParamBlockDesc GLRenderAPI::generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params)
  1836. {
  1837. GpuParamBlockDesc block;
  1838. block.blockSize = 0;
  1839. block.isShareable = true;
  1840. block.name = name;
  1841. block.slot = 0;
  1842. for (auto& param : params)
  1843. {
  1844. const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[param.type];
  1845. UINT32 size = typeInfo.size / 4;
  1846. UINT32 alignment = typeInfo.alignment / 4;
  1847. // Fix alignment if needed
  1848. UINT32 alignOffset = block.blockSize % alignment;
  1849. if (alignOffset != 0)
  1850. {
  1851. UINT32 padding = (alignment - alignOffset);
  1852. block.blockSize += padding;
  1853. }
  1854. if (param.arraySize > 1)
  1855. {
  1856. // Array elements are always padded and aligned to vec4
  1857. alignOffset = size % typeInfo.baseTypeSize;
  1858. if (alignOffset != 0)
  1859. {
  1860. UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
  1861. size += padding;
  1862. }
  1863. alignOffset = block.blockSize % typeInfo.baseTypeSize;
  1864. if (alignOffset != 0)
  1865. {
  1866. UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
  1867. block.blockSize += padding;
  1868. }
  1869. param.elementSize = size;
  1870. param.arrayElementStride = size;
  1871. param.cpuMemOffset = block.blockSize;
  1872. param.gpuMemOffset = 0;
  1873. block.blockSize += size * param.arraySize;
  1874. }
  1875. else
  1876. {
  1877. param.elementSize = size;
  1878. param.arrayElementStride = size;
  1879. param.cpuMemOffset = block.blockSize;
  1880. param.gpuMemOffset = 0;
  1881. block.blockSize += size;
  1882. }
  1883. param.paramBlockSlot = 0;
  1884. }
  1885. // Constant buffer size must always be a multiple of 16
  1886. if (block.blockSize % 4 != 0)
  1887. block.blockSize += (4 - (block.blockSize % 4));
  1888. return block;
  1889. }
  1890. void __stdcall openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam)
  1891. {
  1892. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  1893. {
  1894. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  1895. }
  1896. }
  1897. }