BsGLRenderAPI.cpp 68 KB

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