BsGLRenderAPI.cpp 68 KB

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