BsGLRenderAPI.cpp 59 KB

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