BsGLRenderAPI.cpp 73 KB

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