BsGLRenderAPI.cpp 59 KB

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