BsGLRenderSystem.cpp 57 KB

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