BsGLRenderAPI.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsGLRenderAPI.h"
  4. #include "RenderAPI/BsRenderAPI.h"
  5. #include "BsGLTextureManager.h"
  6. #include "BsGLIndexBuffer.h"
  7. #include "BsGLUtil.h"
  8. #include "GLSL/BsGLSLGpuProgram.h"
  9. #include "Error/BsException.h"
  10. #include "BsGLContext.h"
  11. #include "BsGLSupport.h"
  12. #include "RenderAPI/BsBlendState.h"
  13. #include "RenderAPI/BsRasterizerState.h"
  14. #include "RenderAPI/BsDepthStencilState.h"
  15. #include "BsGLRenderTexture.h"
  16. #include "BsGLRenderWindowManager.h"
  17. #include "GLSL/BsGLSLProgramPipelineManager.h"
  18. #include "BsGLVertexArrayObjectManager.h"
  19. #include "Managers/BsRenderStateManager.h"
  20. #include "RenderAPI/BsGpuParams.h"
  21. #include "BsGLGpuParamBlockBuffer.h"
  22. #include "CoreThread/BsCoreThread.h"
  23. #include "BsGLQueryManager.h"
  24. #include "Debug/BsDebug.h"
  25. #include "Profiling/BsRenderStats.h"
  26. #include "RenderAPI/BsGpuParamDesc.h"
  27. #include "BsGLGpuBuffer.h"
  28. #include "BsGLCommandBuffer.h"
  29. #include "BsGLCommandBufferManager.h"
  30. #include "BsGLTextureView.h"
  31. #include "GLSL/BsGLSLParamParser.h"
  32. namespace bs { namespace ct
  33. {
  34. const char* MODULE_NAME = "BansheeGLRenderAPI.dll";
  35. const char* bs_get_gl_error_string(GLenum errorCode)
  36. {
  37. switch (errorCode)
  38. {
  39. case GL_INVALID_OPERATION: return "INVALID_OPERATION";
  40. case GL_INVALID_ENUM: return "INVALID_ENUM";
  41. case GL_INVALID_VALUE: return "INVALID_VALUE";
  42. case GL_OUT_OF_MEMORY: return "OUT_OF_MEMORY";
  43. case GL_INVALID_FRAMEBUFFER_OPERATION: return "INVALID_FRAMEBUFFER_OPERATION";
  44. }
  45. return nullptr;
  46. }
  47. void bs_check_gl_error(const char* function, const char* file, INT32 line)
  48. {
  49. GLenum errorCode = glGetError();
  50. if (errorCode != GL_NO_ERROR)
  51. {
  52. StringStream errorOutput;
  53. errorOutput << "OpenGL error in " << function << " [" << file << ":" << toString(line) << "]:\n";
  54. while (errorCode != GL_NO_ERROR)
  55. {
  56. const char* errorString = bs_get_gl_error_string(errorCode);
  57. if (errorString)
  58. errorOutput << "\t - " << errorString;
  59. errorCode = glGetError();
  60. }
  61. gDebug().logWarning(errorOutput.str());
  62. }
  63. }
  64. #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
  65. void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar
  66. *message, GLvoid *userParam);
  67. #endif
  68. /************************************************************************/
  69. /* PUBLIC INTERFACE */
  70. /************************************************************************/
  71. GLRenderAPI::GLRenderAPI()
  72. : mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
  73. , mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280)
  74. , mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0)
  75. , mScissorEnabled(false)
  76. , mStencilReadMask(0xFFFFFFFF)
  77. , mStencilWriteMask(0xFFFFFFFF)
  78. , mStencilRefValue(0)
  79. , mStencilCompareFront(CMPF_ALWAYS_PASS)
  80. , mStencilCompareBack(CMPF_ALWAYS_PASS)
  81. , mNumTextureUnits(0)
  82. , mTextureInfos(nullptr)
  83. , mDepthWrite(true)
  84. , mGLSLProgramFactory(nullptr)
  85. , mProgramPipelineManager(nullptr)
  86. , mActivePipeline(nullptr)
  87. , mCurrentDrawOperation(DOT_TRIANGLE_LIST)
  88. , mDrawCallInProgress(false)
  89. , mActiveTextureUnit(-1)
  90. {
  91. // Get our GLSupport
  92. mGLSupport = ct::getGLSupport();
  93. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  94. mCurrentContext = 0;
  95. mMainContext = 0;
  96. mGLInitialised = false;
  97. mMinFilter = FO_LINEAR;
  98. mMipFilter = FO_POINT;
  99. mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
  100. }
  101. GLRenderAPI::~GLRenderAPI()
  102. {
  103. }
  104. const StringID& GLRenderAPI::getName() const
  105. {
  106. static StringID strName("GLRenderAPI");
  107. return strName;
  108. }
  109. void GLRenderAPI::initialize()
  110. {
  111. THROW_IF_NOT_CORE_THREAD;
  112. mGLSupport->start();
  113. mVideoModeInfo = mGLSupport->getVideoModeInfo();
  114. CommandBufferManager::startUp<GLCommandBufferManager>();
  115. bs::RenderWindowManager::startUp<bs::GLRenderWindowManager>(this);
  116. RenderWindowManager::startUp();
  117. RenderStateManager::startUp();
  118. QueryManager::startUp<GLQueryManager>();
  119. RenderAPI::initialize();
  120. }
  121. void GLRenderAPI::initializeWithWindow(const SPtr<RenderWindow>& primaryWindow)
  122. {
  123. // Get the context from the window and finish initialization
  124. SPtr<GLContext> context;
  125. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  126. // Set main and current context
  127. mMainContext = context;
  128. mCurrentContext = mMainContext;
  129. // Set primary context as active
  130. if (mCurrentContext)
  131. mCurrentContext->setCurrent(*primaryWindow);
  132. // Setup GLSupport
  133. mGLSupport->initializeExtensions();
  134. mNumDevices = 1;
  135. mCurrentCapabilities = bs_newN<RenderAPICapabilities>(mNumDevices);
  136. initCapabilities(mCurrentCapabilities[0]);
  137. initFromCaps(mCurrentCapabilities);
  138. GLVertexArrayObjectManager::startUp();
  139. glFrontFace(GL_CW);
  140. BS_CHECK_GL_ERROR();
  141. // Ensure cubemaps are filtered across seams
  142. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  143. BS_CHECK_GL_ERROR();
  144. GPUInfo gpuInfo;
  145. gpuInfo.numGPUs = 1;
  146. const char* vendor = (const char*)glGetString(GL_VENDOR);
  147. BS_CHECK_GL_ERROR();
  148. const char* renderer = (const char*)glGetString(GL_RENDERER);
  149. BS_CHECK_GL_ERROR();
  150. gpuInfo.names[0] = String(vendor) + " " + String(renderer);
  151. PlatformUtility::_setGPUInfo(gpuInfo);
  152. mGLInitialised = true;
  153. RenderAPI::initializeWithWindow(primaryWindow);
  154. }
  155. void GLRenderAPI::destroyCore()
  156. {
  157. RenderAPI::destroyCore();
  158. // Deleting the GLSL program factory
  159. if (mGLSLProgramFactory)
  160. {
  161. // Remove from manager safely
  162. GpuProgramManager::instance().removeFactory("glsl");
  163. GpuProgramManager::instance().removeFactory("glsl4_1");
  164. bs_delete(mGLSLProgramFactory);
  165. mGLSLProgramFactory = nullptr;
  166. }
  167. // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
  168. HardwareBufferManager::shutDown();
  169. bs::HardwareBufferManager::shutDown();
  170. GLRTTManager::shutDown();
  171. for (UINT32 i = 0; i < MAX_VB_COUNT; i++)
  172. mBoundVertexBuffers[i] = nullptr;
  173. mBoundVertexDeclaration = nullptr;
  174. mBoundIndexBuffer = nullptr;
  175. mCurrentVertexProgram = nullptr;
  176. mCurrentFragmentProgram = nullptr;
  177. mCurrentGeometryProgram = nullptr;
  178. mCurrentHullProgram = nullptr;
  179. mCurrentDomainProgram = nullptr;
  180. mCurrentComputeProgram = nullptr;
  181. mGLSupport->stop();
  182. TextureManager::shutDown();
  183. bs::TextureManager::shutDown();
  184. QueryManager::shutDown();
  185. RenderWindowManager::shutDown();
  186. bs::RenderWindowManager::shutDown();
  187. RenderStateManager::shutDown();
  188. GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
  189. CommandBufferManager::shutDown();
  190. mGLInitialised = false;
  191. if(mProgramPipelineManager != nullptr)
  192. bs_delete(mProgramPipelineManager);
  193. if(mCurrentContext)
  194. mCurrentContext->endCurrent();
  195. mCurrentContext = nullptr;
  196. mMainContext = nullptr;
  197. if(mGLSupport)
  198. bs_delete(mGLSupport);
  199. if (mTextureInfos != nullptr)
  200. bs_deleteN(mTextureInfos, mNumTextureUnits);
  201. }
  202. void GLRenderAPI::setGraphicsPipeline(const SPtr<GraphicsPipelineState>& pipelineState,
  203. const SPtr<CommandBuffer>& commandBuffer)
  204. {
  205. auto executeRef = [&](const SPtr<GraphicsPipelineState>& pipelineState)
  206. {
  207. THROW_IF_NOT_CORE_THREAD;
  208. BlendState* blendState;
  209. RasterizerState* rasterizerState;
  210. DepthStencilState* depthStencilState;
  211. if (pipelineState != nullptr)
  212. {
  213. mCurrentVertexProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getVertexProgram());
  214. mCurrentFragmentProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getFragmentProgram());
  215. mCurrentGeometryProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getGeometryProgram());
  216. mCurrentDomainProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getDomainProgram());
  217. mCurrentHullProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getHullProgram());
  218. blendState = pipelineState->getBlendState().get();
  219. rasterizerState = pipelineState->getRasterizerState().get();
  220. depthStencilState = pipelineState->getDepthStencilState().get();
  221. if (blendState == nullptr)
  222. blendState = BlendState::getDefault().get();
  223. if (rasterizerState == nullptr)
  224. rasterizerState = RasterizerState::getDefault().get();
  225. if(depthStencilState == nullptr)
  226. depthStencilState = DepthStencilState::getDefault().get();
  227. }
  228. else
  229. {
  230. mCurrentVertexProgram = nullptr;
  231. mCurrentFragmentProgram = nullptr;
  232. mCurrentGeometryProgram = nullptr;
  233. mCurrentDomainProgram = nullptr;
  234. mCurrentHullProgram = nullptr;
  235. blendState = BlendState::getDefault().get();
  236. rasterizerState = RasterizerState::getDefault().get();
  237. depthStencilState = DepthStencilState::getDefault().get();
  238. }
  239. // Blend state
  240. {
  241. const BlendProperties& stateProps = blendState->getProperties();
  242. // Alpha to coverage
  243. setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
  244. // Blend states
  245. // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
  246. if (stateProps.getBlendEnabled(0))
  247. {
  248. setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
  249. stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
  250. }
  251. else
  252. {
  253. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  254. }
  255. // Color write mask
  256. UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
  257. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  258. }
  259. // Rasterizer state
  260. {
  261. const RasterizerProperties& stateProps = rasterizerState->getProperties();
  262. setDepthBias(stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
  263. setCullingMode(stateProps.getCullMode());
  264. setPolygonMode(stateProps.getPolygonMode());
  265. setScissorTestEnable(stateProps.getScissorEnable());
  266. setMultisamplingEnable(stateProps.getMultisampleEnable());
  267. setDepthClipEnable(stateProps.getDepthClipEnable());
  268. setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
  269. }
  270. // Depth stencil state
  271. {
  272. const DepthStencilProperties& stateProps = depthStencilState->getProperties();
  273. // Set stencil buffer options
  274. setStencilCheckEnabled(stateProps.getStencilEnable());
  275. setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
  276. setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
  277. setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
  278. setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
  279. setStencilBufferWriteMask(stateProps.getStencilWriteMask());
  280. // Set depth buffer options
  281. setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
  282. setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
  283. setDepthBufferFunction(stateProps.getDepthComparisonFunc());
  284. }
  285. };
  286. if (commandBuffer == nullptr)
  287. executeRef(pipelineState);
  288. else
  289. {
  290. auto execute = [=]() { executeRef(pipelineState); };
  291. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  292. cb->queueCommand(execute);
  293. }
  294. BS_INC_RENDER_STAT(NumPipelineStateChanges);
  295. }
  296. void GLRenderAPI::setComputePipeline(const SPtr<ComputePipelineState>& pipelineState,
  297. const SPtr<CommandBuffer>& commandBuffer)
  298. {
  299. auto executeRef = [&](const SPtr<ComputePipelineState>& pipelineState)
  300. {
  301. THROW_IF_NOT_CORE_THREAD;
  302. SPtr<GpuProgram> program;
  303. if (pipelineState != nullptr)
  304. program = pipelineState->getProgram();
  305. if (program != nullptr && program->getProperties().getType() == GPT_COMPUTE_PROGRAM)
  306. mCurrentComputeProgram = std::static_pointer_cast<GLSLGpuProgram>(program);
  307. else
  308. mCurrentComputeProgram = nullptr;
  309. };
  310. if (commandBuffer == nullptr)
  311. executeRef(pipelineState);
  312. else
  313. {
  314. auto execute = [=]() { executeRef(pipelineState); };
  315. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  316. cb->queueCommand(execute);
  317. }
  318. BS_INC_RENDER_STAT(NumPipelineStateChanges);
  319. }
  320. void GLRenderAPI::setGpuParams(const SPtr<GpuParams>& gpuParams, const SPtr<CommandBuffer>& commandBuffer)
  321. {
  322. auto executeRef = [&](const SPtr<GpuParams>& gpuParams)
  323. {
  324. THROW_IF_NOT_CORE_THREAD;
  325. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  326. for (UINT32 i = 0; i < 8; i++)
  327. {
  328. glBindImageTexture(i, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  329. BS_CHECK_GL_ERROR();
  330. }
  331. #endif
  332. bs_frame_mark();
  333. {
  334. UINT32 textureUnitCount = 0;
  335. FrameVector<UINT32> textureUnits(12);
  336. auto getTexUnit = [&](UINT32 binding)
  337. {
  338. for(UINT32 i = 0; i < (UINT32)textureUnits.size(); i++)
  339. {
  340. if (textureUnits[i] == binding)
  341. return i;
  342. }
  343. UINT32 unit = textureUnitCount++;
  344. textureUnits.push_back(binding);
  345. return unit;
  346. };
  347. FrameVector<UINT32> imageUnits(6);
  348. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  349. UINT32 imageUnitCount = 0;
  350. auto getImageUnit = [&](UINT32 binding)
  351. {
  352. for (UINT32 i = 0; i < (UINT32)imageUnits.size(); i++)
  353. {
  354. if (imageUnits[i] == binding)
  355. return i;
  356. }
  357. UINT32 unit = imageUnitCount++;
  358. imageUnits.push_back(binding);
  359. return unit;
  360. };
  361. #endif
  362. UINT32 uniformUnitCount = 0;
  363. FrameVector<UINT32> uniformUnits(6);
  364. auto getUniformUnit = [&](UINT32 binding)
  365. {
  366. for (UINT32 i = 0; i < (UINT32)uniformUnits.size(); i++)
  367. {
  368. if (uniformUnits[i] == binding)
  369. return i;
  370. }
  371. UINT32 unit = uniformUnitCount++;
  372. uniformUnits.push_back(binding);
  373. return unit;
  374. };
  375. FrameVector<UINT32> sharedStorageUnits(6);
  376. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  377. UINT32 sharedStorageUnitCount = 0;
  378. auto getSharedStorageUnit = [&](UINT32 binding)
  379. {
  380. for (UINT32 i = 0; i < (UINT32)sharedStorageUnits.size(); i++)
  381. {
  382. if (sharedStorageUnits[i] == binding)
  383. return i;
  384. }
  385. UINT32 unit = sharedStorageUnitCount++;
  386. sharedStorageUnits.push_back(binding);
  387. return unit;
  388. };
  389. #endif
  390. const UINT32 numStages = 6;
  391. for(UINT32 i = 0; i < numStages; i++)
  392. {
  393. textureUnits.clear();
  394. imageUnits.clear();
  395. uniformUnits.clear();
  396. sharedStorageUnits.clear();
  397. GpuProgramType type = (GpuProgramType)i;
  398. SPtr<GpuParamDesc> paramDesc = gpuParams->getParamDesc(type);
  399. if (paramDesc == nullptr)
  400. continue;
  401. for (auto& entry : paramDesc->textures)
  402. {
  403. UINT32 binding = entry.second.slot;
  404. SPtr<Texture> texture = gpuParams->getTexture(entry.second.set, binding);
  405. const TextureSurface& surface = gpuParams->getTextureSurface(entry.second.set, binding);
  406. UINT32 unit = getTexUnit(binding);
  407. if (!activateGLTextureUnit(unit))
  408. continue;
  409. GLTexture* glTex = static_cast<GLTexture*>(texture.get());
  410. if (glTex != nullptr)
  411. {
  412. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  413. SPtr<TextureView> texView = glTex->requestView(
  414. surface.mipLevel,
  415. surface.numMipLevels,
  416. surface.face,
  417. surface.numFaces,
  418. GVU_DEFAULT);
  419. GLTextureView* glTexView = static_cast<GLTextureView*>(texView.get());
  420. GLenum newTextureType = glTexView->getGLTextureTarget();
  421. GLuint texId = glTexView->getGLID();
  422. #else
  423. // Texture views are not supported, so if user requested a part of the texture surface report
  424. // a warning
  425. auto& props = texture->getProperties();
  426. if (surface.mipLevel != 0 || surface.face != 0 ||
  427. (surface.numMipLevels != 0 && surface.numMipLevels != props.getNumMipmaps()) ||
  428. (surface.numFaces != 0 && surface.numFaces != props.getNumFaces()))
  429. {
  430. LOGWRN("Attempting to bind only a part of a texture, but texture views are not supported. "
  431. "Entire texture will be bound instead.");
  432. }
  433. GLenum newTextureType = glTex->getGLTextureTarget();
  434. GLuint texId = glTex->getGLID();
  435. #endif
  436. if (mTextureInfos[unit].type != newTextureType)
  437. {
  438. glBindTexture(mTextureInfos[unit].type, 0);
  439. BS_CHECK_GL_ERROR();
  440. }
  441. glBindTexture(newTextureType, texId);
  442. BS_CHECK_GL_ERROR();
  443. mTextureInfos[unit].type = newTextureType;
  444. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  445. if (activeProgram != nullptr)
  446. {
  447. GLuint glProgram = activeProgram->getGLHandle();
  448. glProgramUniform1i(glProgram, binding, unit);
  449. BS_CHECK_GL_ERROR();
  450. }
  451. }
  452. else
  453. {
  454. glBindTexture(mTextureInfos[unit].type, 0);
  455. BS_CHECK_GL_ERROR();
  456. }
  457. }
  458. for(auto& entry : paramDesc->samplers)
  459. {
  460. UINT32 binding = entry.second.slot;
  461. SPtr<SamplerState> samplerState = gpuParams->getSamplerState(entry.second.set, binding);
  462. if (samplerState == nullptr)
  463. samplerState = SamplerState::getDefault();
  464. UINT32 unit = getTexUnit(binding);
  465. if (!activateGLTextureUnit(unit))
  466. continue;
  467. bool isMultisample = mTextureInfos[unit].type == GL_TEXTURE_2D_MULTISAMPLE ||
  468. mTextureInfos[unit].type == GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  469. // No sampler options for multisampled textures
  470. if (!isMultisample)
  471. {
  472. const SamplerProperties& stateProps = samplerState->getProperties();
  473. setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
  474. setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
  475. setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
  476. setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
  477. setTextureCompareMode(unit, stateProps.getComparisonFunction());
  478. setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
  479. setTextureMipmapRange(unit, stateProps.getMinimumMip(), stateProps.getMaximumMip());
  480. const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
  481. setTextureAddressingMode(unit, uvw);
  482. setTextureBorderColor(unit, stateProps.getBorderColor());
  483. }
  484. }
  485. for(auto& entry : paramDesc->buffers)
  486. {
  487. UINT32 binding = entry.second.slot;
  488. SPtr<GpuBuffer> buffer = gpuParams->getBuffer(entry.second.set, binding);
  489. GLGpuBuffer* glBuffer = static_cast<GLGpuBuffer*>(buffer.get());
  490. switch(entry.second.type)
  491. {
  492. case GPOT_BYTE_BUFFER: // Texture buffer (read-only, unstructured)
  493. {
  494. UINT32 unit = getTexUnit(binding);
  495. if (!activateGLTextureUnit(unit))
  496. continue;
  497. if (glBuffer != nullptr)
  498. {
  499. if (mTextureInfos[unit].type != GL_TEXTURE_BUFFER)
  500. {
  501. glBindTexture(mTextureInfos[unit].type, 0);
  502. BS_CHECK_GL_ERROR();
  503. }
  504. mTextureInfos[unit].type = GL_TEXTURE_BUFFER;
  505. glBindTexture(GL_TEXTURE_BUFFER, glBuffer->getGLTextureId());
  506. BS_CHECK_GL_ERROR();
  507. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  508. if (activeProgram != nullptr)
  509. {
  510. GLuint glProgram = activeProgram->getGLHandle();
  511. glProgramUniform1i(glProgram, binding, unit);
  512. BS_CHECK_GL_ERROR();
  513. }
  514. }
  515. else
  516. {
  517. glBindTexture(mTextureInfos[unit].type, 0);
  518. BS_CHECK_GL_ERROR();
  519. }
  520. }
  521. break;
  522. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  523. case GPOT_RWBYTE_BUFFER: // Storage buffer (read/write, unstructured)
  524. {
  525. UINT32 unit = getImageUnit(binding);
  526. if (glBuffer != nullptr)
  527. {
  528. glBindImageTexture(
  529. unit,
  530. glBuffer->getGLTextureId(),
  531. 0,
  532. false,
  533. 0,
  534. GL_READ_WRITE,
  535. glBuffer->getGLFormat());
  536. BS_CHECK_GL_ERROR();
  537. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  538. if (activeProgram != nullptr)
  539. {
  540. GLuint glProgram = activeProgram->getGLHandle();
  541. glProgramUniform1i(glProgram, binding, unit);
  542. BS_CHECK_GL_ERROR();
  543. }
  544. }
  545. else
  546. {
  547. glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  548. BS_CHECK_GL_ERROR();
  549. }
  550. }
  551. break;
  552. #endif
  553. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  554. case GPOT_RWSTRUCTURED_BUFFER: // Shared storage block (read/write, structured)
  555. {
  556. UINT32 unit = getSharedStorageUnit(binding);
  557. if (glBuffer != nullptr)
  558. {
  559. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, glBuffer->getGLBufferId());
  560. BS_CHECK_GL_ERROR();
  561. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  562. if (activeProgram != nullptr)
  563. {
  564. GLuint glProgram = activeProgram->getGLHandle();
  565. glShaderStorageBlockBinding(glProgram, binding, unit);
  566. BS_CHECK_GL_ERROR();
  567. }
  568. }
  569. else
  570. {
  571. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, 0);
  572. BS_CHECK_GL_ERROR();
  573. }
  574. }
  575. break;
  576. #endif
  577. default:
  578. break;
  579. }
  580. }
  581. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  582. for(auto& entry : paramDesc->loadStoreTextures)
  583. {
  584. UINT32 binding = entry.second.slot;
  585. SPtr<Texture> texture = gpuParams->getLoadStoreTexture(entry.second.set, binding);
  586. const TextureSurface& surface = gpuParams->getLoadStoreSurface(entry.second.set, binding);
  587. UINT32 unit = getImageUnit(binding);
  588. if (texture != nullptr)
  589. {
  590. GLTexture* tex = static_cast<GLTexture*>(texture.get());
  591. auto& texProps = tex->getProperties();
  592. GLboolean bindAllLayers =
  593. texProps.getNumFaces() == surface.numFaces ||
  594. surface.numFaces == 0;
  595. if(!bindAllLayers && surface.numFaces > 1)
  596. {
  597. LOGWRN("Attempting to bind multiple faces of a load-store texture. You are allowed to bind \
  598. either a single face, or all the faces of the texture. Only the first face will \
  599. be bound instead.");
  600. }
  601. if(surface.numMipLevels > 1)
  602. {
  603. LOGWRN("Attempting to bind multiple mip levels of a load-store texture. This is not \
  604. supported and only the first provided level will be bound.");
  605. }
  606. glBindImageTexture(
  607. unit,
  608. tex->getGLID(),
  609. surface.mipLevel,
  610. bindAllLayers,
  611. surface.face,
  612. GL_READ_WRITE,
  613. tex->getGLFormat());
  614. BS_CHECK_GL_ERROR();
  615. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  616. if (activeProgram != nullptr)
  617. {
  618. GLuint glProgram = activeProgram->getGLHandle();
  619. glProgramUniform1i(glProgram, binding, unit);
  620. BS_CHECK_GL_ERROR();
  621. }
  622. }
  623. else
  624. {
  625. glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  626. BS_CHECK_GL_ERROR();
  627. }
  628. }
  629. #endif
  630. for (auto& entry : paramDesc->paramBlocks)
  631. {
  632. UINT32 binding = entry.second.slot;
  633. SPtr<GpuParamBlockBuffer> buffer = gpuParams->getParamBlockBuffer(entry.second.set, binding);
  634. if (buffer == nullptr)
  635. continue;
  636. buffer->flushToGPU();
  637. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  638. GLuint glProgram = activeProgram->getGLHandle();
  639. // 0 means uniforms are not in block, in which case we handle it specially
  640. if (binding == 0)
  641. {
  642. UINT8* uniformBufferData = (UINT8*)bs_stack_alloc(buffer->getSize());
  643. buffer->read(0, uniformBufferData, buffer->getSize());
  644. for (auto iter = paramDesc->params.begin(); iter != paramDesc->params.end(); ++iter)
  645. {
  646. const GpuParamDataDesc& param = iter->second;
  647. if (param.paramBlockSlot != 0) // 0 means uniforms are not in a block
  648. continue;
  649. const UINT8* ptrData = uniformBufferData + param.cpuMemOffset * sizeof(UINT32);
  650. // Note: We don't transpose matrices here even though we don't use column major format
  651. // because they are assumed to be pre-transposed in the GpuParams buffer
  652. switch (param.type)
  653. {
  654. case GPDT_FLOAT1:
  655. glProgramUniform1fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  656. BS_CHECK_GL_ERROR();
  657. break;
  658. case GPDT_FLOAT2:
  659. glProgramUniform2fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  660. BS_CHECK_GL_ERROR();
  661. break;
  662. case GPDT_FLOAT3:
  663. glProgramUniform3fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  664. BS_CHECK_GL_ERROR();
  665. break;
  666. case GPDT_FLOAT4:
  667. glProgramUniform4fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  668. BS_CHECK_GL_ERROR();
  669. break;
  670. case GPDT_MATRIX_2X2:
  671. glProgramUniformMatrix2fv(
  672. glProgram,
  673. param.gpuMemOffset,
  674. param.arraySize,
  675. GL_FALSE,
  676. (GLfloat*)ptrData);
  677. BS_CHECK_GL_ERROR();
  678. break;
  679. case GPDT_MATRIX_2X3:
  680. glProgramUniformMatrix3x2fv(
  681. glProgram,
  682. param.gpuMemOffset,
  683. param.arraySize,
  684. GL_FALSE,
  685. (GLfloat*)ptrData);
  686. BS_CHECK_GL_ERROR();
  687. break;
  688. case GPDT_MATRIX_2X4:
  689. glProgramUniformMatrix4x2fv(
  690. glProgram,
  691. param.gpuMemOffset,
  692. param.arraySize,
  693. GL_FALSE,
  694. (GLfloat*)ptrData);
  695. BS_CHECK_GL_ERROR();
  696. break;
  697. case GPDT_MATRIX_3X2:
  698. glProgramUniformMatrix2x3fv(
  699. glProgram,
  700. param.gpuMemOffset,
  701. param.arraySize,
  702. GL_FALSE,
  703. (GLfloat*)ptrData);
  704. BS_CHECK_GL_ERROR();
  705. break;
  706. case GPDT_MATRIX_3X3:
  707. glProgramUniformMatrix3fv(
  708. glProgram,
  709. param.gpuMemOffset,
  710. param.arraySize,
  711. GL_FALSE,
  712. (GLfloat*)ptrData);
  713. BS_CHECK_GL_ERROR();
  714. break;
  715. case GPDT_MATRIX_3X4:
  716. glProgramUniformMatrix4x3fv(
  717. glProgram,
  718. param.gpuMemOffset,
  719. param.arraySize,
  720. GL_FALSE,
  721. (GLfloat*)ptrData);
  722. BS_CHECK_GL_ERROR();
  723. break;
  724. case GPDT_MATRIX_4X2:
  725. glProgramUniformMatrix2x4fv(
  726. glProgram,
  727. param.gpuMemOffset,
  728. param.arraySize,
  729. GL_FALSE,
  730. (GLfloat*)ptrData);
  731. BS_CHECK_GL_ERROR();
  732. break;
  733. case GPDT_MATRIX_4X3:
  734. glProgramUniformMatrix3x4fv(
  735. glProgram,
  736. param.gpuMemOffset,
  737. param.arraySize,
  738. GL_FALSE,
  739. (GLfloat*)ptrData);
  740. BS_CHECK_GL_ERROR();
  741. break;
  742. case GPDT_MATRIX_4X4:
  743. glProgramUniformMatrix4fv(
  744. glProgram,
  745. param.gpuMemOffset,
  746. param.arraySize,
  747. GL_FALSE,
  748. (GLfloat*)ptrData);
  749. BS_CHECK_GL_ERROR();
  750. break;
  751. case GPDT_INT1:
  752. glProgramUniform1iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  753. BS_CHECK_GL_ERROR();
  754. break;
  755. case GPDT_INT2:
  756. glProgramUniform2iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  757. BS_CHECK_GL_ERROR();
  758. break;
  759. case GPDT_INT3:
  760. glProgramUniform3iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  761. BS_CHECK_GL_ERROR();
  762. break;
  763. case GPDT_INT4:
  764. glProgramUniform4iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  765. BS_CHECK_GL_ERROR();
  766. break;
  767. case GPDT_BOOL:
  768. glProgramUniform1uiv(glProgram, param.gpuMemOffset, param.arraySize, (GLuint*)ptrData);
  769. BS_CHECK_GL_ERROR();
  770. break;
  771. default:
  772. case GPDT_UNKNOWN:
  773. break;
  774. }
  775. }
  776. if (uniformBufferData != nullptr)
  777. bs_stack_free(uniformBufferData);
  778. }
  779. else
  780. {
  781. const GLGpuParamBlockBuffer* glParamBlockBuffer = static_cast<const GLGpuParamBlockBuffer*>(buffer.get());
  782. UINT32 unit = getUniformUnit(binding - 1);
  783. glUniformBlockBinding(glProgram, binding - 1, unit);
  784. BS_CHECK_GL_ERROR();
  785. glBindBufferBase(GL_UNIFORM_BUFFER, unit, glParamBlockBuffer->getGLHandle());
  786. BS_CHECK_GL_ERROR();
  787. }
  788. }
  789. }
  790. }
  791. bs_frame_clear();
  792. activateGLTextureUnit(0);
  793. };
  794. if (commandBuffer == nullptr)
  795. executeRef(gpuParams);
  796. else
  797. {
  798. auto execute = [=]() { executeRef(gpuParams); };
  799. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  800. cb->queueCommand(execute);
  801. }
  802. BS_INC_RENDER_STAT(NumGpuParamBinds);
  803. }
  804. void GLRenderAPI::setStencilRef(UINT32 stencilRefValue, const SPtr<CommandBuffer>& commandBuffer)
  805. {
  806. auto executeRef = [&](UINT32 stencilRefValue)
  807. {
  808. THROW_IF_NOT_CORE_THREAD;
  809. setStencilRefValue(stencilRefValue);
  810. };
  811. if (commandBuffer == nullptr)
  812. executeRef(stencilRefValue);
  813. else
  814. {
  815. auto execute = [=]() { executeRef(stencilRefValue); };
  816. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  817. cb->queueCommand(execute);
  818. }
  819. }
  820. void GLRenderAPI::setViewport(const Rect2& area,
  821. const SPtr<CommandBuffer>& commandBuffer)
  822. {
  823. auto executeRef = [&](const Rect2& area)
  824. {
  825. THROW_IF_NOT_CORE_THREAD;
  826. mViewportNorm = area;
  827. applyViewport();
  828. };
  829. if (commandBuffer == nullptr)
  830. executeRef(area);
  831. else
  832. {
  833. auto execute = [=]() { executeRef(area); };
  834. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  835. cb->queueCommand(execute);
  836. }
  837. }
  838. void GLRenderAPI::setRenderTarget(const SPtr<RenderTarget>& target, UINT32 readOnlyFlags,
  839. RenderSurfaceMask loadMask, const SPtr<CommandBuffer>& commandBuffer)
  840. {
  841. auto executeRef = [&](const SPtr<RenderTarget>& target, UINT32 readOnlyFlags)
  842. {
  843. THROW_IF_NOT_CORE_THREAD;
  844. // Switch context if different from current one
  845. if (target != nullptr && target->getProperties().isWindow)
  846. {
  847. RenderWindow* window = static_cast<RenderWindow*>(target.get());
  848. SPtr<GLContext> newContext;
  849. target->getCustomAttribute("GLCONTEXT", &newContext);
  850. if (newContext && mCurrentContext != newContext)
  851. switchContext(newContext, *window);
  852. else
  853. mCurrentContext->setCurrent(*window);
  854. }
  855. // This must happen after context switch to ensure previous context is still alive
  856. mActiveRenderTarget = target;
  857. GLFrameBufferObject* fbo = nullptr;
  858. if (target != nullptr)
  859. target->getCustomAttribute("FBO", &fbo);
  860. if (fbo != nullptr)
  861. {
  862. fbo->bind();
  863. // Enable / disable sRGB states
  864. if (target->getProperties().hwGamma)
  865. {
  866. glEnable(GL_FRAMEBUFFER_SRGB);
  867. BS_CHECK_GL_ERROR();
  868. }
  869. else
  870. {
  871. glDisable(GL_FRAMEBUFFER_SRGB);
  872. BS_CHECK_GL_ERROR();
  873. }
  874. }
  875. else
  876. {
  877. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  878. BS_CHECK_GL_ERROR();
  879. }
  880. applyViewport();
  881. };
  882. if (commandBuffer == nullptr)
  883. executeRef(target, readOnlyFlags);
  884. else
  885. {
  886. auto execute = [=]() { executeRef(target, readOnlyFlags); };
  887. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  888. cb->queueCommand(execute);
  889. }
  890. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  891. }
  892. void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers,
  893. const SPtr<CommandBuffer>& commandBuffer)
  894. {
  895. #if BS_DEBUG_MODE
  896. UINT32 lastIdx = index + numBuffers;
  897. if(lastIdx > MAX_VB_COUNT)
  898. {
  899. LOGERR("Provided vertex buffer slot range is invalid: " + toString(index) + " to " +
  900. toString(index + numBuffers) + ".");
  901. return;
  902. }
  903. #endif
  904. auto executeRef = [&](UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers)
  905. {
  906. THROW_IF_NOT_CORE_THREAD;
  907. std::array<SPtr<VertexBuffer>, MAX_VB_COUNT> boundBuffers;
  908. for (UINT32 i = 0; i < numBuffers; i++)
  909. boundBuffers[index + i] = buffers[i];
  910. for (UINT32 i = 0; i < numBuffers; i++)
  911. mBoundVertexBuffers[index + i] = boundBuffers[index + i];
  912. };
  913. if (commandBuffer == nullptr)
  914. executeRef(index, buffers, numBuffers);
  915. else
  916. {
  917. auto execute = [=]() { executeRef(index, buffers, numBuffers); };
  918. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  919. cb->queueCommand(execute);
  920. }
  921. }
  922. void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclaration>& vertexDeclaration,
  923. const SPtr<CommandBuffer>& commandBuffer)
  924. {
  925. auto executeRef = [&](const SPtr<VertexDeclaration>& vertexDeclaration)
  926. {
  927. THROW_IF_NOT_CORE_THREAD;
  928. mBoundVertexDeclaration = vertexDeclaration;
  929. };
  930. if (commandBuffer == nullptr)
  931. executeRef(vertexDeclaration);
  932. else
  933. {
  934. auto execute = [=]() { executeRef(vertexDeclaration); };
  935. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  936. cb->queueCommand(execute);
  937. }
  938. }
  939. void GLRenderAPI::setDrawOperation(DrawOperationType op, const SPtr<CommandBuffer>& commandBuffer)
  940. {
  941. auto executeRef = [&](DrawOperationType op)
  942. {
  943. THROW_IF_NOT_CORE_THREAD;
  944. mCurrentDrawOperation = op;
  945. };
  946. if (commandBuffer == nullptr)
  947. executeRef(op);
  948. else
  949. {
  950. auto execute = [=]() { executeRef(op); };
  951. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  952. cb->queueCommand(execute);
  953. cb->mCurrentDrawOperation = op;
  954. }
  955. }
  956. void GLRenderAPI::setIndexBuffer(const SPtr<IndexBuffer>& buffer, const SPtr<CommandBuffer>& commandBuffer)
  957. {
  958. auto executeRef = [&](const SPtr<IndexBuffer>& buffer)
  959. {
  960. THROW_IF_NOT_CORE_THREAD;
  961. mBoundIndexBuffer = buffer;
  962. };
  963. if (commandBuffer == nullptr)
  964. executeRef(buffer);
  965. else
  966. {
  967. auto execute = [=]() { executeRef(buffer); };
  968. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  969. cb->queueCommand(execute);
  970. }
  971. }
  972. void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount,
  973. const SPtr<CommandBuffer>& commandBuffer)
  974. {
  975. auto executeRef = [&](UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount)
  976. {
  977. THROW_IF_NOT_CORE_THREAD;
  978. // Find the correct type to render
  979. GLint primType = getGLDrawMode();
  980. beginDraw();
  981. if (instanceCount <= 1)
  982. {
  983. glDrawArrays(primType, vertexOffset, vertexCount);
  984. BS_CHECK_GL_ERROR();
  985. }
  986. else
  987. {
  988. glDrawArraysInstanced(primType, vertexOffset, vertexCount, instanceCount);
  989. BS_CHECK_GL_ERROR();
  990. }
  991. endDraw();
  992. };
  993. UINT32 primCount;
  994. if (commandBuffer == nullptr)
  995. {
  996. executeRef(vertexOffset, vertexCount, instanceCount);
  997. primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  998. }
  999. else
  1000. {
  1001. auto execute = [=]() { executeRef(vertexOffset, vertexCount, instanceCount); };
  1002. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1003. cb->queueCommand(execute);
  1004. primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
  1005. }
  1006. BS_INC_RENDER_STAT(NumDrawCalls);
  1007. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1008. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1009. }
  1010. void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  1011. UINT32 instanceCount, const SPtr<CommandBuffer>& commandBuffer)
  1012. {
  1013. auto executeRef = [&](UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  1014. UINT32 instanceCount)
  1015. {
  1016. THROW_IF_NOT_CORE_THREAD;
  1017. if (mBoundIndexBuffer == nullptr)
  1018. {
  1019. LOGWRN("Cannot draw indexed because index buffer is not set.");
  1020. return;
  1021. }
  1022. // Find the correct type to render
  1023. GLint primType = getGLDrawMode();
  1024. beginDraw();
  1025. SPtr<GLIndexBuffer> indexBuffer = std::static_pointer_cast<GLIndexBuffer>(mBoundIndexBuffer);
  1026. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  1027. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  1028. BS_CHECK_GL_ERROR();
  1029. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  1030. if (instanceCount <= 1)
  1031. {
  1032. glDrawElementsBaseVertex(
  1033. primType,
  1034. indexCount,
  1035. indexType,
  1036. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
  1037. vertexOffset);
  1038. BS_CHECK_GL_ERROR();
  1039. }
  1040. else
  1041. {
  1042. glDrawElementsInstancedBaseVertex(
  1043. primType,
  1044. indexCount,
  1045. indexType,
  1046. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
  1047. instanceCount,
  1048. vertexOffset);
  1049. BS_CHECK_GL_ERROR();
  1050. }
  1051. endDraw();
  1052. };
  1053. UINT32 primCount;
  1054. if (commandBuffer == nullptr)
  1055. {
  1056. executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount);
  1057. primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  1058. }
  1059. else
  1060. {
  1061. auto execute = [=]() { executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount); };
  1062. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1063. cb->queueCommand(execute);
  1064. primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
  1065. }
  1066. BS_INC_RENDER_STAT(NumDrawCalls);
  1067. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1068. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1069. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  1070. }
  1071. void GLRenderAPI::dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ,
  1072. const SPtr<CommandBuffer>& commandBuffer)
  1073. {
  1074. auto executeRef = [&](UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ)
  1075. {
  1076. THROW_IF_NOT_CORE_THREAD;
  1077. if (mCurrentComputeProgram == nullptr)
  1078. {
  1079. LOGWRN("Cannot dispatch compute without a set compute program.");
  1080. return;
  1081. }
  1082. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  1083. glUseProgram(mCurrentComputeProgram->getGLHandle());
  1084. BS_CHECK_GL_ERROR();
  1085. glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);
  1086. BS_CHECK_GL_ERROR();
  1087. #else
  1088. LOGWRN("Compute shaders not supported on current OpenGL version.");
  1089. #endif
  1090. };
  1091. if (commandBuffer == nullptr)
  1092. executeRef(numGroupsX, numGroupsY, numGroupsZ);
  1093. else
  1094. {
  1095. auto execute = [=]() { executeRef(numGroupsX, numGroupsY, numGroupsZ); };
  1096. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1097. cb->queueCommand(execute);
  1098. }
  1099. BS_INC_RENDER_STAT(NumComputeCalls);
  1100. }
  1101. void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom,
  1102. const SPtr<CommandBuffer>& commandBuffer)
  1103. {
  1104. auto executeRef = [&](UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  1105. {
  1106. THROW_IF_NOT_CORE_THREAD;
  1107. mScissorTop = top;
  1108. mScissorBottom = bottom;
  1109. mScissorLeft = left;
  1110. mScissorRight = right;
  1111. };
  1112. if (commandBuffer == nullptr)
  1113. executeRef(left, top, right, bottom);
  1114. else
  1115. {
  1116. auto execute = [=]() { executeRef(left, top, right, bottom); };
  1117. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1118. cb->queueCommand(execute);
  1119. }
  1120. }
  1121. void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
  1122. const SPtr<CommandBuffer>& commandBuffer)
  1123. {
  1124. auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  1125. {
  1126. if (mActiveRenderTarget == nullptr)
  1127. return;
  1128. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1129. Rect2I clearRect(0, 0, rtProps.width, rtProps.height);
  1130. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  1131. };
  1132. if (commandBuffer == nullptr)
  1133. executeRef(buffers, color, depth, stencil, targetMask);
  1134. else
  1135. {
  1136. auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
  1137. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1138. cb->queueCommand(execute);
  1139. }
  1140. }
  1141. void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
  1142. const SPtr<CommandBuffer>& commandBuffer)
  1143. {
  1144. auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  1145. {
  1146. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1147. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  1148. };
  1149. if (commandBuffer == nullptr)
  1150. executeRef(buffers, color, depth, stencil, targetMask);
  1151. else
  1152. {
  1153. auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
  1154. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1155. cb->queueCommand(execute);
  1156. }
  1157. }
  1158. void GLRenderAPI::swapBuffers(const SPtr<RenderTarget>& target, UINT32 syncMask)
  1159. {
  1160. THROW_IF_NOT_CORE_THREAD;
  1161. // Switch context if different from current one
  1162. if(!target->getProperties().isWindow)
  1163. return;
  1164. RenderWindow* window = static_cast<RenderWindow*>(target.get());
  1165. SPtr<GLContext> newContext;
  1166. target->getCustomAttribute("GLCONTEXT", &newContext);
  1167. if (newContext && mCurrentContext != newContext)
  1168. switchContext(newContext, *window);
  1169. else
  1170. mCurrentContext->setCurrent(*window);
  1171. target->swapBuffers();
  1172. BS_INC_RENDER_STAT(NumPresents);
  1173. }
  1174. void GLRenderAPI::addCommands(const SPtr<CommandBuffer>& commandBuffer, const SPtr<CommandBuffer>& secondary)
  1175. {
  1176. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1177. SPtr<GLCommandBuffer> secondaryCb = std::static_pointer_cast<GLCommandBuffer>(secondary);
  1178. cb->appendSecondary(secondaryCb);
  1179. }
  1180. void GLRenderAPI::submitCommandBuffer(const SPtr<CommandBuffer>& commandBuffer, UINT32 syncMask)
  1181. {
  1182. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1183. if (cb == nullptr)
  1184. return;
  1185. cb->executeCommands();
  1186. cb->clear();
  1187. }
  1188. void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect,
  1189. UINT8 targetMask)
  1190. {
  1191. THROW_IF_NOT_CORE_THREAD;
  1192. if(mActiveRenderTarget == nullptr)
  1193. return;
  1194. bool colorMask = !mColorWrite[0] || !mColorWrite[1] || !mColorWrite[2] || !mColorWrite[3];
  1195. // Disable scissor test as we want to clear the entire render surface
  1196. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  1197. UINT32 oldScissorTop = mScissorTop;
  1198. UINT32 oldScissorBottom = mScissorBottom;
  1199. UINT32 oldScissorLeft = mScissorLeft;
  1200. UINT32 oldScissorRight = mScissorRight;
  1201. if (scissorTestEnabled)
  1202. {
  1203. glDisable(GL_SCISSOR_TEST);
  1204. BS_CHECK_GL_ERROR();
  1205. }
  1206. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1207. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  1208. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.width && clearRect.height == rtProps.height);
  1209. if (!clearEntireTarget)
  1210. {
  1211. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  1212. setScissorTestEnable(true);
  1213. }
  1214. if (buffers & FBT_COLOR)
  1215. {
  1216. // Enable buffer for writing if it isn't
  1217. if (colorMask)
  1218. {
  1219. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1220. BS_CHECK_GL_ERROR();
  1221. }
  1222. }
  1223. if (buffers & FBT_DEPTH)
  1224. {
  1225. // Enable buffer for writing if it isn't
  1226. if (!mDepthWrite)
  1227. {
  1228. glDepthMask(GL_TRUE);
  1229. BS_CHECK_GL_ERROR();
  1230. }
  1231. }
  1232. if (buffers & FBT_STENCIL)
  1233. {
  1234. // Enable buffer for writing if it isn't
  1235. glStencilMask(0xFFFFFFFF);
  1236. BS_CHECK_GL_ERROR();
  1237. }
  1238. if (targetMask == 0xFF)
  1239. {
  1240. GLbitfield flags = 0;
  1241. if (buffers & FBT_COLOR)
  1242. {
  1243. flags |= GL_COLOR_BUFFER_BIT;
  1244. glClearColor(color.r, color.g, color.b, color.a);
  1245. BS_CHECK_GL_ERROR();
  1246. }
  1247. if (buffers & FBT_DEPTH)
  1248. {
  1249. flags |= GL_DEPTH_BUFFER_BIT;
  1250. glClearDepth(depth);
  1251. BS_CHECK_GL_ERROR();
  1252. }
  1253. if (buffers & FBT_STENCIL)
  1254. {
  1255. flags |= GL_STENCIL_BUFFER_BIT;
  1256. glClearStencil(stencil);
  1257. BS_CHECK_GL_ERROR();
  1258. }
  1259. // Clear buffers
  1260. glClear(flags);
  1261. BS_CHECK_GL_ERROR();
  1262. }
  1263. else
  1264. {
  1265. GLFrameBufferObject* fbo = nullptr;
  1266. mActiveRenderTarget->getCustomAttribute("FBO", &fbo);
  1267. if (buffers & FBT_COLOR)
  1268. {
  1269. for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
  1270. {
  1271. if (fbo->hasColorBuffer(i) && ((1 << i) & targetMask) != 0)
  1272. {
  1273. glClearBufferfv(GL_COLOR, i, (GLfloat*)&color);
  1274. BS_CHECK_GL_ERROR();
  1275. }
  1276. }
  1277. }
  1278. if (buffers & FBT_DEPTH)
  1279. {
  1280. if (buffers & FBT_STENCIL)
  1281. {
  1282. glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
  1283. BS_CHECK_GL_ERROR();
  1284. }
  1285. else
  1286. {
  1287. glClearBufferfv(GL_DEPTH, 0, &depth);
  1288. BS_CHECK_GL_ERROR();
  1289. }
  1290. }
  1291. else if (buffers & FBT_STENCIL)
  1292. {
  1293. INT32 stencilClear = (INT32)stencil;
  1294. glClearBufferiv(GL_STENCIL, 0, &stencilClear);
  1295. BS_CHECK_GL_ERROR();
  1296. }
  1297. }
  1298. if (!clearEntireTarget)
  1299. {
  1300. setScissorTestEnable(false);
  1301. }
  1302. // Restore scissor test
  1303. if (scissorTestEnabled)
  1304. {
  1305. glEnable(GL_SCISSOR_TEST);
  1306. BS_CHECK_GL_ERROR();
  1307. mScissorTop = oldScissorTop;
  1308. mScissorBottom = oldScissorBottom;
  1309. mScissorLeft = oldScissorLeft;
  1310. mScissorRight = oldScissorRight;
  1311. }
  1312. // Reset buffer write state
  1313. if (!mDepthWrite && (buffers & FBT_DEPTH))
  1314. {
  1315. glDepthMask(GL_FALSE);
  1316. BS_CHECK_GL_ERROR();
  1317. }
  1318. if (colorMask && (buffers & FBT_COLOR))
  1319. {
  1320. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1321. BS_CHECK_GL_ERROR();
  1322. }
  1323. if (buffers & FBT_STENCIL)
  1324. {
  1325. glStencilMask(mStencilWriteMask);
  1326. BS_CHECK_GL_ERROR();
  1327. }
  1328. BS_INC_RENDER_STAT(NumClears);
  1329. }
  1330. /************************************************************************/
  1331. /* PRIVATE */
  1332. /************************************************************************/
  1333. void GLRenderAPI::setTextureAddressingMode(UINT16 unit, const UVWAddressingMode& uvw)
  1334. {
  1335. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_S, getTextureAddressingMode(uvw.u));
  1336. BS_CHECK_GL_ERROR();
  1337. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_T, getTextureAddressingMode(uvw.v));
  1338. BS_CHECK_GL_ERROR();
  1339. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_R, getTextureAddressingMode(uvw.w));
  1340. BS_CHECK_GL_ERROR();
  1341. }
  1342. void GLRenderAPI::setTextureBorderColor(UINT16 unit, const Color& color)
  1343. {
  1344. GLfloat border[4] = { color.r, color.g, color.b, color.a };
  1345. glTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_BORDER_COLOR, border);
  1346. BS_CHECK_GL_ERROR();
  1347. }
  1348. void GLRenderAPI::setTextureMipmapBias(UINT16 unit, float bias)
  1349. {
  1350. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_LOD_BIAS, bias);
  1351. BS_CHECK_GL_ERROR();
  1352. }
  1353. void GLRenderAPI::setTextureMipmapRange(UINT16 unit, float min, float max)
  1354. {
  1355. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MIN_LOD, min);
  1356. BS_CHECK_GL_ERROR();
  1357. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_LOD, max);
  1358. BS_CHECK_GL_ERROR();
  1359. }
  1360. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op)
  1361. {
  1362. GLint sourceBlend = getBlendMode(sourceFactor);
  1363. GLint destBlend = getBlendMode(destFactor);
  1364. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  1365. {
  1366. glDisable(GL_BLEND);
  1367. BS_CHECK_GL_ERROR();
  1368. }
  1369. else
  1370. {
  1371. glEnable(GL_BLEND);
  1372. BS_CHECK_GL_ERROR();
  1373. glBlendFunc(sourceBlend, destBlend);
  1374. BS_CHECK_GL_ERROR();
  1375. }
  1376. GLint func = GL_FUNC_ADD;
  1377. switch(op)
  1378. {
  1379. case BO_ADD:
  1380. func = GL_FUNC_ADD;
  1381. break;
  1382. case BO_SUBTRACT:
  1383. func = GL_FUNC_SUBTRACT;
  1384. break;
  1385. case BO_REVERSE_SUBTRACT:
  1386. func = GL_FUNC_REVERSE_SUBTRACT;
  1387. break;
  1388. case BO_MIN:
  1389. func = GL_MIN;
  1390. break;
  1391. case BO_MAX:
  1392. func = GL_MAX;
  1393. break;
  1394. }
  1395. glBlendEquation(func);
  1396. BS_CHECK_GL_ERROR();
  1397. }
  1398. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  1399. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  1400. {
  1401. GLint sourceBlend = getBlendMode(sourceFactor);
  1402. GLint destBlend = getBlendMode(destFactor);
  1403. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  1404. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  1405. if(sourceFactor == BF_ONE && destFactor == BF_ZERO && sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  1406. {
  1407. glDisable(GL_BLEND);
  1408. BS_CHECK_GL_ERROR();
  1409. }
  1410. else
  1411. {
  1412. glEnable(GL_BLEND);
  1413. BS_CHECK_GL_ERROR();
  1414. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  1415. BS_CHECK_GL_ERROR();
  1416. }
  1417. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  1418. switch(op)
  1419. {
  1420. case BO_ADD:
  1421. func = GL_FUNC_ADD;
  1422. break;
  1423. case BO_SUBTRACT:
  1424. func = GL_FUNC_SUBTRACT;
  1425. break;
  1426. case BO_REVERSE_SUBTRACT:
  1427. func = GL_FUNC_REVERSE_SUBTRACT;
  1428. break;
  1429. case BO_MIN:
  1430. func = GL_MIN;
  1431. break;
  1432. case BO_MAX:
  1433. func = GL_MAX;
  1434. break;
  1435. }
  1436. switch(alphaOp)
  1437. {
  1438. case BO_ADD:
  1439. alphaFunc = GL_FUNC_ADD;
  1440. break;
  1441. case BO_SUBTRACT:
  1442. alphaFunc = GL_FUNC_SUBTRACT;
  1443. break;
  1444. case BO_REVERSE_SUBTRACT:
  1445. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  1446. break;
  1447. case BO_MIN:
  1448. alphaFunc = GL_MIN;
  1449. break;
  1450. case BO_MAX:
  1451. alphaFunc = GL_MAX;
  1452. break;
  1453. }
  1454. glBlendEquationSeparate(func, alphaFunc);
  1455. BS_CHECK_GL_ERROR();
  1456. }
  1457. void GLRenderAPI::setAlphaToCoverage(bool enable)
  1458. {
  1459. static bool lasta2c = false;
  1460. if (enable != lasta2c)
  1461. {
  1462. if (enable)
  1463. {
  1464. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1465. BS_CHECK_GL_ERROR();
  1466. }
  1467. else
  1468. {
  1469. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1470. BS_CHECK_GL_ERROR();
  1471. }
  1472. lasta2c = enable;
  1473. }
  1474. }
  1475. void GLRenderAPI::setScissorTestEnable(bool enable)
  1476. {
  1477. if (mActiveRenderTarget == nullptr)
  1478. return;
  1479. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1480. GLsizei x, y, w, h;
  1481. if (enable)
  1482. {
  1483. glEnable(GL_SCISSOR_TEST);
  1484. BS_CHECK_GL_ERROR();
  1485. x = mScissorLeft;
  1486. y = rtProps.height - mScissorBottom;
  1487. w = mScissorRight - mScissorLeft;
  1488. h = mScissorBottom - mScissorTop;
  1489. glScissor(x, y, w, h);
  1490. BS_CHECK_GL_ERROR();
  1491. }
  1492. else
  1493. {
  1494. glDisable(GL_SCISSOR_TEST);
  1495. BS_CHECK_GL_ERROR();
  1496. // GL requires you to reset the scissor when disabling
  1497. x = mViewportLeft;
  1498. y = rtProps.height - (mViewportTop + mViewportHeight);
  1499. w = mViewportWidth;
  1500. h = mViewportHeight;
  1501. glScissor(x, y, w, h);
  1502. BS_CHECK_GL_ERROR();
  1503. }
  1504. mScissorEnabled = enable;
  1505. }
  1506. void GLRenderAPI::setMultisamplingEnable(bool enable)
  1507. {
  1508. if (enable)
  1509. {
  1510. glEnable(GL_MULTISAMPLE);
  1511. BS_CHECK_GL_ERROR();
  1512. }
  1513. else
  1514. {
  1515. glDisable(GL_MULTISAMPLE);
  1516. BS_CHECK_GL_ERROR();
  1517. }
  1518. }
  1519. void GLRenderAPI::setDepthClipEnable(bool enable)
  1520. {
  1521. if (!enable) // If clipping disabled, clamp is enabled
  1522. {
  1523. glEnable(GL_DEPTH_CLAMP);
  1524. BS_CHECK_GL_ERROR();
  1525. }
  1526. else
  1527. {
  1528. glDisable(GL_DEPTH_CLAMP);
  1529. BS_CHECK_GL_ERROR();
  1530. }
  1531. }
  1532. void GLRenderAPI::setAntialiasedLineEnable(bool enable)
  1533. {
  1534. if (enable)
  1535. {
  1536. glEnable(GL_LINE_SMOOTH);
  1537. BS_CHECK_GL_ERROR();
  1538. }
  1539. else
  1540. {
  1541. glDisable(GL_LINE_SMOOTH);
  1542. BS_CHECK_GL_ERROR();
  1543. }
  1544. }
  1545. void GLRenderAPI::setCullingMode(CullingMode mode)
  1546. {
  1547. GLenum cullMode;
  1548. switch( mode )
  1549. {
  1550. case CULL_NONE:
  1551. glDisable(GL_CULL_FACE);
  1552. BS_CHECK_GL_ERROR();
  1553. return;
  1554. default:
  1555. case CULL_CLOCKWISE:
  1556. cullMode = GL_FRONT;
  1557. break;
  1558. case CULL_COUNTERCLOCKWISE:
  1559. cullMode = GL_BACK;
  1560. break;
  1561. }
  1562. glEnable(GL_CULL_FACE);
  1563. BS_CHECK_GL_ERROR();
  1564. glCullFace(cullMode);
  1565. BS_CHECK_GL_ERROR();
  1566. }
  1567. void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
  1568. {
  1569. if (enabled)
  1570. {
  1571. glClearDepth(1.0f);
  1572. BS_CHECK_GL_ERROR();
  1573. glEnable(GL_DEPTH_TEST);
  1574. BS_CHECK_GL_ERROR();
  1575. }
  1576. else
  1577. {
  1578. glDisable(GL_DEPTH_TEST);
  1579. BS_CHECK_GL_ERROR();
  1580. }
  1581. }
  1582. void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
  1583. {
  1584. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  1585. glDepthMask(flag);
  1586. BS_CHECK_GL_ERROR();
  1587. mDepthWrite = enabled;
  1588. }
  1589. void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
  1590. {
  1591. glDepthFunc(convertCompareFunction(func));
  1592. BS_CHECK_GL_ERROR();
  1593. }
  1594. void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
  1595. {
  1596. if (constantBias != 0 || slopeScaleBias != 0)
  1597. {
  1598. glEnable(GL_POLYGON_OFFSET_FILL);
  1599. BS_CHECK_GL_ERROR();
  1600. glEnable(GL_POLYGON_OFFSET_POINT);
  1601. BS_CHECK_GL_ERROR();
  1602. glEnable(GL_POLYGON_OFFSET_LINE);
  1603. BS_CHECK_GL_ERROR();
  1604. float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
  1605. glPolygonOffset(slopeScaleBias, scaledConstantBias);
  1606. BS_CHECK_GL_ERROR();
  1607. }
  1608. else
  1609. {
  1610. glDisable(GL_POLYGON_OFFSET_FILL);
  1611. BS_CHECK_GL_ERROR();
  1612. glDisable(GL_POLYGON_OFFSET_POINT);
  1613. BS_CHECK_GL_ERROR();
  1614. glDisable(GL_POLYGON_OFFSET_LINE);
  1615. BS_CHECK_GL_ERROR();
  1616. }
  1617. }
  1618. void GLRenderAPI::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  1619. {
  1620. glColorMask(red, green, blue, alpha);
  1621. BS_CHECK_GL_ERROR();
  1622. mColorWrite[0] = red;
  1623. mColorWrite[1] = blue;
  1624. mColorWrite[2] = green;
  1625. mColorWrite[3] = alpha;
  1626. }
  1627. void GLRenderAPI::setPolygonMode(PolygonMode level)
  1628. {
  1629. GLenum glmode;
  1630. switch(level)
  1631. {
  1632. case PM_WIREFRAME:
  1633. glmode = GL_LINE;
  1634. break;
  1635. default:
  1636. case PM_SOLID:
  1637. glmode = GL_FILL;
  1638. break;
  1639. }
  1640. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1641. BS_CHECK_GL_ERROR();
  1642. }
  1643. void GLRenderAPI::setStencilCheckEnabled(bool enabled)
  1644. {
  1645. if (enabled)
  1646. {
  1647. glEnable(GL_STENCIL_TEST);
  1648. BS_CHECK_GL_ERROR();
  1649. }
  1650. else
  1651. {
  1652. glDisable(GL_STENCIL_TEST);
  1653. BS_CHECK_GL_ERROR();
  1654. }
  1655. }
  1656. void GLRenderAPI::setStencilBufferOperations(StencilOperation stencilFailOp,
  1657. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  1658. {
  1659. if (front)
  1660. {
  1661. glStencilOpSeparate(
  1662. GL_FRONT,
  1663. convertStencilOp(stencilFailOp),
  1664. convertStencilOp(depthFailOp),
  1665. convertStencilOp(passOp));
  1666. BS_CHECK_GL_ERROR();
  1667. }
  1668. else
  1669. {
  1670. glStencilOpSeparate(
  1671. GL_BACK,
  1672. convertStencilOp(stencilFailOp),
  1673. convertStencilOp(depthFailOp),
  1674. convertStencilOp(passOp));
  1675. BS_CHECK_GL_ERROR();
  1676. }
  1677. }
  1678. void GLRenderAPI::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  1679. {
  1680. mStencilReadMask = mask;
  1681. if(front)
  1682. {
  1683. mStencilCompareFront = func;
  1684. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1685. BS_CHECK_GL_ERROR();
  1686. }
  1687. else
  1688. {
  1689. mStencilCompareBack = func;
  1690. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1691. BS_CHECK_GL_ERROR();
  1692. }
  1693. }
  1694. void GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
  1695. {
  1696. mStencilWriteMask = mask;
  1697. glStencilMask(mask);
  1698. BS_CHECK_GL_ERROR();
  1699. }
  1700. void GLRenderAPI::setStencilRefValue(UINT32 refValue)
  1701. {
  1702. THROW_IF_NOT_CORE_THREAD;
  1703. mStencilRefValue = refValue;
  1704. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1705. BS_CHECK_GL_ERROR();
  1706. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1707. BS_CHECK_GL_ERROR();
  1708. }
  1709. void GLRenderAPI::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  1710. {
  1711. switch(ftype)
  1712. {
  1713. case FT_MIN:
  1714. mMinFilter = fo;
  1715. // Combine with existing mip filter
  1716. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1717. BS_CHECK_GL_ERROR();
  1718. break;
  1719. case FT_MAG:
  1720. switch (fo)
  1721. {
  1722. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1723. case FO_LINEAR:
  1724. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1725. BS_CHECK_GL_ERROR();
  1726. break;
  1727. case FO_POINT:
  1728. case FO_NONE:
  1729. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1730. BS_CHECK_GL_ERROR();
  1731. break;
  1732. default:
  1733. break;
  1734. }
  1735. break;
  1736. case FT_MIP:
  1737. mMipFilter = fo;
  1738. // Combine with existing min filter
  1739. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1740. BS_CHECK_GL_ERROR();
  1741. break;
  1742. }
  1743. }
  1744. void GLRenderAPI::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1745. {
  1746. GLfloat maxSupportAnisotropy = 0;
  1747. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxSupportAnisotropy);
  1748. BS_CHECK_GL_ERROR();
  1749. if (maxAnisotropy > maxSupportAnisotropy)
  1750. maxAnisotropy = maxSupportAnisotropy ? static_cast<UINT32>(maxSupportAnisotropy) : 1;
  1751. if(maxAnisotropy < 1)
  1752. maxAnisotropy = 1;
  1753. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1754. {
  1755. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1756. BS_CHECK_GL_ERROR();
  1757. }
  1758. }
  1759. void GLRenderAPI::setTextureCompareMode(UINT16 unit, CompareFunction compare)
  1760. {
  1761. if (compare == CMPF_ALWAYS_PASS)
  1762. {
  1763. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  1764. BS_CHECK_GL_ERROR();
  1765. }
  1766. else
  1767. {
  1768. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  1769. BS_CHECK_GL_ERROR();
  1770. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_FUNC, convertCompareFunction(compare));
  1771. BS_CHECK_GL_ERROR();
  1772. }
  1773. }
  1774. bool GLRenderAPI::activateGLTextureUnit(UINT16 unit)
  1775. {
  1776. if (mActiveTextureUnit != unit)
  1777. {
  1778. if (unit < getCapabilities(0).getNumCombinedTextureUnits())
  1779. {
  1780. glActiveTexture(GL_TEXTURE0 + unit);
  1781. BS_CHECK_GL_ERROR();
  1782. mActiveTextureUnit = unit;
  1783. return true;
  1784. }
  1785. else if (!unit)
  1786. {
  1787. // Always ok to use the first unit
  1788. return true;
  1789. }
  1790. else
  1791. {
  1792. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1793. ". Supported range: 0 .. " + toString(getCapabilities(0).getNumCombinedTextureUnits() - 1));
  1794. return false;
  1795. }
  1796. }
  1797. else
  1798. {
  1799. return true;
  1800. }
  1801. }
  1802. void GLRenderAPI::beginDraw()
  1803. {
  1804. if(mDrawCallInProgress)
  1805. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1806. mDrawCallInProgress = true;
  1807. if(mCurrentVertexProgram == nullptr)
  1808. {
  1809. LOGWRN("Cannot render without a set vertex shader.");
  1810. return;
  1811. }
  1812. if(mBoundVertexDeclaration == nullptr)
  1813. {
  1814. LOGWRN("Cannot render without a set vertex declaration.");
  1815. return;
  1816. }
  1817. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1818. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1819. glUseProgram(0);
  1820. BS_CHECK_GL_ERROR();
  1821. if(mActivePipeline != pipeline)
  1822. {
  1823. glBindProgramPipeline(pipeline->glHandle);
  1824. BS_CHECK_GL_ERROR();
  1825. mActivePipeline = pipeline;
  1826. }
  1827. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(
  1828. mCurrentVertexProgram,
  1829. mBoundVertexDeclaration,
  1830. mBoundVertexBuffers);
  1831. glBindVertexArray(vao.getGLHandle());
  1832. BS_CHECK_GL_ERROR();
  1833. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1834. }
  1835. void GLRenderAPI::endDraw()
  1836. {
  1837. if(!mDrawCallInProgress)
  1838. return;
  1839. mDrawCallInProgress = false;
  1840. }
  1841. GLfloat GLRenderAPI::getCurrentAnisotropy(UINT16 unit)
  1842. {
  1843. GLfloat curAniso = 0;
  1844. glGetTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1845. BS_CHECK_GL_ERROR();
  1846. return curAniso ? curAniso : 1;
  1847. }
  1848. GLint GLRenderAPI::convertStencilOp(StencilOperation op) const
  1849. {
  1850. switch (op)
  1851. {
  1852. case SOP_KEEP:
  1853. return GL_KEEP;
  1854. case SOP_ZERO:
  1855. return GL_ZERO;
  1856. case SOP_REPLACE:
  1857. return GL_REPLACE;
  1858. case SOP_INCREMENT:
  1859. return GL_INCR;
  1860. case SOP_DECREMENT:
  1861. return GL_DECR;
  1862. case SOP_INCREMENT_WRAP:
  1863. return GL_INCR_WRAP;
  1864. case SOP_DECREMENT_WRAP:
  1865. return GL_DECR_WRAP;
  1866. case SOP_INVERT:
  1867. return GL_INVERT;
  1868. }
  1869. return SOP_KEEP;
  1870. }
  1871. GLint GLRenderAPI::convertCompareFunction(CompareFunction func) const
  1872. {
  1873. switch (func)
  1874. {
  1875. case CMPF_ALWAYS_FAIL:
  1876. return GL_NEVER;
  1877. case CMPF_ALWAYS_PASS:
  1878. return GL_ALWAYS;
  1879. case CMPF_LESS:
  1880. return GL_LESS;
  1881. case CMPF_LESS_EQUAL:
  1882. return GL_LEQUAL;
  1883. case CMPF_EQUAL:
  1884. return GL_EQUAL;
  1885. case CMPF_NOT_EQUAL:
  1886. return GL_NOTEQUAL;
  1887. case CMPF_GREATER_EQUAL:
  1888. return GL_GEQUAL;
  1889. case CMPF_GREATER:
  1890. return GL_GREATER;
  1891. }
  1892. return GL_ALWAYS;
  1893. }
  1894. GLuint GLRenderAPI::getCombinedMinMipFilter() const
  1895. {
  1896. switch (mMinFilter)
  1897. {
  1898. case FO_ANISOTROPIC:
  1899. case FO_LINEAR:
  1900. switch (mMipFilter)
  1901. {
  1902. case FO_ANISOTROPIC:
  1903. case FO_LINEAR:
  1904. // Linear min, linear mip
  1905. return GL_LINEAR_MIPMAP_LINEAR;
  1906. case FO_POINT:
  1907. // Linear min, point mip
  1908. return GL_LINEAR_MIPMAP_NEAREST;
  1909. case FO_NONE:
  1910. // Linear min, no mip
  1911. return GL_LINEAR;
  1912. default:
  1913. break;
  1914. }
  1915. break;
  1916. case FO_POINT:
  1917. case FO_NONE:
  1918. switch (mMipFilter)
  1919. {
  1920. case FO_ANISOTROPIC:
  1921. case FO_LINEAR:
  1922. // Nearest min, linear mip
  1923. return GL_NEAREST_MIPMAP_LINEAR;
  1924. case FO_POINT:
  1925. // Nearest min, point mip
  1926. return GL_NEAREST_MIPMAP_NEAREST;
  1927. case FO_NONE:
  1928. // Nearest min, no mip
  1929. return GL_NEAREST;
  1930. default:
  1931. break;
  1932. }
  1933. break;
  1934. default:
  1935. break;
  1936. }
  1937. // Should never get here
  1938. return 0;
  1939. }
  1940. GLint GLRenderAPI::getBlendMode(BlendFactor blendMode) const
  1941. {
  1942. switch (blendMode)
  1943. {
  1944. case BF_ONE:
  1945. return GL_ONE;
  1946. case BF_ZERO:
  1947. return GL_ZERO;
  1948. case BF_DEST_COLOR:
  1949. return GL_DST_COLOR;
  1950. case BF_SOURCE_COLOR:
  1951. return GL_SRC_COLOR;
  1952. case BF_INV_DEST_COLOR:
  1953. return GL_ONE_MINUS_DST_COLOR;
  1954. case BF_INV_SOURCE_COLOR:
  1955. return GL_ONE_MINUS_SRC_COLOR;
  1956. case BF_DEST_ALPHA:
  1957. return GL_DST_ALPHA;
  1958. case BF_SOURCE_ALPHA:
  1959. return GL_SRC_ALPHA;
  1960. case BF_INV_DEST_ALPHA:
  1961. return GL_ONE_MINUS_DST_ALPHA;
  1962. case BF_INV_SOURCE_ALPHA:
  1963. return GL_ONE_MINUS_SRC_ALPHA;
  1964. }
  1965. return GL_ONE;
  1966. }
  1967. GLint GLRenderAPI::getTextureAddressingMode(TextureAddressingMode tam) const
  1968. {
  1969. switch (tam)
  1970. {
  1971. default:
  1972. case TAM_WRAP:
  1973. return GL_REPEAT;
  1974. case TAM_MIRROR:
  1975. return GL_MIRRORED_REPEAT;
  1976. case TAM_CLAMP:
  1977. return GL_CLAMP_TO_EDGE;
  1978. case TAM_BORDER:
  1979. return GL_CLAMP_TO_BORDER;
  1980. }
  1981. }
  1982. GLint GLRenderAPI::getGLDrawMode() const
  1983. {
  1984. GLint primType;
  1985. // Use adjacency if there is a geometry program and it requested adjacency info
  1986. bool useAdjacency = (mCurrentGeometryProgram != nullptr && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1987. switch (mCurrentDrawOperation)
  1988. {
  1989. case DOT_POINT_LIST:
  1990. primType = GL_POINTS;
  1991. break;
  1992. case DOT_LINE_LIST:
  1993. primType = useAdjacency ? GL_LINES_ADJACENCY : GL_LINES;
  1994. break;
  1995. case DOT_LINE_STRIP:
  1996. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY : GL_LINE_STRIP;
  1997. break;
  1998. default:
  1999. case DOT_TRIANGLE_LIST:
  2000. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY : GL_TRIANGLES;
  2001. break;
  2002. case DOT_TRIANGLE_STRIP:
  2003. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY : GL_TRIANGLE_STRIP;
  2004. break;
  2005. case DOT_TRIANGLE_FAN:
  2006. primType = GL_TRIANGLE_FAN;
  2007. break;
  2008. }
  2009. return primType;
  2010. }
  2011. SPtr<GLSLGpuProgram> GLRenderAPI::getActiveProgram(GpuProgramType gptype) const
  2012. {
  2013. switch (gptype)
  2014. {
  2015. case GPT_VERTEX_PROGRAM:
  2016. return mCurrentVertexProgram;
  2017. case GPT_FRAGMENT_PROGRAM:
  2018. return mCurrentFragmentProgram;
  2019. case GPT_GEOMETRY_PROGRAM:
  2020. return mCurrentGeometryProgram;
  2021. case GPT_DOMAIN_PROGRAM:
  2022. return mCurrentDomainProgram;
  2023. case GPT_HULL_PROGRAM:
  2024. return mCurrentHullProgram;
  2025. case GPT_COMPUTE_PROGRAM:
  2026. return mCurrentComputeProgram;
  2027. default:
  2028. BS_EXCEPT(InvalidParametersException, "Unsupported gpu program type: " + toString(gptype));
  2029. }
  2030. return nullptr;
  2031. }
  2032. void GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
  2033. {
  2034. if(caps->getRenderAPIName() != getName())
  2035. {
  2036. BS_EXCEPT(InvalidParametersException,
  2037. "Trying to initialize GLRenderAPI from RenderSystemCapabilities that do not support OpenGL");
  2038. }
  2039. #if BS_DEBUG_MODE && (BS_OPENGL_4_3 || BS_OPENGLES_3_2)
  2040. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  2041. {
  2042. glDebugMessageCallback(&openGlErrorCallback, 0);
  2043. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  2044. }
  2045. #endif
  2046. bs::HardwareBufferManager::startUp();
  2047. HardwareBufferManager::startUp<GLHardwareBufferManager>();
  2048. // GPU Program Manager setup
  2049. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  2050. if(caps->isShaderProfileSupported("glsl")) // Check for most recent GLSL support
  2051. GpuProgramManager::instance().addFactory("glsl", mGLSLProgramFactory);
  2052. if(caps->isShaderProfileSupported("glsl4_1")) // Check for OpenGL 4.1 compatible version
  2053. GpuProgramManager::instance().addFactory("glsl4_1", mGLSLProgramFactory);
  2054. GLRTTManager::startUp<GLRTTManager>();
  2055. UINT32 curTexUnitOffset = 0;
  2056. for (UINT32 i = 0; i < 6; i++)
  2057. curTexUnitOffset += caps->getNumTextureUnits((GpuProgramType)i);
  2058. UINT32 totalNumTexUnits = curTexUnitOffset;
  2059. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  2060. if (totalNumTexUnits > numCombinedTexUnits)
  2061. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  2062. mNumTextureUnits = numCombinedTexUnits;
  2063. mTextureInfos = bs_newN<TextureInfo>(mNumTextureUnits);
  2064. for (UINT16 i = 0; i < mNumTextureUnits; i++)
  2065. mTextureInfos[i].type = GL_TEXTURE_2D;
  2066. bs::TextureManager::startUp<bs::GLTextureManager>(std::ref(*mGLSupport));
  2067. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  2068. }
  2069. void GLRenderAPI::switchContext(const SPtr<GLContext>& context, const RenderWindow& window)
  2070. {
  2071. // Unbind GPU programs and rebind to new context later, because
  2072. // scene manager treat render system as ONE 'context' ONLY, and it
  2073. // cached the GPU programs using state.
  2074. setGraphicsPipeline(nullptr);
  2075. // It's ready for switching
  2076. if (mCurrentContext)
  2077. mCurrentContext->endCurrent();
  2078. mCurrentContext = context;
  2079. mCurrentContext->setCurrent(window);
  2080. // Must reset depth/colour write mask to according with user desired, otherwise,
  2081. // clearFrameBuffer would be wrong because the value we recorded may be
  2082. // different from the real state stored in GL context.
  2083. glDepthMask(mDepthWrite);
  2084. BS_CHECK_GL_ERROR();
  2085. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  2086. BS_CHECK_GL_ERROR();
  2087. glStencilMask(mStencilWriteMask);
  2088. BS_CHECK_GL_ERROR();
  2089. }
  2090. void GLRenderAPI::initCapabilities(RenderAPICapabilities& caps) const
  2091. {
  2092. Vector<String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  2093. DriverVersion driverVersion;
  2094. if (!tokens.empty())
  2095. {
  2096. driverVersion.major = parseINT32(tokens[0]);
  2097. if (tokens.size() > 1)
  2098. driverVersion.minor = parseINT32(tokens[1]);
  2099. if (tokens.size() > 2)
  2100. driverVersion.release = parseINT32(tokens[2]);
  2101. }
  2102. driverVersion.build = 0;
  2103. caps.setDriverVersion(driverVersion);
  2104. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  2105. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  2106. caps.setDeviceName(deviceName);
  2107. caps.setRenderAPIName(getName());
  2108. // determine vendor
  2109. if (strstr(vendorName, "NVIDIA"))
  2110. caps.setVendor(GPU_NVIDIA);
  2111. else if (strstr(vendorName, "ATI"))
  2112. caps.setVendor(GPU_AMD);
  2113. else if (strstr(vendorName, "AMD"))
  2114. caps.setVendor(GPU_AMD);
  2115. else if (strstr(vendorName, "Intel"))
  2116. caps.setVendor(GPU_INTEL);
  2117. else
  2118. caps.setVendor(GPU_UNKNOWN);
  2119. #if BS_OPENGL_4_1
  2120. caps.addShaderProfile("glsl4_1");
  2121. #endif
  2122. #if BS_OPENGL_4_5
  2123. caps.addShaderProfile("glsl");
  2124. #endif
  2125. caps.setCapability(RSC_TEXTURE_COMPRESSION_BC);
  2126. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2127. caps.setCapability(RSC_GEOMETRY_PROGRAM);
  2128. #endif
  2129. GLint maxOutputVertices;
  2130. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2131. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES, &maxOutputVertices);
  2132. BS_CHECK_GL_ERROR();
  2133. #else
  2134. maxOutputVertices = 0;
  2135. #endif
  2136. caps.setGeometryProgramNumOutputVertices(maxOutputVertices);
  2137. // Max number of fragment shader textures
  2138. GLint units;
  2139. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  2140. BS_CHECK_GL_ERROR();
  2141. caps.setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  2142. // Max number of vertex shader textures
  2143. GLint vUnits;
  2144. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  2145. BS_CHECK_GL_ERROR();
  2146. caps.setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  2147. GLint numUniformBlocks;
  2148. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  2149. BS_CHECK_GL_ERROR();
  2150. caps.setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  2151. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  2152. BS_CHECK_GL_ERROR();
  2153. caps.setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  2154. {
  2155. GLint geomUnits;
  2156. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2157. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  2158. BS_CHECK_GL_ERROR();
  2159. #else
  2160. geomUnits = 0;
  2161. #endif
  2162. caps.setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  2163. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2164. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  2165. BS_CHECK_GL_ERROR();
  2166. #else
  2167. numUniformBlocks = 0;
  2168. #endif
  2169. caps.setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  2170. }
  2171. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  2172. {
  2173. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2174. caps.setCapability(RSC_TESSELLATION_PROGRAM);
  2175. #endif
  2176. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2177. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  2178. BS_CHECK_GL_ERROR();
  2179. #else
  2180. numUniformBlocks = 0;
  2181. #endif
  2182. caps.setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  2183. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2184. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  2185. BS_CHECK_GL_ERROR();
  2186. #else
  2187. numUniformBlocks = 0;
  2188. #endif
  2189. caps.setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  2190. }
  2191. if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
  2192. {
  2193. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2194. caps.setCapability(RSC_COMPUTE_PROGRAM);
  2195. #endif
  2196. GLint computeUnits;
  2197. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2198. glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  2199. BS_CHECK_GL_ERROR();
  2200. #else
  2201. computeUnits = 0;
  2202. #endif
  2203. caps.setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  2204. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2205. glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  2206. BS_CHECK_GL_ERROR();
  2207. #else
  2208. numUniformBlocks = 0;
  2209. #endif
  2210. caps.setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  2211. // Max number of load-store textures
  2212. GLint lsfUnits;
  2213. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2214. glGetIntegerv(GL_MAX_FRAGMENT_IMAGE_UNIFORMS, &lsfUnits);
  2215. BS_CHECK_GL_ERROR();
  2216. #else
  2217. lsfUnits = 0;
  2218. #endif
  2219. caps.setNumLoadStoreTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(lsfUnits));
  2220. GLint lscUnits;
  2221. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2222. glGetIntegerv(GL_MAX_COMPUTE_IMAGE_UNIFORMS, &lscUnits);
  2223. BS_CHECK_GL_ERROR();
  2224. #else
  2225. lscUnits = 0;
  2226. #endif
  2227. caps.setNumLoadStoreTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(lscUnits));
  2228. GLint combinedLoadStoreTextureUnits;
  2229. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2230. glGetIntegerv(GL_MAX_IMAGE_UNITS, &combinedLoadStoreTextureUnits);
  2231. BS_CHECK_GL_ERROR();
  2232. #else
  2233. combinedLoadStoreTextureUnits = 0;
  2234. #endif
  2235. caps.setNumCombinedLoadStoreTextureUnits(static_cast<UINT16>(combinedLoadStoreTextureUnits));
  2236. }
  2237. GLint combinedTexUnits;
  2238. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  2239. BS_CHECK_GL_ERROR();
  2240. caps.setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  2241. GLint combinedUniformBlockUnits;
  2242. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  2243. BS_CHECK_GL_ERROR();
  2244. caps.setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  2245. caps.setNumMultiRenderTargets(8);
  2246. }
  2247. void GLRenderAPI::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  2248. {
  2249. UINT32 x = 0;
  2250. for (UINT32 i = 0; i < 4; i++)
  2251. {
  2252. for (UINT32 j = 0; j < 4; j++)
  2253. {
  2254. gl_matrix[x] = m[j][i];
  2255. x++;
  2256. }
  2257. }
  2258. }
  2259. void GLRenderAPI::applyViewport()
  2260. {
  2261. if (mActiveRenderTarget == nullptr)
  2262. return;
  2263. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  2264. // Calculate the "lower-left" corner of the viewport
  2265. mViewportLeft = (UINT32)(rtProps.width * mViewportNorm.x);
  2266. mViewportTop = (UINT32)(rtProps.height * mViewportNorm.y);
  2267. mViewportWidth = (UINT32)(rtProps.width * mViewportNorm.width);
  2268. mViewportHeight = (UINT32)(rtProps.height * mViewportNorm.height);
  2269. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  2270. BS_CHECK_GL_ERROR();
  2271. // Configure the viewport clipping
  2272. if (!mScissorEnabled)
  2273. {
  2274. glEnable(GL_SCISSOR_TEST);
  2275. BS_CHECK_GL_ERROR();
  2276. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  2277. BS_CHECK_GL_ERROR();
  2278. }
  2279. }
  2280. /************************************************************************/
  2281. /* UTILITY */
  2282. /************************************************************************/
  2283. void GLRenderAPI::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  2284. {
  2285. dest = matrix;
  2286. }
  2287. const RenderAPIInfo& GLRenderAPI::getAPIInfo() const
  2288. {
  2289. RenderAPIFeatures featureFlags =
  2290. RenderAPIFeatureFlag::UVYAxisUp |
  2291. RenderAPIFeatureFlag::ColumnMajorMatrices |
  2292. RenderAPIFeatureFlag::MSAAImageStores;
  2293. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2294. featureFlags |= RenderAPIFeatureFlag::TextureViews;
  2295. featureFlags |= RenderAPIFeatureFlag::Compute;
  2296. #endif
  2297. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2298. featureFlags |= RenderAPIFeatureFlag::LoadStore;
  2299. #endif
  2300. static RenderAPIInfo info(0.0f, 0.0f, -1.0f, 1.0f, VET_COLOR_ABGR, featureFlags);
  2301. return info;
  2302. }
  2303. GpuParamBlockDesc GLRenderAPI::generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params)
  2304. {
  2305. GpuParamBlockDesc block;
  2306. block.blockSize = 0;
  2307. block.isShareable = true;
  2308. block.name = name;
  2309. block.slot = 0;
  2310. block.set = 0;
  2311. for (auto& param : params)
  2312. {
  2313. UINT32 size;
  2314. if(param.type == GPDT_STRUCT)
  2315. {
  2316. // Structs are always aligned and rounded up to vec4
  2317. size = Math::divideAndRoundUp(param.elementSize, 16U) * 4;
  2318. block.blockSize = Math::divideAndRoundUp(block.blockSize, 4U) * 4;
  2319. }
  2320. else
  2321. size = GLSLParamParser::calcInterfaceBlockElementSizeAndOffset(param.type, param.arraySize, block.blockSize);
  2322. if (param.arraySize > 1)
  2323. {
  2324. param.elementSize = size;
  2325. param.arrayElementStride = size;
  2326. param.cpuMemOffset = block.blockSize;
  2327. param.gpuMemOffset = 0;
  2328. block.blockSize += size * param.arraySize;
  2329. }
  2330. else
  2331. {
  2332. param.elementSize = size;
  2333. param.arrayElementStride = size;
  2334. param.cpuMemOffset = block.blockSize;
  2335. param.gpuMemOffset = 0;
  2336. block.blockSize += size;
  2337. }
  2338. param.paramBlockSlot = 0;
  2339. param.paramBlockSet = 0;
  2340. }
  2341. // Constant buffer size must always be a multiple of 16
  2342. if (block.blockSize % 4 != 0)
  2343. block.blockSize += (4 - (block.blockSize % 4));
  2344. return block;
  2345. }
  2346. #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
  2347. void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  2348. const GLchar *message, GLvoid *userParam)
  2349. {
  2350. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  2351. {
  2352. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  2353. }
  2354. }
  2355. #endif
  2356. }}