BsGLRenderAPI.cpp 64 KB

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