BsGLRenderAPI.cpp 72 KB

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