BsGLRenderAPI.cpp 72 KB

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