BsGLRenderAPI.cpp 74 KB

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