BsGLRenderAPI.cpp 66 KB

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