BsGLRenderSystem.cpp 58 KB

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