BsGLRenderAPI.cpp 65 KB

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