BsGLRenderAPI.cpp 73 KB

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