BsGLRenderAPI.cpp 66 KB

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