BsGLRenderAPI.cpp 68 KB

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