BsGLRenderSystem.cpp 59 KB

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