2
0

BsGLRenderAPI.cpp 63 KB

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