2
0

BsGLRenderAPI.cpp 62 KB

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