BsGLRenderAPI.cpp 63 KB

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