BsGLRenderAPI.cpp 74 KB

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