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. mDepthWrite = enabled;
  897. }
  898. void GLRenderSystem::setDepthBufferFunction(CompareFunction func)
  899. {
  900. glDepthFunc(convertCompareFunction(func));
  901. }
  902. void GLRenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  903. {
  904. if (constantBias != 0 || slopeScaleBias != 0)
  905. {
  906. glEnable(GL_POLYGON_OFFSET_FILL);
  907. glEnable(GL_POLYGON_OFFSET_POINT);
  908. glEnable(GL_POLYGON_OFFSET_LINE);
  909. glPolygonOffset(-slopeScaleBias, -constantBias);
  910. }
  911. else
  912. {
  913. glDisable(GL_POLYGON_OFFSET_FILL);
  914. glDisable(GL_POLYGON_OFFSET_POINT);
  915. glDisable(GL_POLYGON_OFFSET_LINE);
  916. }
  917. }
  918. void GLRenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  919. {
  920. glColorMask(red, green, blue, alpha);
  921. // record this
  922. mColorWrite[0] = red;
  923. mColorWrite[1] = blue;
  924. mColorWrite[2] = green;
  925. mColorWrite[3] = alpha;
  926. }
  927. void GLRenderSystem::setPolygonMode(PolygonMode level)
  928. {
  929. GLenum glmode;
  930. switch(level)
  931. {
  932. case PM_WIREFRAME:
  933. glmode = GL_LINE;
  934. break;
  935. default:
  936. case PM_SOLID:
  937. glmode = GL_FILL;
  938. break;
  939. }
  940. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  941. }
  942. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  943. {
  944. if (enabled)
  945. glEnable(GL_STENCIL_TEST);
  946. else
  947. glDisable(GL_STENCIL_TEST);
  948. }
  949. void GLRenderSystem::setStencilBufferOperations(StencilOperation stencilFailOp,
  950. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  951. {
  952. if (front)
  953. {
  954. glStencilOpSeparate(GL_FRONT,
  955. convertStencilOp(stencilFailOp),
  956. convertStencilOp(depthFailOp),
  957. convertStencilOp(passOp));
  958. }
  959. else
  960. {
  961. glStencilOpSeparate(GL_BACK,
  962. convertStencilOp(stencilFailOp, true),
  963. convertStencilOp(depthFailOp, true),
  964. convertStencilOp(passOp, true));
  965. }
  966. }
  967. void GLRenderSystem::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  968. {
  969. mStencilReadMask = mask;
  970. if(front)
  971. {
  972. mStencilCompareFront = func;
  973. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  974. }
  975. else
  976. {
  977. mStencilCompareBack = func;
  978. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  979. }
  980. }
  981. void GLRenderSystem::setStencilBufferWriteMask(UINT32 mask)
  982. {
  983. mStencilWriteMask = mask;
  984. glStencilMask(mask);
  985. }
  986. void GLRenderSystem::setStencilRefValue(UINT32 refValue)
  987. {
  988. THROW_IF_NOT_CORE_THREAD;
  989. mStencilRefValue = refValue;
  990. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  991. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  992. }
  993. void GLRenderSystem::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  994. {
  995. if (!activateGLTextureUnit(unit))
  996. return;
  997. switch(ftype)
  998. {
  999. case FT_MIN:
  1000. mMinFilter = fo;
  1001. // Combine with existing mip filter
  1002. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1003. break;
  1004. case FT_MAG:
  1005. switch (fo)
  1006. {
  1007. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1008. case FO_LINEAR:
  1009. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1010. break;
  1011. case FO_POINT:
  1012. case FO_NONE:
  1013. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1014. break;
  1015. }
  1016. break;
  1017. case FT_MIP:
  1018. mMipFilter = fo;
  1019. // Combine with existing min filter
  1020. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1021. break;
  1022. }
  1023. activateGLTextureUnit(0);
  1024. }
  1025. void GLRenderSystem::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1026. {
  1027. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1028. return;
  1029. if (!activateGLTextureUnit(unit))
  1030. return;
  1031. GLfloat largest_supported_anisotropy = 0;
  1032. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1033. if (maxAnisotropy > largest_supported_anisotropy)
  1034. maxAnisotropy = largest_supported_anisotropy ?
  1035. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1036. if(maxAnisotropy < 1)
  1037. maxAnisotropy = 1;
  1038. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1039. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1040. activateGLTextureUnit(0);
  1041. }
  1042. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1043. {
  1044. size_t i = 0;
  1045. size_t numClipPlanes;
  1046. GLdouble clipPlane[4];
  1047. numClipPlanes = clipPlanes.size();
  1048. for (i = 0; i < numClipPlanes; ++i)
  1049. {
  1050. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1051. const Plane& plane = clipPlanes[i];
  1052. if (i >= 6)
  1053. {
  1054. BS_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1055. }
  1056. clipPlane[0] = plane.normal.x;
  1057. clipPlane[1] = plane.normal.y;
  1058. clipPlane[2] = plane.normal.z;
  1059. clipPlane[3] = plane.d;
  1060. glClipPlane(clipPlaneId, clipPlane);
  1061. glEnable(clipPlaneId);
  1062. }
  1063. // Disable remaining clip planes
  1064. for (; i < 6; ++i)
  1065. {
  1066. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1067. }
  1068. }
  1069. bool GLRenderSystem::activateGLTextureUnit(UINT16 unit)
  1070. {
  1071. if (mActiveTextureUnit != unit)
  1072. {
  1073. if (unit < getCapabilities()->getNumCombinedTextureUnits())
  1074. {
  1075. glActiveTexture(GL_TEXTURE0 + unit);
  1076. mActiveTextureUnit = unit;
  1077. return true;
  1078. }
  1079. else if (!unit)
  1080. {
  1081. // always ok to use the first unit
  1082. return true;
  1083. }
  1084. else
  1085. {
  1086. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1087. ". Supported range: 0 .. " + toString(getCapabilities()->getNumCombinedTextureUnits() - 1));
  1088. return false;
  1089. }
  1090. }
  1091. else
  1092. {
  1093. return true;
  1094. }
  1095. }
  1096. void GLRenderSystem::beginDraw()
  1097. {
  1098. if(mDrawCallInProgress)
  1099. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1100. mDrawCallInProgress = true;
  1101. if(mCurrentVertexProgram == nullptr)
  1102. {
  1103. LOGWRN("Cannot render without a set vertex shader.");
  1104. return;
  1105. }
  1106. if(mBoundVertexDeclaration == nullptr)
  1107. {
  1108. LOGWRN("Cannot render without a set vertex declaration.");
  1109. return;
  1110. }
  1111. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1112. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1113. if(mActivePipeline != pipeline)
  1114. {
  1115. glBindProgramPipeline(pipeline->glHandle);
  1116. mActivePipeline = pipeline;
  1117. }
  1118. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(mCurrentVertexProgram, mBoundVertexDeclaration, mBoundVertexBuffers);
  1119. glBindVertexArray(vao.getGLHandle());
  1120. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1121. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  1122. }
  1123. void GLRenderSystem::endDraw()
  1124. {
  1125. if(!mDrawCallInProgress)
  1126. return;
  1127. mDrawCallInProgress = false;
  1128. }
  1129. GLfloat GLRenderSystem::getCurrentAnisotropy(UINT16 unit)
  1130. {
  1131. GLfloat curAniso = 0;
  1132. glGetTexParameterfv(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1133. return curAniso ? curAniso : 1;
  1134. }
  1135. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1136. {
  1137. switch (op)
  1138. {
  1139. case SOP_KEEP:
  1140. return GL_KEEP;
  1141. case SOP_ZERO:
  1142. return GL_ZERO;
  1143. case SOP_REPLACE:
  1144. return GL_REPLACE;
  1145. case SOP_INCREMENT:
  1146. return invert ? GL_DECR : GL_INCR;
  1147. case SOP_DECREMENT:
  1148. return invert ? GL_INCR : GL_DECR;
  1149. case SOP_INCREMENT_WRAP:
  1150. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1151. case SOP_DECREMENT_WRAP:
  1152. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1153. case SOP_INVERT:
  1154. return GL_INVERT;
  1155. };
  1156. // to keep compiler happy
  1157. return SOP_KEEP;
  1158. }
  1159. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1160. {
  1161. switch (func)
  1162. {
  1163. case CMPF_ALWAYS_FAIL:
  1164. return GL_NEVER;
  1165. case CMPF_ALWAYS_PASS:
  1166. return GL_ALWAYS;
  1167. case CMPF_LESS:
  1168. return GL_LESS;
  1169. case CMPF_LESS_EQUAL:
  1170. return GL_LEQUAL;
  1171. case CMPF_EQUAL:
  1172. return GL_EQUAL;
  1173. case CMPF_NOT_EQUAL:
  1174. return GL_NOTEQUAL;
  1175. case CMPF_GREATER_EQUAL:
  1176. return GL_GEQUAL;
  1177. case CMPF_GREATER:
  1178. return GL_GREATER;
  1179. };
  1180. return GL_ALWAYS;
  1181. }
  1182. GLuint GLRenderSystem::getCombinedMinMipFilter() const
  1183. {
  1184. switch (mMinFilter)
  1185. {
  1186. case FO_ANISOTROPIC:
  1187. case FO_LINEAR:
  1188. switch (mMipFilter)
  1189. {
  1190. case FO_ANISOTROPIC:
  1191. case FO_LINEAR:
  1192. // Linear min, linear mip
  1193. return GL_LINEAR_MIPMAP_LINEAR;
  1194. case FO_POINT:
  1195. // Linear min, point mip
  1196. return GL_LINEAR_MIPMAP_NEAREST;
  1197. case FO_NONE:
  1198. // Linear min, no mip
  1199. return GL_LINEAR;
  1200. }
  1201. break;
  1202. case FO_POINT:
  1203. case FO_NONE:
  1204. switch (mMipFilter)
  1205. {
  1206. case FO_ANISOTROPIC:
  1207. case FO_LINEAR:
  1208. // Nearest min, linear mip
  1209. return GL_NEAREST_MIPMAP_LINEAR;
  1210. case FO_POINT:
  1211. // Nearest min, point mip
  1212. return GL_NEAREST_MIPMAP_NEAREST;
  1213. case FO_NONE:
  1214. // Nearest min, no mip
  1215. return GL_NEAREST;
  1216. }
  1217. break;
  1218. }
  1219. // Should never get here
  1220. return 0;
  1221. }
  1222. GLint GLRenderSystem::getBlendMode(BlendFactor blendMode) const
  1223. {
  1224. switch (blendMode)
  1225. {
  1226. case BF_ONE:
  1227. return GL_ONE;
  1228. case BF_ZERO:
  1229. return GL_ZERO;
  1230. case BF_DEST_COLOR:
  1231. return GL_DST_COLOR;
  1232. case BF_SOURCE_COLOR:
  1233. return GL_SRC_COLOR;
  1234. case BF_INV_DEST_COLOR:
  1235. return GL_ONE_MINUS_DST_COLOR;
  1236. case BF_INV_SOURCE_COLOR:
  1237. return GL_ONE_MINUS_SRC_COLOR;
  1238. case BF_DEST_ALPHA:
  1239. return GL_DST_ALPHA;
  1240. case BF_SOURCE_ALPHA:
  1241. return GL_SRC_ALPHA;
  1242. case BF_INV_DEST_ALPHA:
  1243. return GL_ONE_MINUS_DST_ALPHA;
  1244. case BF_INV_SOURCE_ALPHA:
  1245. return GL_ONE_MINUS_SRC_ALPHA;
  1246. };
  1247. return GL_ONE;
  1248. }
  1249. GLint GLRenderSystem::getTextureAddressingMode(TextureAddressingMode tam) const
  1250. {
  1251. switch (tam)
  1252. {
  1253. default:
  1254. case TAM_WRAP:
  1255. return GL_REPEAT;
  1256. case TAM_MIRROR:
  1257. return GL_MIRRORED_REPEAT;
  1258. case TAM_CLAMP:
  1259. return GL_CLAMP_TO_EDGE;
  1260. case TAM_BORDER:
  1261. return GL_CLAMP_TO_BORDER;
  1262. }
  1263. }
  1264. GLint GLRenderSystem::getGLDrawMode() const
  1265. {
  1266. GLint primType;
  1267. // Use adjacency if there is a geometry program and it requested adjacency info
  1268. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1269. switch (mCurrentDrawOperation)
  1270. {
  1271. case DOT_POINT_LIST:
  1272. primType = GL_POINTS;
  1273. break;
  1274. case DOT_LINE_LIST:
  1275. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1276. break;
  1277. case DOT_LINE_STRIP:
  1278. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1279. break;
  1280. default:
  1281. case DOT_TRIANGLE_LIST:
  1282. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1283. break;
  1284. case DOT_TRIANGLE_STRIP:
  1285. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1286. break;
  1287. case DOT_TRIANGLE_FAN:
  1288. primType = GL_TRIANGLE_FAN;
  1289. break;
  1290. }
  1291. return primType;
  1292. }
  1293. UINT32 GLRenderSystem::getGLTextureUnit(GpuProgramType gptype, UINT32 unit)
  1294. {
  1295. if (gptype != GPT_VERTEX_PROGRAM && gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_GEOMETRY_PROGRAM)
  1296. {
  1297. BS_EXCEPT(InvalidParametersException, "OpenGL cannot assign textures to this gpu program type: " + toString(gptype));
  1298. }
  1299. UINT32 numSupportedUnits = mCurrentCapabilities->getNumTextureUnits(gptype);
  1300. if (unit < 0 || unit >= numSupportedUnits)
  1301. {
  1302. BS_EXCEPT(InvalidParametersException, "Invalid texture unit index for the provided stage. Unit index: " + toString(unit) + ". Stage: " +
  1303. toString(gptype) + ". Supported range is 0 .. " + toString(numSupportedUnits - 1));
  1304. }
  1305. switch (gptype)
  1306. {
  1307. case GPT_FRAGMENT_PROGRAM:
  1308. return mFragmentTexOffset + unit;
  1309. case GPT_VERTEX_PROGRAM:
  1310. return mVertexTexOffset + unit;
  1311. case GPT_GEOMETRY_PROGRAM:
  1312. return mGeometryTexOffset + unit;
  1313. default:
  1314. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1315. }
  1316. }
  1317. UINT32 GLRenderSystem::getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding)
  1318. {
  1319. UINT32 maxNumBindings = mCurrentCapabilities->getNumGpuParamBlockBuffers(gptype);
  1320. if (binding < 0 || binding >= maxNumBindings)
  1321. {
  1322. BS_EXCEPT(InvalidParametersException, "Invalid buffer binding for the provided stage. Buffer binding: " + toString(binding) + ". Stage: " +
  1323. toString(gptype) + ". Supported range is 0 .. " + toString(maxNumBindings - 1));
  1324. }
  1325. switch (gptype)
  1326. {
  1327. case GPT_FRAGMENT_PROGRAM:
  1328. return mFragmentUBOffset + binding;
  1329. case GPT_VERTEX_PROGRAM:
  1330. return mVertexUBOffset + binding;
  1331. case GPT_GEOMETRY_PROGRAM:
  1332. return mGeometryUBOffset + binding;
  1333. case GPT_HULL_PROGRAM:
  1334. return mHullUBOffset + binding;
  1335. case GPT_DOMAIN_PROGRAM:
  1336. return mDomainUBOffset + binding;
  1337. case GPT_COMPUTE_PROGRAM:
  1338. return mComputeUBOffset + binding;
  1339. default:
  1340. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1341. }
  1342. }
  1343. void GLRenderSystem::setActiveProgram(GpuProgramType gptype, GLSLGpuProgramPtr program)
  1344. {
  1345. switch (gptype)
  1346. {
  1347. case GPT_VERTEX_PROGRAM:
  1348. mCurrentVertexProgram = program;
  1349. break;
  1350. case GPT_FRAGMENT_PROGRAM:
  1351. mCurrentFragmentProgram = program;
  1352. break;
  1353. case GPT_GEOMETRY_PROGRAM:
  1354. mCurrentGeometryProgram = program;
  1355. break;
  1356. case GPT_DOMAIN_PROGRAM:
  1357. mCurrentDomainProgram = program;
  1358. break;
  1359. case GPT_HULL_PROGRAM:
  1360. mCurrentHullProgram = program;
  1361. break;
  1362. }
  1363. }
  1364. GLSLGpuProgramPtr GLRenderSystem::getActiveProgram(GpuProgramType gptype) const
  1365. {
  1366. switch (gptype)
  1367. {
  1368. case GPT_VERTEX_PROGRAM:
  1369. return mCurrentVertexProgram;
  1370. break;
  1371. case GPT_FRAGMENT_PROGRAM:
  1372. return mCurrentFragmentProgram;
  1373. break;
  1374. case GPT_GEOMETRY_PROGRAM:
  1375. return mCurrentGeometryProgram;
  1376. break;
  1377. case GPT_DOMAIN_PROGRAM:
  1378. return mCurrentDomainProgram;
  1379. break;
  1380. case GPT_HULL_PROGRAM:
  1381. return mCurrentHullProgram;
  1382. break;
  1383. default:
  1384. BS_EXCEPT(InvalidParametersException, "Insupported gpu program type: " + toString(gptype));
  1385. }
  1386. }
  1387. void GLRenderSystem::initFromCaps(RenderSystemCapabilities* caps)
  1388. {
  1389. if(caps->getRenderSystemName() != getName())
  1390. {
  1391. BS_EXCEPT(InvalidParametersException,
  1392. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  1393. }
  1394. #if BS_DEBUG_MODE
  1395. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  1396. {
  1397. glDebugMessageCallback(&openGlErrorCallback, 0);
  1398. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  1399. }
  1400. #endif
  1401. HardwareBufferManager::startUp<GLHardwareBufferManager>();
  1402. // GPU Program Manager setup
  1403. if(caps->isShaderProfileSupported("glsl"))
  1404. {
  1405. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  1406. GpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  1407. }
  1408. // Check for framebuffer object extension
  1409. if(caps->hasCapability(RSC_FBO))
  1410. {
  1411. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  1412. {
  1413. // Create FBO manager
  1414. GLRTTManager::startUp<GLRTTManager>();
  1415. }
  1416. }
  1417. else
  1418. {
  1419. BS_EXCEPT(RenderingAPIException, "GPU doesn't support frame buffer objects. OpenGL versions lower than 3.0 are not supported.");
  1420. }
  1421. mFragmentTexOffset = 0;
  1422. mVertexTexOffset = caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1423. mGeometryTexOffset = mVertexTexOffset + caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1424. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  1425. UINT32 totalNumTexUnits = caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1426. totalNumTexUnits += caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1427. totalNumTexUnits += caps->getNumTextureUnits(GPT_GEOMETRY_PROGRAM);
  1428. totalNumTexUnits += caps->getNumTextureUnits(GPT_HULL_PROGRAM);
  1429. totalNumTexUnits += caps->getNumTextureUnits(GPT_DOMAIN_PROGRAM);
  1430. totalNumTexUnits += caps->getNumTextureUnits(GPT_COMPUTE_PROGRAM);
  1431. if(totalNumTexUnits > numCombinedTexUnits)
  1432. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  1433. mNumTextureTypes = numCombinedTexUnits;
  1434. mTextureTypes = bs_newN<GLenum>(mNumTextureTypes);
  1435. for(UINT16 i = 0; i < numCombinedTexUnits; i++)
  1436. mTextureTypes[i] = 0;
  1437. mVertexUBOffset = 0;
  1438. UINT32 totalNumUniformBlocks = caps->getNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM);
  1439. mFragmentUBOffset = totalNumUniformBlocks;
  1440. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM);
  1441. mGeometryUBOffset = totalNumUniformBlocks;
  1442. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM);
  1443. mHullUBOffset = totalNumUniformBlocks;
  1444. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_HULL_PROGRAM);
  1445. mDomainUBOffset = totalNumUniformBlocks;
  1446. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM);
  1447. mComputeUBOffset = totalNumUniformBlocks;
  1448. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM);
  1449. UINT16 numCombinedUniformBlocks = caps->getNumCombinedGpuParamBlockBuffers();
  1450. if(totalNumUniformBlocks > numCombinedUniformBlocks)
  1451. BS_EXCEPT(InternalErrorException, "Number of combined uniform block buffers less than the number of individual per-stage buffers!?");
  1452. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  1453. }
  1454. void GLRenderSystem::switchContext(GLContext *context)
  1455. {
  1456. // Unbind GPU programs and rebind to new context later, because
  1457. // scene manager treat render system as ONE 'context' ONLY, and it
  1458. // cached the GPU programs using state.
  1459. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1460. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1461. unbindGpuProgram(GPT_GEOMETRY_PROGRAM);
  1462. unbindGpuProgram(GPT_HULL_PROGRAM);
  1463. unbindGpuProgram(GPT_DOMAIN_PROGRAM);
  1464. // It's ready for switching
  1465. if (mCurrentContext)
  1466. mCurrentContext->endCurrent();
  1467. mCurrentContext = context;
  1468. mCurrentContext->setCurrent();
  1469. // Must reset depth/colour write mask to according with user desired, otherwise,
  1470. // clearFrameBuffer would be wrong because the value we are recorded may be
  1471. // difference with the really state stored in GL context.
  1472. glDepthMask(mDepthWrite);
  1473. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1474. glStencilMask(mStencilWriteMask);
  1475. }
  1476. RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const
  1477. {
  1478. RenderSystemCapabilities* rsc = bs_new<RenderSystemCapabilities>();
  1479. rsc->setDriverVersion(mDriverVersion);
  1480. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  1481. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  1482. rsc->setDeviceName(deviceName);
  1483. rsc->setRenderSystemName(getName());
  1484. // determine vendor
  1485. if (strstr(vendorName, "NVIDIA"))
  1486. rsc->setVendor(GPU_NVIDIA);
  1487. else if (strstr(vendorName, "ATI"))
  1488. rsc->setVendor(GPU_AMD);
  1489. else if (strstr(vendorName, "AMD"))
  1490. rsc->setVendor(GPU_AMD);
  1491. else if (strstr(vendorName, "Intel"))
  1492. rsc->setVendor(GPU_INTEL);
  1493. else
  1494. rsc->setVendor(GPU_UNKNOWN);
  1495. // Check for hardware mipmapping support.
  1496. if(GLEW_VERSION_1_4)
  1497. {
  1498. rsc->setCapability(RSC_AUTOMIPMAP);
  1499. }
  1500. // Check for Anisotropy support
  1501. if (getGLSupport()->checkExtension("GL_EXT_texture_filter_anisotropic"))
  1502. {
  1503. rsc->setCapability(RSC_ANISOTROPY);
  1504. }
  1505. // Check for cube mapping
  1506. if(GLEW_VERSION_1_3 ||
  1507. getGLSupport()->checkExtension("GL_ARB_texture_cube_map") ||
  1508. getGLSupport()->checkExtension("GL_EXT_texture_cube_map"))
  1509. {
  1510. rsc->setCapability(RSC_CUBEMAPPING);
  1511. }
  1512. // Point sprites
  1513. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_ARB_point_sprite"))
  1514. {
  1515. rsc->setCapability(RSC_POINT_SPRITES);
  1516. }
  1517. // Check for hardware stencil support and set bit depth
  1518. GLint stencil;
  1519. glGetIntegerv(GL_STENCIL_BITS, &stencil);
  1520. if(stencil)
  1521. {
  1522. rsc->setStencilBufferBitDepth(stencil);
  1523. }
  1524. if (GLEW_VERSION_2_0 ||
  1525. (getGLSupport()->checkExtension("GL_ARB_shading_language_100") &&
  1526. getGLSupport()->checkExtension("GL_ARB_shader_objects") &&
  1527. getGLSupport()->checkExtension("GL_ARB_fragment_shader") &&
  1528. getGLSupport()->checkExtension("GL_ARB_vertex_shader")))
  1529. {
  1530. rsc->addShaderProfile("glsl");
  1531. }
  1532. // Check if geometry shaders are supported
  1533. if (GLEW_VERSION_2_0 &&
  1534. getGLSupport()->checkExtension("GL_EXT_geometry_shader4"))
  1535. {
  1536. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  1537. rsc->setGeometryProgramConstantBoolCount(0);
  1538. rsc->setGeometryProgramConstantIntCount(0);
  1539. GLint floatConstantCount = 0;
  1540. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  1541. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  1542. GLint maxOutputVertices;
  1543. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  1544. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  1545. }
  1546. //Check if render to vertex buffer (transform feedback in OpenGL)
  1547. if (GLEW_VERSION_2_0 && getGLSupport()->checkExtension("GL_EXT_transform_feedback"))
  1548. {
  1549. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  1550. }
  1551. // Check for texture compression
  1552. if (GLEW_VERSION_1_3 || getGLSupport()->checkExtension("GL_ARB_texture_compression"))
  1553. {
  1554. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1555. // Check for dxt compression
  1556. if (getGLSupport()->checkExtension("GL_EXT_texture_compression_s3tc"))
  1557. {
  1558. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1559. }
  1560. // Check for vtc compression
  1561. if (getGLSupport()->checkExtension("GL_NV_texture_compression_vtc"))
  1562. {
  1563. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  1564. }
  1565. }
  1566. // As are user clipping planes
  1567. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1568. // 2-sided stencil?
  1569. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_EXT_stencil_two_side"))
  1570. {
  1571. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1572. }
  1573. // stencil wrapping?
  1574. if (GLEW_VERSION_1_4 || getGLSupport()->checkExtension("GL_EXT_stencil_wrap"))
  1575. {
  1576. rsc->setCapability(RSC_STENCIL_WRAP);
  1577. }
  1578. // Check for hardware occlusion support
  1579. if (GLEW_VERSION_1_5 || getGLSupport()->checkExtension("GL_ARB_occlusion_query"))
  1580. {
  1581. rsc->setCapability(RSC_HWOCCLUSION);
  1582. }
  1583. // UBYTE4 always supported
  1584. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1585. // Infinite far plane always supported
  1586. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1587. // Check for non-power-of-2 texture support
  1588. if (getGLSupport()->checkExtension("GL_ARB_texture_non_power_of_two"))
  1589. {
  1590. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1591. }
  1592. // Check for Float textures
  1593. if (getGLSupport()->checkExtension("GL_ATI_texture_float") || getGLSupport()->checkExtension("GL_ARB_texture_float"))
  1594. {
  1595. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1596. }
  1597. // 3D textures should always be supported
  1598. rsc->setCapability(RSC_TEXTURE_3D);
  1599. // Check for framebuffer object extension
  1600. if (getGLSupport()->checkExtension("GL_ARB_framebuffer_object"))
  1601. {
  1602. // Probe number of draw buffers
  1603. // Only makes sense with FBO support, so probe here
  1604. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_ARB_draw_buffers") || getGLSupport()->checkExtension("GL_ATI_draw_buffers"))
  1605. {
  1606. GLint buffers;
  1607. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  1608. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)BS_MAX_MULTIPLE_RENDER_TARGETS));
  1609. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1610. rsc->setCapability(RSC_FBO);
  1611. }
  1612. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1613. }
  1614. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1615. rsc->setCapability(RSC_PBUFFER);
  1616. // Point size
  1617. float ps;
  1618. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  1619. rsc->setMaxPointSize(ps);
  1620. // Max number of fragment shader textures
  1621. GLint units;
  1622. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  1623. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  1624. // Max number of vertex shader textures
  1625. GLint vUnits;
  1626. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  1627. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  1628. if (vUnits > 0)
  1629. {
  1630. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1631. }
  1632. GLint numUniformBlocks;
  1633. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  1634. rsc->setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  1635. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  1636. rsc->setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  1637. if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
  1638. {
  1639. GLint geomUnits;
  1640. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  1641. rsc->setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  1642. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  1643. rsc->setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  1644. }
  1645. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  1646. {
  1647. rsc->setCapability(RSC_TESSELLATION_PROGRAM);
  1648. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  1649. rsc->setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  1650. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  1651. rsc->setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  1652. }
  1653. if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
  1654. {
  1655. rsc->setCapability(RSC_COMPUTE_PROGRAM);
  1656. GLint computeUnits;
  1657. glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  1658. rsc->setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  1659. glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  1660. rsc->setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  1661. }
  1662. GLint combinedTexUnits;
  1663. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  1664. rsc->setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  1665. GLint combinedUniformBlockUnits;
  1666. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  1667. rsc->setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  1668. // Mipmap LOD biasing
  1669. if (mGLSupport->checkExtension("GL_EXT_texture_lod_bias"))
  1670. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1671. // Alpha to coverage?
  1672. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  1673. {
  1674. // Alpha to coverage always 'supported' when MSAA is available
  1675. // although card may ignore it if it doesn't specifically support A2C
  1676. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1677. }
  1678. // Advanced blending operations
  1679. if(GLEW_VERSION_2_0)
  1680. {
  1681. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1682. }
  1683. return rsc;
  1684. }
  1685. bool GLRenderSystem::checkForErrors() const
  1686. {
  1687. GLenum glErr = glGetError();
  1688. bool errorsFound = false;
  1689. String msg;
  1690. while (glErr != GL_NO_ERROR)
  1691. {
  1692. const char* glerrStr = (const char*)gluErrorString(glErr);
  1693. if (glerrStr)
  1694. {
  1695. msg += String(glerrStr);
  1696. }
  1697. glErr = glGetError();
  1698. errorsFound = true;
  1699. }
  1700. if (errorsFound)
  1701. LOGWRN("OpenGL error: " + msg);
  1702. return errorsFound;
  1703. }
  1704. void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  1705. {
  1706. UINT32 x = 0;
  1707. for (UINT32 i = 0; i < 4; i++)
  1708. {
  1709. for (UINT32 j = 0; j < 4; j++)
  1710. {
  1711. gl_matrix[x] = m[j][i];
  1712. x++;
  1713. }
  1714. }
  1715. }
  1716. /************************************************************************/
  1717. /* UTILITY */
  1718. /************************************************************************/
  1719. float GLRenderSystem::getMinimumDepthInputValue()
  1720. {
  1721. return -1.0f;
  1722. }
  1723. float GLRenderSystem::getMaximumDepthInputValue()
  1724. {
  1725. return 1.0f;
  1726. }
  1727. float GLRenderSystem::getHorizontalTexelOffset()
  1728. {
  1729. return 0.0f;
  1730. }
  1731. float GLRenderSystem::getVerticalTexelOffset()
  1732. {
  1733. return 0.0f;
  1734. }
  1735. VertexElementType GLRenderSystem::getColorVertexElementType() const
  1736. {
  1737. return VET_COLOR_ABGR;
  1738. }
  1739. void GLRenderSystem::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool forGpuProgram)
  1740. {
  1741. dest = matrix;
  1742. }
  1743. void __stdcall openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam)
  1744. {
  1745. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  1746. {
  1747. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  1748. }
  1749. }
  1750. }