renderer_gl.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515
  1. /*
  2. * Copyright 2011-2013 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if (BGFX_CONFIG_RENDERER_OPENGLES2|BGFX_CONFIG_RENDERER_OPENGLES3|BGFX_CONFIG_RENDERER_OPENGL)
  7. # include "renderer_gl.h"
  8. # include <bx/timer.h>
  9. # include <bx/uint32_t.h>
  10. namespace bgfx
  11. {
  12. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][256];
  13. struct Extension
  14. {
  15. enum Enum
  16. {
  17. ANGLE_instanced_arrays,
  18. ANGLE_translated_shader_source,
  19. ARB_debug_output,
  20. ARB_framebuffer_sRGB,
  21. ARB_get_program_binary,
  22. ARB_half_float_vertex,
  23. ARB_instanced_arrays,
  24. ARB_multisample,
  25. ARB_seamless_cube_map,
  26. ARB_texture_float,
  27. ARB_texture_multisample,
  28. ARB_texture_swizzle,
  29. ARB_timer_query,
  30. ARB_vertex_array_object,
  31. ARB_vertex_type_2_10_10_10_rev,
  32. ATI_meminfo,
  33. CHROMIUM_framebuffer_multisample,
  34. CHROMIUM_texture_compression_dxt3,
  35. CHROMIUM_texture_compression_dxt5,
  36. EXT_bgra,
  37. EXT_blend_color,
  38. EXT_blend_minmax,
  39. EXT_blend_subtract,
  40. EXT_framebuffer_blit,
  41. EXT_framebuffer_sRGB,
  42. EXT_occlusion_query_boolean,
  43. EXT_texture_compression_dxt1,
  44. EXT_texture_compression_latc,
  45. EXT_texture_compression_rgtc,
  46. EXT_texture_compression_s3tc,
  47. EXT_texture_filter_anisotropic,
  48. EXT_texture_format_BGRA8888,
  49. EXT_texture_sRGB,
  50. EXT_texture_storage,
  51. EXT_texture_swizzle,
  52. EXT_texture_type_2_10_10_10_REV,
  53. EXT_timer_query,
  54. NVX_gpu_memory_info,
  55. OES_get_program_binary,
  56. OES_rgb8_rgba8,
  57. OES_standard_derivatives,
  58. OES_texture_float,
  59. OES_texture_float_linear,
  60. OES_texture_half_float,
  61. OES_texture_half_float_linear,
  62. OES_vertex_array_object,
  63. OES_vertex_half_float,
  64. OES_vertex_type_10_10_10_2,
  65. Count
  66. };
  67. const char* m_name;
  68. bool m_supported;
  69. bool m_initialize;
  70. };
  71. static Extension s_extension[Extension::Count] =
  72. {
  73. { "GL_ANGLE_instanced_arrays", false, true },
  74. { "GL_ANGLE_translated_shader_source", false, true },
  75. { "GL_ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  76. { "GL_ARB_framebuffer_sRGB", false, true },
  77. { "GL_ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  78. { "GL_ARB_half_float_vertex", false, true },
  79. { "GL_ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  80. { "GL_ARB_multisample", false, true },
  81. { "GL_ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  82. { "GL_ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  83. { "GL_ARB_texture_multisample", false, true },
  84. { "GL_ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  85. { "GL_ARB_timer_query", false, true },
  86. { "GL_ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  87. { "GL_ARB_vertex_type_2_10_10_10_rev", false, true },
  88. { "GL_ATI_meminfo", false, true },
  89. { "GL_CHROMIUM_framebuffer_multisample", false, true },
  90. { "GL_CHROMIUM_texture_compression_dxt3", false, true },
  91. { "GL_CHROMIUM_texture_compression_dxt5", false, true },
  92. { "GL_EXT_bgra", false, true },
  93. { "GL_EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  94. { "GL_EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  95. { "GL_EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  96. { "GL_EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  97. { "GL_EXT_framebuffer_sRGB", false, true },
  98. { "GL_EXT_occlusion_query_boolean", false, true },
  99. { "GL_EXT_texture_compression_dxt1", false, true },
  100. { "GL_EXT_texture_compression_latc", false, true },
  101. { "GL_EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  102. { "GL_EXT_texture_compression_s3tc", false, true },
  103. { "GL_EXT_texture_filter_anisotropic", false, true },
  104. { "GL_EXT_texture_format_BGRA8888", false, true },
  105. { "GL_EXT_texture_sRGB", false, true },
  106. { "GL_EXT_texture_storage", false, true },
  107. { "GL_EXT_texture_swizzle", false, true },
  108. { "GL_EXT_texture_type_2_10_10_10_REV", false, true },
  109. { "GL_EXT_timer_query", false, true },
  110. { "GL_NVX_gpu_memory_info", false, true },
  111. { "GL_OES_get_program_binary", false, false },
  112. { "GL_OES_rgb8_rgba8", false, true },
  113. { "GL_OES_standard_derivatives", false, true },
  114. { "GL_OES_texture_float", false, true },
  115. { "GL_OES_texture_float_linear", false, true },
  116. { "GL_OES_texture_half_float", false, true },
  117. { "GL_OES_texture_half_float_linear", false, true },
  118. { "GL_OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  119. { "GL_OES_vertex_half_float", false, true },
  120. { "GL_OES_vertex_type_10_10_10_2", false, true },
  121. };
  122. #if BGFX_CONFIG_RENDERER_OPENGLES3
  123. # define s_vertexAttribDivisor glVertexAttribDivisor
  124. # define s_drawArraysInstanced glDrawArraysInstanced
  125. # define s_drawElementsInstanced glDrawElementsInstanced
  126. #else
  127. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  128. {
  129. }
  130. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  131. {
  132. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  133. }
  134. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  135. {
  136. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  137. }
  138. static PFNGLVERTEXATTRIBDIVISORBGFXPROC s_vertexAttribDivisor = stubVertexAttribDivisor;
  139. static PFNGLDRAWARRAYSINSTANCEDBGFXPROC s_drawArraysInstanced = stubDrawArraysInstanced;
  140. static PFNGLDRAWELEMENTSINSTANCEDBGFXPROC s_drawElementsInstanced = stubDrawElementsInstanced;
  141. #endif // BGFX_CONFIG_RENDERER_OPENGLES3
  142. #if BGFX_CONFIG_DEBUG_GREMEDY
  143. static void GL_APIENTRY stubStringMarkerGREMEDY(GLsizei /*_len*/, const GLvoid* /*_string*/)
  144. {
  145. }
  146. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  147. {
  148. }
  149. #endif // BGFX_CONFIG_DEBUG_GREMEDY
  150. #if BX_PLATFORM_IOS
  151. PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES = NULL;
  152. PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES = NULL;
  153. PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES = NULL;
  154. PFNGLPROGRAMBINARYOESPROC glProgramBinaryOES = NULL;
  155. PFNGLGETPROGRAMBINARYOESPROC glGetProgramBinaryOES = NULL;
  156. PFLGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstanced = NULL;
  157. PFLGLDRAWELEMENTSINSTANCEDANGLEPROC glDrawElementsInstanced = NULL;
  158. #endif // BX_PLATFORM_IOS
  159. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  160. static void rgbaToBgra(uint8_t* _data, uint32_t _width, uint32_t _height)
  161. {
  162. uint32_t dstpitch = _width*4;
  163. for (uint32_t yy = 0; yy < _height; ++yy)
  164. {
  165. uint8_t* dst = &_data[yy*dstpitch];
  166. for (uint32_t xx = 0; xx < _width; ++xx)
  167. {
  168. uint8_t tmp = dst[0];
  169. dst[0] = dst[2];
  170. dst[2] = tmp;
  171. dst += 4;
  172. }
  173. }
  174. }
  175. static const char* getGLString(GLenum _name)
  176. {
  177. const char* str = (const char*)glGetString(_name);
  178. glGetError(); // ignore error if glGetString returns NULL.
  179. if (NULL != str)
  180. {
  181. return str;
  182. }
  183. return "<unknown>";
  184. }
  185. static uint32_t getGLStringHash(GLenum _name)
  186. {
  187. const char* str = (const char*)glGetString(_name);
  188. glGetError(); // ignore error if glGetString returns NULL.
  189. if (NULL != str)
  190. {
  191. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  192. }
  193. return 0;
  194. }
  195. void dumpExtensions(const char* _extensions)
  196. {
  197. if (NULL != _extensions)
  198. {
  199. char name[1024];
  200. const char* pos = _extensions;
  201. const char* end = _extensions + strlen(_extensions);
  202. while (pos < end)
  203. {
  204. uint32_t len;
  205. const char* space = strchr(pos, ' ');
  206. if (NULL != space)
  207. {
  208. len = uint32_min(sizeof(name), (uint32_t)(space - pos) );
  209. }
  210. else
  211. {
  212. len = uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  213. }
  214. strncpy(name, pos, len);
  215. name[len] = '\0';
  216. BX_TRACE("\t%s", name);
  217. pos += len+1;
  218. }
  219. }
  220. }
  221. #if BGFX_CONFIG_RENDERER_OPENGL
  222. const char* toString(GLenum _enum)
  223. {
  224. switch (_enum)
  225. {
  226. case GL_DEBUG_SOURCE_API_ARB: return "API";
  227. case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: return "WinSys";
  228. case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: return "Shader";
  229. case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: return "3rdparty";
  230. case GL_DEBUG_SOURCE_APPLICATION_ARB: return "Application";
  231. case GL_DEBUG_SOURCE_OTHER_ARB: return "Other";
  232. case GL_DEBUG_TYPE_ERROR_ARB: return "Error";
  233. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: return "Deprecated behavior";
  234. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: return "Undefined behavior";
  235. case GL_DEBUG_TYPE_PORTABILITY_ARB: return "Portability";
  236. case GL_DEBUG_TYPE_PERFORMANCE_ARB: return "Performance";
  237. case GL_DEBUG_TYPE_OTHER_ARB: return "Other";
  238. case GL_DEBUG_SEVERITY_HIGH_ARB: return "High";
  239. case GL_DEBUG_SEVERITY_MEDIUM_ARB: return "Medium";
  240. case GL_DEBUG_SEVERITY_LOW_ARB: return "Low";
  241. default:
  242. break;
  243. }
  244. return "<unknown>";
  245. }
  246. static void APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, GLvoid* /*_userParam*/)
  247. {
  248. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  249. , toString(_source)
  250. , toString(_type)
  251. , _id
  252. , toString(_severity)
  253. , _message
  254. );
  255. BX_UNUSED(_source, _type, _id, _severity, _message);
  256. }
  257. #endif // BGFX_CONFIG_RENDERER_OPENGL
  258. struct RendererContext
  259. {
  260. RendererContext()
  261. : m_rtMsaa(false)
  262. , m_capture(NULL)
  263. , m_captureSize(0)
  264. , m_maxAnisotropy(0.0f)
  265. , m_maxMsaa(0)
  266. , m_vao(0)
  267. , m_vaoSupport(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  268. , m_programBinarySupport(false)
  269. , m_textureSwizzleSupport(false)
  270. , m_useClearQuad(true)
  271. , m_flip(false)
  272. , m_postSwapBuffers(NULL)
  273. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  274. , m_backBufferFbo(0)
  275. , m_msaaBackBufferFbo(0)
  276. {
  277. m_rt.idx = invalidHandle;
  278. memset(&m_resolution, 0, sizeof(m_resolution) );
  279. }
  280. void updateResolution(const Resolution& _resolution)
  281. {
  282. if (m_resolution.m_width != _resolution.m_width
  283. || m_resolution.m_height != _resolution.m_height
  284. || m_resolution.m_flags != _resolution.m_flags)
  285. {
  286. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  287. m_textVideoMem.clear();
  288. m_resolution = _resolution;
  289. uint32_t msaa = 1<<( (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT);
  290. msaa = uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  291. bool vsync = !!(m_resolution.m_flags&BGFX_RESET_VSYNC);
  292. setRenderContextSize(_resolution.m_width, _resolution.m_height, msaa, vsync);
  293. updateCapture();
  294. }
  295. }
  296. uint32_t setRenderTarget(RenderTargetHandle _rt, uint32_t _height, bool _msaa = true)
  297. {
  298. if (m_rt.idx != invalidHandle
  299. && m_rt.idx != _rt.idx
  300. && m_rtMsaa)
  301. {
  302. RenderTarget& renderTarget = m_renderTargets[m_rt.idx];
  303. if (0 != renderTarget.m_fbo[1])
  304. {
  305. renderTarget.resolve();
  306. }
  307. }
  308. if (_rt.idx == invalidHandle)
  309. {
  310. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  311. }
  312. else
  313. {
  314. RenderTarget& renderTarget = m_renderTargets[_rt.idx];
  315. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, renderTarget.m_fbo[0]) );
  316. _height = renderTarget.m_height;
  317. }
  318. m_rt = _rt;
  319. m_rtMsaa = _msaa;
  320. return _height;
  321. }
  322. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  323. {
  324. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  325. if (1 < _msaa)
  326. {
  327. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  328. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  329. GL_CHECK(glGenRenderbuffers(3, m_msaaBackBufferRbos) );
  330. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  331. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  332. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  333. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  334. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  335. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  336. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  337. , "glCheckFramebufferStatus failed 0x%08x"
  338. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  339. );
  340. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  341. }
  342. #else
  343. BX_UNUSED(_width);
  344. BX_UNUSED(_height);
  345. BX_UNUSED(_msaa);
  346. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  347. }
  348. void destroyMsaaFbo()
  349. {
  350. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  351. if (0 != m_msaaBackBufferFbo)
  352. {
  353. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  354. GL_CHECK(glDeleteRenderbuffers(3, m_msaaBackBufferRbos) );
  355. m_msaaBackBufferFbo = 0;
  356. }
  357. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  358. }
  359. void blitMsaaFbo()
  360. {
  361. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  362. if (0 != m_msaaBackBufferFbo)
  363. {
  364. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  365. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  366. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  367. uint32_t width = m_resolution.m_width;
  368. uint32_t height = m_resolution.m_height;
  369. GL_CHECK(glBlitFramebuffer(0
  370. , 0
  371. , width
  372. , height
  373. , 0
  374. , 0
  375. , width
  376. , height
  377. , GL_COLOR_BUFFER_BIT
  378. , GL_LINEAR
  379. ) );
  380. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  381. }
  382. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  383. }
  384. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _msaa = 0, bool _vsync = false)
  385. {
  386. if (_width != 0
  387. || _height != 0)
  388. {
  389. if (!m_glctx.isValid() )
  390. {
  391. m_glctx.create(_width, _height);
  392. #if BX_PLATFORM_IOS
  393. // BK - Temp, need to figure out how to deal with FBO created by context.
  394. m_backBufferFbo = m_glctx.m_fbo;
  395. #endif // BX_PLATFORM_IOS
  396. }
  397. else
  398. {
  399. destroyMsaaFbo();
  400. m_glctx.resize(_width, _height, _vsync);
  401. createMsaaFbo(_width, _height, _msaa);
  402. }
  403. }
  404. m_flip = true;
  405. }
  406. void flip()
  407. {
  408. if (m_flip)
  409. {
  410. m_glctx.swap();
  411. }
  412. if (NULL != m_postSwapBuffers)
  413. {
  414. m_postSwapBuffers(m_resolution.m_width, m_resolution.m_height);
  415. }
  416. }
  417. void invalidateCache()
  418. {
  419. if (m_vaoSupport)
  420. {
  421. m_vaoCache.invalidate();
  422. }
  423. }
  424. void updateCapture()
  425. {
  426. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  427. {
  428. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  429. m_capture = g_realloc(m_capture, m_captureSize);
  430. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  431. }
  432. else
  433. {
  434. if (NULL != m_capture)
  435. {
  436. g_callback->captureEnd();
  437. g_free(m_capture);
  438. m_capture = NULL;
  439. m_captureSize = 0;
  440. }
  441. }
  442. }
  443. void capture()
  444. {
  445. if (NULL != m_capture)
  446. {
  447. GLint fmt = s_extension[Extension::EXT_texture_format_BGRA8888].m_supported ? GL_BGRA_EXT : GL_RGBA;
  448. GL_CHECK(glReadPixels(0
  449. , 0
  450. , m_resolution.m_width
  451. , m_resolution.m_height
  452. , fmt
  453. , GL_UNSIGNED_BYTE
  454. , m_capture
  455. ) );
  456. g_callback->captureFrame(m_capture, m_captureSize);
  457. }
  458. }
  459. void saveScreenShot(const char* _filePath)
  460. {
  461. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  462. uint8_t* data = (uint8_t*)g_realloc(NULL, length);
  463. GLint fmt = s_extension[Extension::EXT_texture_format_BGRA8888].m_supported ? GL_BGRA_EXT : GL_RGBA;
  464. uint32_t width = m_resolution.m_width;
  465. uint32_t height = m_resolution.m_height;
  466. GL_CHECK(glReadPixels(0
  467. , 0
  468. , width
  469. , height
  470. , fmt
  471. , GL_UNSIGNED_BYTE
  472. , data
  473. ) );
  474. if (GL_RGBA == fmt)
  475. {
  476. rgbaToBgra(data, width, height);
  477. }
  478. g_callback->screenShot(_filePath
  479. , width
  480. , height
  481. , width*4
  482. , data
  483. , length
  484. , true
  485. );
  486. g_free(data);
  487. }
  488. void init()
  489. {
  490. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  491. m_vendor = getGLString(GL_VENDOR);
  492. m_renderer = getGLString(GL_RENDERER);
  493. m_version = getGLString(GL_VERSION);
  494. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  495. #if BGFX_CONFIG_DEBUG_GREMEDY
  496. if (NULL == glStringMarkerGREMEDY
  497. || NULL == glFrameTerminatorGREMEDY)
  498. {
  499. glStringMarkerGREMEDY = stubStringMarkerGREMEDY;
  500. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  501. }
  502. #endif // BGFX_CONFIG_DEBUG_GREMEDY
  503. #if BGFX_CONFIG_RENDERER_OPENGL
  504. m_queries.create();
  505. #endif // BGFX_CONFIG_RENDERER_OPENGL
  506. }
  507. void shutdown()
  508. {
  509. invalidateCache();
  510. #if BGFX_CONFIG_RENDERER_OPENGL
  511. m_queries.destroy();
  512. #endif // BGFX_CONFIG_RENDERER_OPENGL
  513. destroyMsaaFbo();
  514. m_glctx.destroy();
  515. m_flip = false;
  516. }
  517. IndexBuffer m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  518. VertexBuffer m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  519. Shader m_vertexShaders[BGFX_CONFIG_MAX_VERTEX_SHADERS];
  520. Shader m_fragmentShaders[BGFX_CONFIG_MAX_FRAGMENT_SHADERS];
  521. Program m_program[BGFX_CONFIG_MAX_PROGRAMS];
  522. Texture m_textures[BGFX_CONFIG_MAX_TEXTURES];
  523. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  524. RenderTarget m_renderTargets[BGFX_CONFIG_MAX_RENDER_TARGETS];
  525. UniformRegistry m_uniformReg;
  526. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  527. #if BGFX_CONFIG_RENDERER_OPENGL
  528. Queries m_queries;
  529. #endif // BGFX_CONFIG_RENDERER_OPENGL
  530. VaoCache m_vaoCache;
  531. TextVideoMem m_textVideoMem;
  532. RenderTargetHandle m_rt;
  533. bool m_rtMsaa;
  534. Resolution m_resolution;
  535. void* m_capture;
  536. uint32_t m_captureSize;
  537. float m_maxAnisotropy;
  538. int32_t m_maxMsaa;
  539. GLuint m_vao;
  540. bool m_vaoSupport;
  541. bool m_programBinarySupport;
  542. bool m_textureSwizzleSupport;
  543. bool m_useClearQuad;
  544. bool m_flip;
  545. PostSwapBuffersFn m_postSwapBuffers;
  546. uint64_t m_hash;
  547. GLuint m_backBufferFbo;
  548. GLuint m_msaaBackBufferFbo;
  549. GLuint m_msaaBackBufferRbos[2];
  550. GlContext m_glctx;
  551. const char* m_vendor;
  552. const char* m_renderer;
  553. const char* m_version;
  554. const char* m_glslVersion;
  555. };
  556. RendererContext s_renderCtx;
  557. #if BX_PLATFORM_NACL
  558. static void GL_APIENTRY naclVertexAttribDivisor(GLuint _index, GLuint _divisor)
  559. {
  560. s_renderCtx.m_glctx.m_instancedArrays->VertexAttribDivisorANGLE(s_renderCtx.m_glctx.m_context, _index, _divisor);
  561. }
  562. static void GL_APIENTRY naclDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei _primcount)
  563. {
  564. s_renderCtx.m_glctx.m_instancedArrays->DrawArraysInstancedANGLE(s_renderCtx.m_glctx.m_context, _mode, _first, _count, _primcount);
  565. }
  566. static void GL_APIENTRY naclDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei _primcount)
  567. {
  568. s_renderCtx.m_glctx.m_instancedArrays->DrawElementsInstancedANGLE(s_renderCtx.m_glctx.m_context, _mode, _count, _type, _indices, _primcount);
  569. }
  570. void naclSetIntefraces(PP_Instance _instance, const PPB_Instance* _instInterface, const PPB_Graphics3D* _graphicsInterface, PostSwapBuffersFn _postSwapBuffers)
  571. {
  572. s_renderCtx.m_glctx.m_instance = _instance;
  573. s_renderCtx.m_glctx.m_instInterface = _instInterface;
  574. s_renderCtx.m_glctx.m_graphicsInterface = _graphicsInterface;
  575. s_renderCtx.m_postSwapBuffers = _postSwapBuffers;
  576. s_renderCtx.m_glctx.m_instancedArrays = glGetInstancedArraysInterfacePPAPI();
  577. s_renderCtx.setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  578. if (NULL != s_renderCtx.m_glctx.m_instancedArrays)
  579. {
  580. s_vertexAttribDivisor = naclVertexAttribDivisor;
  581. s_drawArraysInstanced = naclDrawArraysInstanced;
  582. s_drawElementsInstanced = naclDrawElementsInstanced;
  583. }
  584. }
  585. void naclSwapCompleteCb(void* /*_data*/, int32_t /*_result*/)
  586. {
  587. renderFrame();
  588. }
  589. #endif // BX_PLATFORM_
  590. static const GLenum s_primType[] =
  591. {
  592. GL_TRIANGLES,
  593. GL_LINES,
  594. GL_POINTS,
  595. };
  596. static const char* s_attribName[Attrib::Count] =
  597. {
  598. "a_position",
  599. "a_normal",
  600. "a_tangent",
  601. "a_color0",
  602. "a_color1",
  603. "a_indices",
  604. "a_weight",
  605. "a_texcoord0",
  606. "a_texcoord1",
  607. "a_texcoord2",
  608. "a_texcoord3",
  609. "a_texcoord4",
  610. "a_texcoord5",
  611. "a_texcoord6",
  612. "a_texcoord7",
  613. };
  614. static const char* s_instanceDataName[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT] =
  615. {
  616. "i_data0",
  617. "i_data1",
  618. "i_data2",
  619. "i_data3",
  620. "i_data4",
  621. };
  622. static const GLenum s_attribType[AttribType::Count] =
  623. {
  624. GL_UNSIGNED_BYTE,
  625. GL_SHORT,
  626. GL_HALF_FLOAT,
  627. GL_FLOAT,
  628. };
  629. struct Blend
  630. {
  631. GLenum m_src;
  632. GLenum m_dst;
  633. bool m_factor;
  634. };
  635. static const Blend s_blendFactor[] =
  636. {
  637. { 0, 0, false }, // ignored
  638. { GL_ZERO, GL_ZERO, false },
  639. { GL_ONE, GL_ONE, false },
  640. { GL_SRC_COLOR, GL_SRC_COLOR, false },
  641. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false },
  642. { GL_SRC_ALPHA, GL_SRC_ALPHA, false },
  643. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false },
  644. { GL_DST_ALPHA, GL_DST_ALPHA, false },
  645. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false },
  646. { GL_DST_COLOR, GL_DST_COLOR, false },
  647. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false },
  648. { GL_SRC_ALPHA_SATURATE, GL_ONE, false },
  649. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true },
  650. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true },
  651. };
  652. static const GLenum s_blendEquation[] =
  653. {
  654. GL_FUNC_ADD,
  655. GL_FUNC_SUBTRACT,
  656. GL_FUNC_REVERSE_SUBTRACT,
  657. GL_MIN,
  658. GL_MAX,
  659. };
  660. static const GLenum s_depthFunc[] =
  661. {
  662. 0, // ignored
  663. GL_LESS,
  664. GL_LEQUAL,
  665. GL_EQUAL,
  666. GL_GEQUAL,
  667. GL_GREATER,
  668. GL_NOTEQUAL,
  669. GL_NEVER,
  670. GL_ALWAYS,
  671. };
  672. static const GLenum s_stencilFunc[] =
  673. {
  674. 0, // ignored
  675. GL_LESS,
  676. GL_LEQUAL,
  677. GL_EQUAL,
  678. GL_GEQUAL,
  679. GL_GREATER,
  680. GL_NOTEQUAL,
  681. GL_NEVER,
  682. GL_ALWAYS,
  683. };
  684. static const GLenum s_stencilOp[] =
  685. {
  686. GL_ZERO,
  687. GL_KEEP,
  688. GL_REPLACE,
  689. GL_INCR_WRAP,
  690. GL_INCR,
  691. GL_DECR_WRAP,
  692. GL_DECR,
  693. GL_INVERT,
  694. };
  695. static const GLenum s_stencilFace[] =
  696. {
  697. GL_FRONT_AND_BACK,
  698. GL_FRONT,
  699. GL_BACK,
  700. };
  701. struct RenderTargetColorFormat
  702. {
  703. GLenum m_internalFmt;
  704. GLenum m_type;
  705. uint8_t m_bpp;
  706. };
  707. // Specifies the internal format of the texture.
  708. // Must be one of the following symbolic constants:
  709. // GL_ALPHA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA.
  710. static const RenderTargetColorFormat s_colorFormat[] =
  711. {
  712. { 0, 0, 0 }, // ignored
  713. { GL_RGBA8, GL_UNSIGNED_BYTE, 32 },
  714. { GL_RGB10_A2, GL_UNSIGNED_INT_2_10_10_10_REV, 32 },
  715. { GL_RGBA16, GL_UNSIGNED_SHORT, 64 },
  716. { GL_RGBA16F, GL_HALF_FLOAT, 64 },
  717. { GL_R16F, GL_HALF_FLOAT, 16 },
  718. { GL_R32F, GL_FLOAT, 32 },
  719. };
  720. static const GLenum s_depthFormat[] =
  721. {
  722. 0, // ignored
  723. 0,
  724. };
  725. static const GLenum s_textureAddress[] =
  726. {
  727. GL_REPEAT,
  728. GL_MIRRORED_REPEAT,
  729. GL_CLAMP_TO_EDGE,
  730. };
  731. static const GLenum s_textureFilterMag[] =
  732. {
  733. GL_LINEAR,
  734. GL_NEAREST,
  735. GL_LINEAR,
  736. };
  737. static const GLenum s_textureFilterMin[][3] =
  738. {
  739. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  740. { GL_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_NEAREST },
  741. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  742. };
  743. struct TextureFormatInfo
  744. {
  745. GLenum m_internalFmt;
  746. GLenum m_fmt;
  747. GLenum m_type;
  748. uint8_t m_bpp;
  749. bool m_supported;
  750. };
  751. static TextureFormatInfo s_textureFormat[TextureFormat::Count] =
  752. {
  753. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, 4, false },
  754. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, 8, false },
  755. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, 8, false },
  756. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, 4, false },
  757. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, 8, false },
  758. { GL_ZERO, GL_ZERO, GL_ZERO, 0, true },
  759. { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, true },
  760. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, true },
  761. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, true },
  762. { GL_RGBA16, GL_RGBA, GL_UNSIGNED_BYTE, 64, true },
  763. { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 64, true },
  764. { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, true },
  765. { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, true },
  766. { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, true },
  767. { GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, 32, true },
  768. };
  769. const char* glslTypeName(GLuint _type)
  770. {
  771. #define GLSL_TYPE(_ty) case _ty: return #_ty
  772. switch (_type)
  773. {
  774. GLSL_TYPE(GL_FLOAT);
  775. GLSL_TYPE(GL_FLOAT_VEC2);
  776. GLSL_TYPE(GL_FLOAT_VEC3);
  777. GLSL_TYPE(GL_FLOAT_VEC4);
  778. GLSL_TYPE(GL_FLOAT_MAT2);
  779. GLSL_TYPE(GL_FLOAT_MAT3);
  780. GLSL_TYPE(GL_FLOAT_MAT4);
  781. // GLSL_TYPE(GL_FLOAT_MAT2x3);
  782. // GLSL_TYPE(GL_FLOAT_MAT2x4);
  783. // GLSL_TYPE(GL_FLOAT_MAT3x2);
  784. // GLSL_TYPE(GL_FLOAT_MAT3x4);
  785. // GLSL_TYPE(GL_FLOAT_MAT4x2);
  786. // GLSL_TYPE(GL_FLOAT_MAT4x3);
  787. // GLSL_TYPE(GL_SAMPLER_1D);
  788. GLSL_TYPE(GL_SAMPLER_2D);
  789. GLSL_TYPE(GL_SAMPLER_3D);
  790. GLSL_TYPE(GL_SAMPLER_CUBE);
  791. // GLSL_TYPE(GL_SAMPLER_1D_SHADOW);
  792. // GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  793. }
  794. #undef GLSL_TYPE
  795. return "UNKNOWN GLSL TYPE!";
  796. }
  797. const char* glEnumName(GLenum _enum)
  798. {
  799. #define GLENUM(_ty) case _ty: return #_ty
  800. switch (_enum)
  801. {
  802. GLENUM(GL_TEXTURE);
  803. GLENUM(GL_RENDERBUFFER);
  804. }
  805. #undef GLENUM
  806. return "UNKNOWN GLENUM!";
  807. }
  808. UniformType::Enum convertGlType(GLenum _type)
  809. {
  810. switch (_type)
  811. {
  812. case GL_FLOAT:
  813. return UniformType::Uniform1fv;
  814. case GL_FLOAT_VEC2:
  815. return UniformType::Uniform2fv;
  816. case GL_FLOAT_VEC3:
  817. return UniformType::Uniform3fv;
  818. case GL_FLOAT_VEC4:
  819. return UniformType::Uniform4fv;
  820. case GL_FLOAT_MAT2:
  821. break;
  822. case GL_FLOAT_MAT3:
  823. return UniformType::Uniform3x3fv;
  824. case GL_FLOAT_MAT4:
  825. return UniformType::Uniform4x4fv;
  826. // case GL_FLOAT_MAT2x3:
  827. // case GL_FLOAT_MAT2x4:
  828. // case GL_FLOAT_MAT3x2:
  829. // case GL_FLOAT_MAT3x4:
  830. // case GL_FLOAT_MAT4x2:
  831. // case GL_FLOAT_MAT4x3:
  832. // break;
  833. // case GL_SAMPLER_1D:
  834. case GL_SAMPLER_2D:
  835. case GL_SAMPLER_3D:
  836. case GL_SAMPLER_CUBE:
  837. // case GL_SAMPLER_1D_SHADOW:
  838. // case GL_SAMPLER_2D_SHADOW:
  839. return UniformType::Uniform1iv;
  840. };
  841. return UniformType::End;
  842. }
  843. void Program::create(const Shader& _vsh, const Shader& _fsh)
  844. {
  845. m_id = glCreateProgram();
  846. BX_TRACE("program create: %d: %d, %d", m_id, _vsh.m_id, _fsh.m_id);
  847. bool cached = false;
  848. uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  849. id ^= s_renderCtx.m_hash;
  850. if (s_renderCtx.m_programBinarySupport)
  851. {
  852. uint32_t length = g_callback->cacheReadSize(id);
  853. cached = length > 0;
  854. if (cached)
  855. {
  856. void* data = g_realloc(NULL, length);
  857. if (g_callback->cacheRead(id, data, length) )
  858. {
  859. bx::MemoryReader reader(data, length);
  860. GLenum format;
  861. bx::read(&reader, format);
  862. GL_CHECK(glProgramBinary(m_id, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  863. }
  864. g_free(data);
  865. }
  866. #if BGFX_CONFIG_RENDERER_OPENGL
  867. GL_CHECK(glProgramParameteri(m_id, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  868. #endif // BGFX_CONFIG_RENDERER_OPENGL
  869. }
  870. if (!cached)
  871. {
  872. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  873. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  874. GL_CHECK(glLinkProgram(m_id) );
  875. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  876. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  877. GLint linked = 0;
  878. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  879. if (0 == linked)
  880. {
  881. char log[1024];
  882. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  883. BX_TRACE("%d: %s", linked, log);
  884. GL_CHECK(glDeleteProgram(m_id) );
  885. return;
  886. }
  887. if (s_renderCtx.m_programBinarySupport)
  888. {
  889. GLint programLength;
  890. GLenum format;
  891. GL_CHECK(glGetProgramiv(m_id, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  892. if (0 < programLength)
  893. {
  894. uint32_t length = programLength + 4;
  895. uint8_t* data = (uint8_t*)g_realloc(NULL, length);
  896. GL_CHECK(glGetProgramBinary(m_id, programLength, NULL, &format, &data[4]) );
  897. *(uint32_t*)data = format;
  898. g_callback->cacheWrite(id, data, length);
  899. g_free(data);
  900. }
  901. }
  902. }
  903. init();
  904. }
  905. void Program::destroy()
  906. {
  907. GL_CHECK(glUseProgram(0) );
  908. GL_CHECK(glDeleteProgram(m_id) );
  909. m_vcref.invalidate(s_renderCtx.m_vaoCache);
  910. }
  911. void Program::init()
  912. {
  913. GLint activeAttribs;
  914. GLint activeUniforms;
  915. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs) );
  916. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  917. GLint max0, max1;
  918. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  919. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  920. GLint maxLength = uint32_max(max0, max1);
  921. char* name = (char*)g_realloc(NULL, maxLength + 1);
  922. BX_TRACE("Program %d", m_id);
  923. BX_TRACE("Attributes:");
  924. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  925. {
  926. GLint size;
  927. GLenum type;
  928. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  929. BX_TRACE("\t%s %s is at location %d"
  930. , glslTypeName(type)
  931. , name
  932. , glGetAttribLocation(m_id, name)
  933. );
  934. }
  935. m_numPredefined = 0;
  936. m_constantBuffer = ConstantBuffer::create(1024);
  937. m_numSamplers = 0;
  938. BX_TRACE("Uniforms:");
  939. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  940. {
  941. GLint num;
  942. GLenum gltype;
  943. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  944. GLint loc = glGetUniformLocation(m_id, name);
  945. int offset = 0;
  946. char* array = strchr(name, '[');
  947. if (NULL != array)
  948. {
  949. BX_TRACE("--- %s", name);
  950. *array = '\0';
  951. array++;
  952. char* end = strchr(array, ']');
  953. *end = '\0';
  954. offset = atoi(array);
  955. }
  956. if (GL_SAMPLER_2D == gltype)
  957. {
  958. BX_TRACE("Sampler %d at %d.", m_numSamplers, loc);
  959. m_sampler[m_numSamplers] = loc;
  960. m_numSamplers++;
  961. }
  962. const void* data = NULL;
  963. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  964. if (PredefinedUniform::Count != predefined)
  965. {
  966. m_predefined[m_numPredefined].m_loc = loc;
  967. m_predefined[m_numPredefined].m_type = predefined;
  968. m_predefined[m_numPredefined].m_count = num;
  969. m_numPredefined++;
  970. }
  971. else
  972. {
  973. const UniformInfo* info = s_renderCtx.m_uniformReg.find(name);
  974. if (NULL != info)
  975. {
  976. data = info->m_data;
  977. UniformType::Enum type = convertGlType(gltype);
  978. m_constantBuffer->writeUniformRef(type, 0, data, num);
  979. m_constantBuffer->write(loc);
  980. BX_TRACE("store %s %p", name, data);
  981. }
  982. }
  983. BX_TRACE("\tuniform %s %s%s is at location %d, size %d (%p), offset %d"
  984. , glslTypeName(gltype)
  985. , name
  986. , PredefinedUniform::Count != predefined ? "*" : ""
  987. , loc
  988. , num
  989. , data
  990. , offset
  991. );
  992. BX_UNUSED(offset);
  993. }
  994. m_constantBuffer->finish();
  995. g_free(name);
  996. memset(m_attributes, 0xff, sizeof(m_attributes) );
  997. uint32_t used = 0;
  998. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  999. {
  1000. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  1001. if (-1 != loc)
  1002. {
  1003. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  1004. m_attributes[ii] = loc;
  1005. m_used[used++] = ii;
  1006. }
  1007. }
  1008. m_used[used] = Attrib::Count;
  1009. used = 0;
  1010. for (uint32_t ii = 0; ii < countof(s_instanceDataName); ++ii)
  1011. {
  1012. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  1013. if (GLuint(-1) != loc )
  1014. {
  1015. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  1016. m_instanceData[used++] = loc;
  1017. }
  1018. }
  1019. m_instanceData[used] = 0xffff;
  1020. }
  1021. void Program::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  1022. {
  1023. uint32_t enabled = 0;
  1024. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  1025. {
  1026. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  1027. GLint loc = m_attributes[attr];
  1028. uint8_t num;
  1029. AttribType::Enum type;
  1030. bool normalized;
  1031. bool asInt;
  1032. _vertexDecl.decode(attr, num, type, normalized, asInt);
  1033. if (-1 != loc
  1034. && 0xff != _vertexDecl.m_attributes[attr])
  1035. {
  1036. GL_CHECK(glEnableVertexAttribArray(loc) );
  1037. enabled |= 1<<attr;
  1038. GL_CHECK(s_vertexAttribDivisor(loc, 0) );
  1039. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  1040. GL_CHECK(glVertexAttribPointer(loc, num, s_attribType[type], normalized, _vertexDecl.m_stride, (void*)(uintptr_t)baseVertex) );
  1041. }
  1042. else
  1043. {
  1044. // GL_CHECK(glDisableVertexAttribArray(loc) );
  1045. switch (num)
  1046. {
  1047. case 1:
  1048. GL_CHECK(glVertexAttrib1f(loc, 0.0f) );
  1049. break;
  1050. case 2:
  1051. GL_CHECK(glVertexAttrib2f(loc, 0.0f, 0.0f) );
  1052. break;
  1053. case 3:
  1054. GL_CHECK(glVertexAttrib3f(loc, 0.0f, 0.0f, 0.0f) );
  1055. break;
  1056. case 4:
  1057. GL_CHECK(glVertexAttrib4f(loc, 0.0f, 0.0f, 0.0f, 0.0f) );
  1058. break;
  1059. default:
  1060. BX_CHECK(false, "You should not be here!");
  1061. break;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. void Program::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  1067. {
  1068. uint32_t baseVertex = _baseVertex;
  1069. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  1070. {
  1071. GLint loc = m_instanceData[ii];
  1072. GL_CHECK(glEnableVertexAttribArray(loc) );
  1073. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  1074. GL_CHECK(s_vertexAttribDivisor(loc, 1) );
  1075. baseVertex += 16;
  1076. }
  1077. }
  1078. void IndexBuffer::destroy()
  1079. {
  1080. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  1081. GL_CHECK(glDeleteBuffers(1, &m_id) );
  1082. m_vcref.invalidate(s_renderCtx.m_vaoCache);
  1083. }
  1084. void VertexBuffer::destroy()
  1085. {
  1086. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  1087. GL_CHECK(glDeleteBuffers(1, &m_id) );
  1088. m_vcref.invalidate(s_renderCtx.m_vaoCache);
  1089. }
  1090. static void texImage(GLenum _target, GLint _level, GLint _internalFormat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLenum _format, GLenum _type, const GLvoid* _pixels)
  1091. {
  1092. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1093. if (_target == GL_TEXTURE_3D)
  1094. {
  1095. GL_CHECK(glTexImage3D(_target
  1096. , _level
  1097. , _internalFormat
  1098. , _width
  1099. , _height
  1100. , _depth
  1101. , _border
  1102. , _format
  1103. , _type
  1104. , _pixels
  1105. ) );
  1106. }
  1107. else
  1108. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1109. {
  1110. BX_UNUSED(_depth);
  1111. GL_CHECK(glTexImage2D(_target
  1112. , _level
  1113. , _internalFormat
  1114. , _width
  1115. , _height
  1116. , _border
  1117. , _format
  1118. , _type
  1119. , _pixels
  1120. ) );
  1121. }
  1122. }
  1123. static void compressedTexImage(GLenum _target, GLint _level, GLenum _internalformat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLsizei _imageSize, const GLvoid* _data)
  1124. {
  1125. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1126. if (_target == GL_TEXTURE_3D)
  1127. {
  1128. GL_CHECK(glCompressedTexImage3D(_target
  1129. , _level
  1130. , _internalformat
  1131. , _width
  1132. , _height
  1133. , _depth
  1134. , _border
  1135. , _imageSize
  1136. , _data
  1137. ) );
  1138. }
  1139. else
  1140. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1141. {
  1142. BX_UNUSED(_depth);
  1143. GL_CHECK(glCompressedTexImage2D(_target
  1144. , _level
  1145. , _internalformat
  1146. , _width
  1147. , _height
  1148. , _border
  1149. , _imageSize
  1150. , _data
  1151. ) );
  1152. }
  1153. }
  1154. void Texture::init(GLenum _target, uint8_t _numMips, uint32_t _flags)
  1155. {
  1156. m_target = _target;
  1157. GL_CHECK(glGenTextures(1, &m_id) );
  1158. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1159. GL_CHECK(glBindTexture(_target, m_id) );
  1160. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_WRAP_S, s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  1161. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_WRAP_T, s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  1162. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1163. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_MAX_LEVEL, _numMips-1) );
  1164. if (_target == GL_TEXTURE_3D)
  1165. {
  1166. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_WRAP_R, s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  1167. }
  1168. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1169. uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  1170. uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  1171. uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  1172. GLenum minFilter = s_textureFilterMin[min][1 < _numMips ? mip+1 : 0];
  1173. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_MAG_FILTER, s_textureFilterMag[mag]) );
  1174. GL_CHECK(glTexParameteri(_target, GL_TEXTURE_MIN_FILTER, minFilter) );
  1175. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  1176. && 0.0f < s_renderCtx.m_maxAnisotropy)
  1177. {
  1178. GL_CHECK(glTexParameterf(_target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderCtx.m_maxAnisotropy) );
  1179. }
  1180. }
  1181. void Texture::create(const Memory* _mem, uint32_t _flags)
  1182. {
  1183. Dds dds;
  1184. if (parseDds(dds, _mem) )
  1185. {
  1186. uint8_t numMips = dds.m_numMips;
  1187. if (dds.m_cubeMap)
  1188. {
  1189. init(GL_TEXTURE_CUBE_MAP, numMips, _flags);
  1190. }
  1191. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1192. else if (dds.m_depth > 1)
  1193. {
  1194. init(GL_TEXTURE_3D, numMips, _flags);
  1195. }
  1196. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1197. else
  1198. {
  1199. init(GL_TEXTURE_2D, numMips, _flags);
  1200. }
  1201. const TextureFormatInfo& tfi = s_textureFormat[dds.m_type];
  1202. GLenum internalFmt = tfi.m_internalFmt;
  1203. m_fmt = tfi.m_fmt;
  1204. m_type = tfi.m_type;
  1205. GLenum target = m_target;
  1206. if (dds.m_cubeMap)
  1207. {
  1208. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  1209. }
  1210. if (!tfi.m_supported
  1211. || TextureFormat::Unknown < dds.m_type)
  1212. {
  1213. uint8_t textureFormat = dds.m_type;
  1214. bool decompress = TextureFormat::Unknown > textureFormat;
  1215. uint32_t bpp = tfi.m_bpp;
  1216. if (decompress)
  1217. {
  1218. textureFormat = TextureFormat::BGRA8;
  1219. const TextureFormatInfo& tfi = s_textureFormat[textureFormat];
  1220. internalFmt = tfi.m_internalFmt;
  1221. m_fmt = tfi.m_fmt;
  1222. m_type = tfi.m_type;
  1223. bpp = tfi.m_bpp;
  1224. }
  1225. bool swizzle = GL_RGBA == m_fmt;
  1226. #if BGFX_CONFIG_RENDERER_OPENGL
  1227. if (swizzle
  1228. && s_renderCtx.m_textureSwizzleSupport)
  1229. {
  1230. swizzle = false;
  1231. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  1232. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  1233. }
  1234. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1235. uint8_t* bits = (uint8_t*)g_realloc(NULL, dds.m_width*dds.m_height*bpp/8);
  1236. for (uint8_t side = 0, numSides = dds.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1237. {
  1238. uint32_t width = dds.m_width;
  1239. uint32_t height = dds.m_height;
  1240. uint32_t depth = dds.m_depth;
  1241. for (uint32_t lod = 0, num = numMips; lod < num; ++lod)
  1242. {
  1243. width = uint32_max(1, width);
  1244. height = uint32_max(1, height);
  1245. depth = uint32_max(1, depth);
  1246. Mip mip;
  1247. if (getRawImageData(dds, side, lod, _mem, mip) )
  1248. {
  1249. mip.decode(bits);
  1250. if (swizzle)
  1251. {
  1252. rgbaToBgra(bits, width, height);
  1253. }
  1254. texImage(target+side
  1255. , lod
  1256. , internalFmt
  1257. , width
  1258. , height
  1259. , depth
  1260. , 0
  1261. , m_fmt
  1262. , m_type
  1263. , bits
  1264. );
  1265. }
  1266. width >>= 1;
  1267. height >>= 1;
  1268. depth >>= 1;
  1269. }
  1270. }
  1271. g_free(bits);
  1272. }
  1273. else
  1274. {
  1275. m_compressed = true;
  1276. for (uint8_t side = 0, numSides = dds.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1277. {
  1278. uint32_t width = dds.m_width;
  1279. uint32_t height = dds.m_height;
  1280. uint32_t depth = dds.m_depth;
  1281. for (uint32_t ii = 0, num = numMips; ii < num; ++ii)
  1282. {
  1283. width = uint32_max(1, width);
  1284. height = uint32_max(1, height);
  1285. depth = uint32_max(1, depth);
  1286. Mip mip;
  1287. if (getRawImageData(dds, side, ii, _mem, mip) )
  1288. {
  1289. compressedTexImage(target+side
  1290. , ii
  1291. , internalFmt
  1292. , width
  1293. , height
  1294. , depth
  1295. , 0
  1296. , mip.m_size
  1297. , mip.m_data
  1298. );
  1299. }
  1300. width >>= 1;
  1301. height >>= 1;
  1302. depth >>= 1;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. else
  1308. {
  1309. bx::MemoryReader reader(_mem->data, _mem->size);
  1310. uint32_t magic;
  1311. bx::read(&reader, magic);
  1312. if (BGFX_CHUNK_MAGIC_TEX == magic)
  1313. {
  1314. TextureCreate tc;
  1315. bx::read(&reader, tc);
  1316. uint8_t numMips = tc.m_numMips;
  1317. if (tc.m_cubeMap)
  1318. {
  1319. init(GL_TEXTURE_CUBE_MAP, numMips, _flags);
  1320. }
  1321. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1322. else if (tc.m_depth > 1)
  1323. {
  1324. init(GL_TEXTURE_3D, numMips, _flags);
  1325. }
  1326. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1327. else
  1328. {
  1329. init(GL_TEXTURE_2D, numMips, _flags);
  1330. }
  1331. const TextureFormatInfo& tfi = s_textureFormat[tc.m_format];
  1332. GLenum internalFmt = tfi.m_internalFmt;
  1333. m_fmt = tfi.m_fmt;
  1334. m_type = tfi.m_type;
  1335. m_compressed = tc.m_format < TextureFormat::Unknown;
  1336. GLenum target = m_target;
  1337. if (tc.m_cubeMap)
  1338. {
  1339. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  1340. }
  1341. uint32_t bpp = tfi.m_bpp;
  1342. uint8_t* data = NULL != tc.m_mem ? tc.m_mem->data : NULL;
  1343. uint32_t min = m_compressed ? 4 : 1;
  1344. bool swizzle = GL_RGBA == m_fmt;
  1345. #if BGFX_CONFIG_RENDERER_OPENGL
  1346. if (swizzle
  1347. && s_renderCtx.m_textureSwizzleSupport)
  1348. {
  1349. swizzle = false;
  1350. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  1351. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  1352. }
  1353. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1354. for (uint8_t side = 0, numSides = tc.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1355. {
  1356. uint32_t width = tc.m_width;
  1357. uint32_t height = tc.m_height;
  1358. uint32_t depth = tc.m_depth;
  1359. for (uint32_t lod = 0, num = numMips; lod < num; ++lod)
  1360. {
  1361. width = uint32_max(width, min);
  1362. height = uint32_max(height, min);
  1363. depth = uint32_max(1, depth);
  1364. uint32_t size = width*height*bpp/8;
  1365. if (m_compressed)
  1366. {
  1367. compressedTexImage(target+side
  1368. , lod
  1369. , internalFmt
  1370. , width
  1371. , height
  1372. , depth
  1373. , 0
  1374. , size
  1375. , data
  1376. );
  1377. }
  1378. else
  1379. {
  1380. if (NULL != data
  1381. && swizzle)
  1382. {
  1383. rgbaToBgra(data, width, height);
  1384. }
  1385. texImage(target+side
  1386. , lod
  1387. , internalFmt
  1388. , width
  1389. , height
  1390. , depth
  1391. , 0
  1392. , m_fmt
  1393. , m_type
  1394. , data
  1395. );
  1396. }
  1397. if (NULL != data)
  1398. {
  1399. data += size;
  1400. }
  1401. width >>= 1;
  1402. height >>= 1;
  1403. depth >>= 1;
  1404. }
  1405. }
  1406. if (NULL != tc.m_mem)
  1407. {
  1408. release(tc.m_mem);
  1409. }
  1410. }
  1411. else
  1412. {
  1413. //
  1414. }
  1415. }
  1416. GL_CHECK(glBindTexture(m_target, 0) );
  1417. }
  1418. void Texture::createColor(uint32_t _colorFormat, uint32_t _width, uint32_t _height, GLenum _min, GLenum _mag)
  1419. {
  1420. const RenderTargetColorFormat& rtcf = s_colorFormat[_colorFormat];
  1421. GLenum internalFormat = rtcf.m_internalFmt;
  1422. GLenum type = rtcf.m_type;
  1423. m_target = GL_TEXTURE_2D;
  1424. GL_CHECK(glGenTextures(1, &m_id) );
  1425. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1426. GL_CHECK(glBindTexture(m_target, m_id) );
  1427. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1428. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAX_LEVEL, 0) );
  1429. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1430. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, _min) );
  1431. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, _mag) );
  1432. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  1433. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  1434. GL_CHECK(glTexImage2D(m_target
  1435. , 0
  1436. , internalFormat
  1437. , _width
  1438. , _height
  1439. , 0
  1440. , GL_RGBA
  1441. , type
  1442. , NULL
  1443. ) );
  1444. GL_CHECK(glBindTexture(m_target, 0) );
  1445. }
  1446. void Texture::createDepth(uint32_t _width, uint32_t _height)
  1447. {
  1448. m_target = GL_TEXTURE_2D;
  1449. GL_CHECK(glGenTextures(1, &m_id) );
  1450. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1451. GL_CHECK(glBindTexture(m_target, m_id) );
  1452. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1453. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAX_LEVEL, 0) );
  1454. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1455. // GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  1456. // GL_CHECK(glTexParameteri(m_target, GL_DEPTH_TEXTURE_MODE, GL_NONE) );
  1457. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  1458. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  1459. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  1460. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  1461. // OpenGL ES 2.0 doesn't support GL_DEPTH_COMPONENT... this will fail.
  1462. GL_CHECK(glTexImage2D(m_target
  1463. , 0
  1464. , GL_DEPTH_COMPONENT
  1465. , _width
  1466. , _height
  1467. , 0
  1468. , GL_DEPTH_COMPONENT
  1469. , GL_FLOAT
  1470. , NULL
  1471. ) );
  1472. GL_CHECK(glBindTexture(m_target, 0) );
  1473. }
  1474. void Texture::destroy()
  1475. {
  1476. if (0 != m_id)
  1477. {
  1478. GL_CHECK(glBindTexture(m_target, 0) );
  1479. GL_CHECK(glDeleteTextures(1, &m_id) );
  1480. m_id = 0;
  1481. }
  1482. }
  1483. void Texture::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, const Memory* _mem)
  1484. {
  1485. BX_UNUSED(_z);
  1486. BX_UNUSED(_depth);
  1487. GL_CHECK(glBindTexture(m_target, m_id) );
  1488. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  1489. switch (m_target)
  1490. {
  1491. case GL_TEXTURE_2D:
  1492. if (m_compressed)
  1493. {
  1494. GL_CHECK(glCompressedTexSubImage2D(m_target
  1495. , _mip
  1496. , _rect.m_x
  1497. , _rect.m_y
  1498. , _rect.m_width
  1499. , _rect.m_height
  1500. , m_fmt
  1501. , _mem->size
  1502. , _mem->data
  1503. ) );
  1504. }
  1505. else
  1506. {
  1507. GL_CHECK(glTexSubImage2D(m_target
  1508. , _mip
  1509. , _rect.m_x
  1510. , _rect.m_y
  1511. , _rect.m_width
  1512. , _rect.m_height
  1513. , m_fmt
  1514. , m_type
  1515. , _mem->data
  1516. ) );
  1517. }
  1518. break;
  1519. case GL_TEXTURE_CUBE_MAP:
  1520. if (m_compressed)
  1521. {
  1522. GL_CHECK(glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+_side
  1523. , _mip
  1524. , _rect.m_x
  1525. , _rect.m_y
  1526. , _rect.m_width
  1527. , _rect.m_height
  1528. , m_fmt
  1529. , _mem->size
  1530. , _mem->data
  1531. ) );
  1532. }
  1533. else
  1534. {
  1535. GL_CHECK(glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+_side
  1536. , _mip
  1537. , _rect.m_x
  1538. , _rect.m_y
  1539. , _rect.m_width
  1540. , _rect.m_height
  1541. , m_fmt
  1542. , m_type
  1543. , _mem->data
  1544. ) );
  1545. }
  1546. break;
  1547. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1548. case GL_TEXTURE_3D:
  1549. if (m_compressed)
  1550. {
  1551. GL_CHECK(glCompressedTexSubImage3D(m_target
  1552. , _mip
  1553. , _rect.m_x
  1554. , _rect.m_y
  1555. , _z
  1556. , _rect.m_width
  1557. , _rect.m_height
  1558. , _depth
  1559. , m_fmt
  1560. , _mem->size
  1561. , _mem->data
  1562. ) );
  1563. }
  1564. else
  1565. {
  1566. GL_CHECK(glTexSubImage3D(m_target
  1567. , _mip
  1568. , _rect.m_x
  1569. , _rect.m_y
  1570. , _z
  1571. , _rect.m_width
  1572. , _rect.m_height
  1573. , _depth
  1574. , m_fmt
  1575. , m_type
  1576. , _mem->data
  1577. ) );
  1578. }
  1579. break;
  1580. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1581. }
  1582. }
  1583. void RenderTarget::create(uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1584. {
  1585. BX_TRACE("Create render target %dx%d 0x%02x", _width, _height, _flags);
  1586. m_width = _width;
  1587. m_height = _height;
  1588. uint32_t msaa = (_flags&BGFX_RENDER_TARGET_MSAA_MASK)>>BGFX_RENDER_TARGET_MSAA_SHIFT;
  1589. m_msaa = uint32_min(s_renderCtx.m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  1590. uint32_t colorFormat = (_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1591. uint32_t depthFormat = (_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1592. GLenum minFilter = s_textureFilterMin[(_textureFlags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT][0];
  1593. GLenum magFilter = s_textureFilterMag[(_textureFlags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  1594. if (0 < colorFormat)
  1595. {
  1596. m_color.createColor(colorFormat, _width, _height, minFilter, magFilter);
  1597. }
  1598. #if 0 // GLES can't create texture with depth texture format...
  1599. if (0 < depthFormat)
  1600. {
  1601. m_depth.createDepth(_width, _height);
  1602. }
  1603. #endif //
  1604. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1605. if (0 < colorFormat
  1606. && 0 != m_msaa)
  1607. {
  1608. GL_CHECK(glGenFramebuffers(2, m_fbo) );
  1609. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  1610. GL_CHECK(glGenRenderbuffers(1, &m_colorRbo) );
  1611. BX_CHECK(0 != m_colorRbo, "Failed to generate color renderbuffer id.");
  1612. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_colorRbo) );
  1613. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msaa, s_colorFormat[colorFormat].m_internalFmt, _width, _height) );
  1614. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  1615. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  1616. , GL_COLOR_ATTACHMENT0
  1617. , GL_RENDERBUFFER
  1618. , m_colorRbo
  1619. ) );
  1620. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  1621. }
  1622. else
  1623. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1624. {
  1625. GL_CHECK(glGenFramebuffers(1, m_fbo) );
  1626. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  1627. }
  1628. if (0 < colorFormat)
  1629. {
  1630. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1631. , GL_COLOR_ATTACHMENT0
  1632. , m_color.m_target
  1633. , m_color.m_id
  1634. , 0
  1635. ) );
  1636. }
  1637. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1638. , "glCheckFramebufferStatus failed 0x%08x"
  1639. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1640. );
  1641. if (0 < depthFormat)
  1642. {
  1643. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  1644. if (0 < colorFormat)
  1645. {
  1646. #if BGFX_CONFIG_RENDERER_OPENGL
  1647. GLenum depthComponent = GL_DEPTH_COMPONENT32;
  1648. #else
  1649. GLenum depthComponent = GL_DEPTH_COMPONENT16;
  1650. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1651. GL_CHECK(glGenRenderbuffers(1, &m_depthRbo) );
  1652. BX_CHECK(0 != m_depthRbo, "Failed to generate renderbuffer id.");
  1653. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_depthRbo) );
  1654. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1655. if (0 != m_msaa)
  1656. {
  1657. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msaa, depthComponent, _width, _height) );
  1658. }
  1659. else
  1660. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1661. {
  1662. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, depthComponent, _width, _height) );
  1663. }
  1664. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  1665. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  1666. , GL_DEPTH_ATTACHMENT
  1667. , GL_RENDERBUFFER
  1668. , m_depthRbo
  1669. ) );
  1670. }
  1671. else
  1672. {
  1673. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1674. , GL_DEPTH_ATTACHMENT
  1675. , m_depth.m_target
  1676. , m_depth.m_id
  1677. , 0
  1678. ) );
  1679. }
  1680. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1681. , "glCheckFramebufferStatus failed 0x%08x"
  1682. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1683. );
  1684. }
  1685. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_msaaBackBufferFbo) );
  1686. }
  1687. void RenderTarget::destroy()
  1688. {
  1689. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  1690. memset(m_fbo, 0, sizeof(m_fbo) );
  1691. if (0 != m_colorRbo)
  1692. {
  1693. GL_CHECK(glDeleteRenderbuffers(1, &m_colorRbo) );
  1694. m_colorRbo = 0;
  1695. }
  1696. if (0 != m_depthRbo)
  1697. {
  1698. GL_CHECK(glDeleteRenderbuffers(1, &m_depthRbo) );
  1699. m_depthRbo = 0;
  1700. }
  1701. m_color.destroy();
  1702. m_depth.destroy();
  1703. }
  1704. void RenderTarget::resolve()
  1705. {
  1706. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1707. BX_CHECK(0 != m_fbo[1], "Can resolve without two framebuffers.");
  1708. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  1709. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  1710. GL_CHECK(glBlitFramebuffer(0
  1711. , 0
  1712. , m_width
  1713. , m_height
  1714. , 0
  1715. , 0
  1716. , m_width
  1717. , m_height
  1718. , GL_COLOR_BUFFER_BIT
  1719. , GL_LINEAR
  1720. ) );
  1721. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_msaaBackBufferFbo) );
  1722. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  1723. }
  1724. void ConstantBuffer::commit()
  1725. {
  1726. reset();
  1727. do
  1728. {
  1729. uint32_t opcode = read();
  1730. if (UniformType::End == opcode)
  1731. {
  1732. break;
  1733. }
  1734. UniformType::Enum type;
  1735. uint16_t ignore;
  1736. uint16_t num;
  1737. uint16_t copy;
  1738. decodeOpcode(opcode, type, ignore, num, copy);
  1739. const char* data;
  1740. if (copy)
  1741. {
  1742. data = read(g_uniformTypeSize[type]*num);
  1743. }
  1744. else
  1745. {
  1746. memcpy(&data, read(sizeof(void*) ), sizeof(void*) );
  1747. }
  1748. uint32_t loc = read();
  1749. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  1750. case UniformType::_uniform: \
  1751. { \
  1752. _type* value = (_type*)data; \
  1753. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  1754. } \
  1755. break;
  1756. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  1757. case UniformType::_uniform: \
  1758. { \
  1759. _type* value = (_type*)data; \
  1760. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  1761. } \
  1762. break;
  1763. switch (type)
  1764. {
  1765. // case ConstantType::Uniform1iv:
  1766. // {
  1767. // int* value = (int*)data;
  1768. // BX_TRACE("Uniform1iv sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  1769. // GL_CHECK(glUniform1iv(loc, num, value) );
  1770. // }
  1771. // break;
  1772. CASE_IMPLEMENT_UNIFORM(Uniform1i, 1iv, I, int);
  1773. CASE_IMPLEMENT_UNIFORM(Uniform1f, 1fv, F, float);
  1774. CASE_IMPLEMENT_UNIFORM(Uniform1iv, 1iv, I, int);
  1775. CASE_IMPLEMENT_UNIFORM(Uniform1fv, 1fv, F, float);
  1776. CASE_IMPLEMENT_UNIFORM(Uniform2fv, 2fv, F, float);
  1777. CASE_IMPLEMENT_UNIFORM(Uniform3fv, 3fv, F, float);
  1778. CASE_IMPLEMENT_UNIFORM(Uniform4fv, 4fv, F, float);
  1779. CASE_IMPLEMENT_UNIFORM_T(Uniform3x3fv, Matrix3fv, F, float);
  1780. CASE_IMPLEMENT_UNIFORM_T(Uniform4x4fv, Matrix4fv, F, float);
  1781. case UniformType::End:
  1782. break;
  1783. default:
  1784. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", m_pos, opcode, type, loc, num, copy);
  1785. break;
  1786. }
  1787. #undef CASE_IMPLEMENT_UNIFORM
  1788. #undef CASE_IMPLEMENT_UNIFORM_T
  1789. } while (true);
  1790. }
  1791. void TextVideoMemBlitter::setup()
  1792. {
  1793. if (0 != s_renderCtx.m_vao)
  1794. {
  1795. GL_CHECK(glBindVertexArray(s_renderCtx.m_vao) );
  1796. }
  1797. uint32_t width = s_renderCtx.m_resolution.m_width;
  1798. uint32_t height = s_renderCtx.m_resolution.m_height;
  1799. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_backBufferFbo) );
  1800. GL_CHECK(glViewport(0, 0, width, height) );
  1801. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1802. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1803. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1804. GL_CHECK(glDisable(GL_CULL_FACE) );
  1805. GL_CHECK(glDisable(GL_BLEND) );
  1806. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1807. Program& program = s_renderCtx.m_program[m_program.idx];
  1808. GL_CHECK(glUseProgram(program.m_id) );
  1809. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  1810. float proj[16];
  1811. mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1812. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  1813. , 1
  1814. , GL_FALSE
  1815. , proj
  1816. ) );
  1817. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1818. GL_CHECK(glBindTexture(GL_TEXTURE_2D, s_renderCtx.m_textures[m_texture.idx].m_id) );
  1819. }
  1820. void TextVideoMemBlitter::render(uint32_t _numIndices)
  1821. {
  1822. uint32_t numVertices = _numIndices*4/6;
  1823. s_renderCtx.m_indexBuffers[m_ib->handle.idx].update(0, _numIndices*2, m_ib->data);
  1824. s_renderCtx.m_vertexBuffers[m_vb->handle.idx].update(0, numVertices*m_decl.m_stride, m_vb->data);
  1825. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[m_vb->handle.idx];
  1826. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1827. IndexBuffer& ib = s_renderCtx.m_indexBuffers[m_ib->handle.idx];
  1828. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1829. Program& program = s_renderCtx.m_program[m_program.idx];
  1830. program.bindAttributes(m_decl, 0);
  1831. GL_CHECK(glDrawElements(GL_TRIANGLES
  1832. , _numIndices
  1833. , GL_UNSIGNED_SHORT
  1834. , (void*)0
  1835. ) );
  1836. }
  1837. void ClearQuad::clear(const Rect& _rect, const Clear& _clear, uint32_t _height)
  1838. {
  1839. #if BGFX_CONFIG_CLEAR_QUAD
  1840. if (s_renderCtx.m_useClearQuad)
  1841. {
  1842. GL_CHECK(glDisable(GL_CULL_FACE) );
  1843. GL_CHECK(glDisable(GL_BLEND) );
  1844. GLboolean colorMask = !!(BGFX_CLEAR_COLOR_BIT & _clear.m_flags);
  1845. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  1846. if (BGFX_CLEAR_DEPTH_BIT & _clear.m_flags)
  1847. {
  1848. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  1849. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1850. GL_CHECK(glDepthMask(GL_TRUE) );
  1851. }
  1852. else
  1853. {
  1854. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1855. }
  1856. if (BGFX_CLEAR_STENCIL_BIT & _clear.m_flags)
  1857. {
  1858. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  1859. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  1860. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  1861. }
  1862. else
  1863. {
  1864. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1865. }
  1866. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[m_vb->handle.idx];
  1867. VertexDecl& vertexDecl = s_renderCtx.m_vertexDecls[m_vb->decl.idx];
  1868. {
  1869. struct Vertex
  1870. {
  1871. float m_x;
  1872. float m_y;
  1873. float m_z;
  1874. uint32_t m_abgr;
  1875. } * vertex = (Vertex*)m_vb->data;
  1876. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  1877. const uint32_t abgr = bx::endianSwap(_clear.m_rgba);
  1878. const float depth = _clear.m_depth;
  1879. vertex->m_x = -1.0f;
  1880. vertex->m_y = -1.0f;
  1881. vertex->m_z = depth;
  1882. vertex->m_abgr = abgr;
  1883. vertex++;
  1884. vertex->m_x = 1.0f;
  1885. vertex->m_y = -1.0f;
  1886. vertex->m_z = depth;
  1887. vertex->m_abgr = abgr;
  1888. vertex++;
  1889. vertex->m_x = 1.0f;
  1890. vertex->m_y = 1.0f;
  1891. vertex->m_z = depth;
  1892. vertex->m_abgr = abgr;
  1893. vertex++;
  1894. vertex->m_x = -1.0f;
  1895. vertex->m_y = 1.0f;
  1896. vertex->m_z = depth;
  1897. vertex->m_abgr = abgr;
  1898. }
  1899. s_renderCtx.m_vertexBuffers[m_vb->handle.idx].update(0, 4*m_decl.m_stride, m_vb->data);
  1900. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1901. IndexBuffer& ib = s_renderCtx.m_indexBuffers[m_ib.idx];
  1902. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1903. Program& program = s_renderCtx.m_program[m_program.idx];
  1904. GL_CHECK(glUseProgram(program.m_id) );
  1905. program.bindAttributes(vertexDecl, 0);
  1906. GL_CHECK(glDrawElements(GL_TRIANGLES
  1907. , 6
  1908. , GL_UNSIGNED_SHORT
  1909. , (void*)0
  1910. ) );
  1911. }
  1912. else
  1913. #endif // BGFX_CONFIG_CLEAR_QUAD
  1914. {
  1915. GLuint flags = 0;
  1916. if (BGFX_CLEAR_COLOR_BIT & _clear.m_flags)
  1917. {
  1918. flags |= GL_COLOR_BUFFER_BIT;
  1919. uint32_t rgba = _clear.m_rgba;
  1920. float rr = (rgba>>24)/255.0f;
  1921. float gg = ( (rgba>>16)&0xff)/255.0f;
  1922. float bb = ( (rgba>>8)&0xff)/255.0f;
  1923. float aa = (rgba&0xff)/255.0f;
  1924. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  1925. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1926. }
  1927. if (BGFX_CLEAR_DEPTH_BIT & _clear.m_flags)
  1928. {
  1929. flags |= GL_DEPTH_BUFFER_BIT;
  1930. GL_CHECK(glClearDepth(_clear.m_depth) );
  1931. GL_CHECK(glDepthMask(GL_TRUE) );
  1932. }
  1933. if (BGFX_CLEAR_STENCIL_BIT & _clear.m_flags)
  1934. {
  1935. flags |= GL_STENCIL_BUFFER_BIT;
  1936. GL_CHECK(glClearStencil(_clear.m_stencil) );
  1937. }
  1938. if (0 != flags)
  1939. {
  1940. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  1941. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  1942. GL_CHECK(glClear(flags) );
  1943. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1944. }
  1945. }
  1946. }
  1947. void Context::flip()
  1948. {
  1949. s_renderCtx.flip();
  1950. }
  1951. GLint glGet(GLenum _pname)
  1952. {
  1953. GLint result;
  1954. GL_CHECK(glGetIntegerv(_pname, &result) );
  1955. return result;
  1956. }
  1957. void Context::rendererInit()
  1958. {
  1959. s_renderCtx.init();
  1960. #if BGFX_CONFIG_DEBUG
  1961. GLint numCmpFormats;
  1962. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1963. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1964. if (0 < numCmpFormats)
  1965. {
  1966. GLint* formats = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1967. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats) );
  1968. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1969. {
  1970. BX_TRACE(" %3d: %8x", ii, formats[ii]);
  1971. }
  1972. }
  1973. # define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1974. BX_TRACE("Defaults:");
  1975. # if BX_PLATFORM_OSX
  1976. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1977. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1978. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1979. # else
  1980. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1981. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1982. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1983. # endif
  1984. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1985. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1986. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1987. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1988. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1989. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1990. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1991. BX_TRACE(" Vendor: %s", s_renderCtx.m_vendor);
  1992. BX_TRACE(" Renderer: %s", s_renderCtx.m_renderer);
  1993. BX_TRACE(" Version: %s", s_renderCtx.m_version);
  1994. BX_TRACE("GLSL version: %s", s_renderCtx.m_glslVersion);
  1995. #endif // BGFX_CONFIG_DEBUG
  1996. // Initial binary shader hash depends on driver version.
  1997. s_renderCtx.m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1998. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1999. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  2000. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  2001. ;
  2002. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  2003. glGetError(); // ignore error if glGetString returns NULL.
  2004. if (NULL != extensions)
  2005. {
  2006. char name[1024];
  2007. const char* pos = extensions;
  2008. const char* end = extensions + strlen(extensions);
  2009. uint32_t index = 0;
  2010. while (pos < end)
  2011. {
  2012. uint32_t len;
  2013. const char* space = strchr(pos, ' ');
  2014. if (NULL != space)
  2015. {
  2016. len = uint32_min(sizeof(name), (uint32_t)(space - pos) );
  2017. }
  2018. else
  2019. {
  2020. len = uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  2021. }
  2022. strncpy(name, pos, len);
  2023. name[len] = '\0';
  2024. bool supported = false;
  2025. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  2026. {
  2027. Extension& extension = s_extension[ii];
  2028. if (!extension.m_supported
  2029. && extension.m_initialize)
  2030. {
  2031. if (0 == strcmp(name, extension.m_name) )
  2032. {
  2033. extension.m_supported = true;
  2034. supported = true;
  2035. break;
  2036. }
  2037. }
  2038. }
  2039. BX_TRACE("GL_EXTENSION %3d%s: %s", index, supported ? " (supported)" : "", name);
  2040. BX_UNUSED(supported);
  2041. pos += len+1;
  2042. ++index;
  2043. }
  2044. BX_TRACE("Supported extensions:");
  2045. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  2046. {
  2047. if (s_extension[ii].m_supported)
  2048. {
  2049. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  2050. }
  2051. }
  2052. }
  2053. bool bc123Supported = s_extension[Extension::EXT_texture_compression_s3tc].m_supported;
  2054. s_textureFormat[TextureFormat::BC1].m_supported = bc123Supported || s_extension[Extension::EXT_texture_compression_dxt1].m_supported;
  2055. s_textureFormat[TextureFormat::BC2].m_supported = bc123Supported || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported;
  2056. s_textureFormat[TextureFormat::BC3].m_supported = bc123Supported || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported;
  2057. bool bc45Supported = s_extension[Extension::EXT_texture_compression_latc].m_supported
  2058. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported
  2059. ;
  2060. s_textureFormat[TextureFormat::BC4].m_supported = bc45Supported;
  2061. s_textureFormat[TextureFormat::BC5].m_supported = bc45Supported;
  2062. s_renderCtx.m_vaoSupport = !!BGFX_CONFIG_RENDERER_OPENGLES3
  2063. || s_extension[Extension::ARB_vertex_array_object].m_supported
  2064. || s_extension[Extension::OES_vertex_array_object].m_supported
  2065. ;
  2066. s_renderCtx.m_programBinarySupport = !!BGFX_CONFIG_RENDERER_OPENGLES3
  2067. || s_extension[Extension::ARB_get_program_binary].m_supported
  2068. || s_extension[Extension::OES_get_program_binary].m_supported
  2069. ;
  2070. s_renderCtx.m_textureSwizzleSupport = false
  2071. || s_extension[Extension::ARB_texture_swizzle].m_supported
  2072. || s_extension[Extension::EXT_texture_swizzle].m_supported
  2073. ;
  2074. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  2075. {
  2076. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &s_renderCtx.m_maxAnisotropy) );
  2077. }
  2078. #if BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  2079. if (s_extension[Extension::ARB_texture_multisample].m_supported)
  2080. {
  2081. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &s_renderCtx.m_maxMsaa) );
  2082. }
  2083. #endif // BGFX_CONFIG_RENDERER_OPENGL|BGFX_CONFIG_RENDERER_OPENGLES3
  2084. if (s_extension[Extension::EXT_texture_format_BGRA8888].m_supported
  2085. || s_extension[Extension::EXT_bgra].m_supported)
  2086. {
  2087. s_textureFormat[TextureFormat::BGRX8].m_fmt = GL_BGRA_EXT;
  2088. s_textureFormat[TextureFormat::BGRA8].m_fmt = GL_BGRA_EXT;
  2089. // Mixing GLES and GL extensions here. OpenGL EXT_bgra wants
  2090. // format to be BGRA but internal format to stay RGBA, but
  2091. // EXT_texture_format_BGRA8888 wants both format and internal
  2092. // format to be BGRA.
  2093. //
  2094. // Reference:
  2095. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  2096. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  2097. if (!s_extension[Extension::EXT_bgra].m_supported)
  2098. {
  2099. s_textureFormat[TextureFormat::BGRX8].m_internalFmt = GL_BGRA_EXT;
  2100. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA_EXT;
  2101. }
  2102. }
  2103. if (s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  2104. {
  2105. s_textureFormat[TextureFormat::BC4].m_fmt = GL_COMPRESSED_RED_RGTC1_EXT;
  2106. s_textureFormat[TextureFormat::BC4].m_internalFmt = GL_COMPRESSED_RED_RGTC1_EXT;
  2107. s_textureFormat[TextureFormat::BC5].m_fmt = GL_COMPRESSED_RED_GREEN_RGTC2_EXT;
  2108. s_textureFormat[TextureFormat::BC5].m_internalFmt = GL_COMPRESSED_RED_GREEN_RGTC2_EXT;
  2109. }
  2110. #if !BGFX_CONFIG_RENDERER_OPENGLES3
  2111. s_vertexAttribDivisor = stubVertexAttribDivisor;
  2112. s_drawArraysInstanced = stubDrawArraysInstanced;
  2113. s_drawElementsInstanced = stubDrawElementsInstanced;
  2114. # if !BX_PLATFORM_IOS
  2115. if (s_extension[Extension::ARB_instanced_arrays].m_supported
  2116. || s_extension[Extension::ANGLE_instanced_arrays].m_supported)
  2117. {
  2118. if (NULL != glVertexAttribDivisor
  2119. && NULL != glDrawArraysInstanced
  2120. && NULL != glDrawElementsInstanced)
  2121. {
  2122. s_vertexAttribDivisor = glVertexAttribDivisor;
  2123. s_drawArraysInstanced = glDrawArraysInstanced;
  2124. s_drawElementsInstanced = glDrawElementsInstanced;
  2125. }
  2126. }
  2127. # endif // !BX_PLATFORM_IOS
  2128. #endif // !BGFX_CONFIG_RENDERER_OPENGLES3
  2129. if (s_renderCtx.m_vaoSupport)
  2130. {
  2131. GL_CHECK(glGenVertexArrays(1, &s_renderCtx.m_vao) );
  2132. }
  2133. #if BGFX_CONFIG_RENDERER_OPENGL
  2134. # if BGFX_CONFIG_RENDERER_OPENGL >= 31
  2135. s_textureFormat[TextureFormat::L8].m_internalFmt = GL_R8;
  2136. s_textureFormat[TextureFormat::L8].m_fmt = GL_RED;
  2137. # endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  2138. if (s_extension[Extension::ARB_debug_output].m_supported)
  2139. {
  2140. GL_CHECK(glDebugMessageCallbackARB(debugProcCb, NULL) );
  2141. GL_CHECK(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM_ARB, 0, NULL, GL_TRUE) );
  2142. }
  2143. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  2144. {
  2145. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  2146. }
  2147. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2148. }
  2149. void Context::rendererShutdown()
  2150. {
  2151. if (s_renderCtx.m_vaoSupport)
  2152. {
  2153. GL_CHECK(glBindVertexArray(0) );
  2154. GL_CHECK(glDeleteVertexArrays(1, &s_renderCtx.m_vao) );
  2155. s_renderCtx.m_vao = 0;
  2156. }
  2157. s_renderCtx.shutdown();
  2158. }
  2159. void Context::rendererCreateIndexBuffer(IndexBufferHandle _handle, Memory* _mem)
  2160. {
  2161. s_renderCtx.m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  2162. }
  2163. void Context::rendererDestroyIndexBuffer(IndexBufferHandle _handle)
  2164. {
  2165. s_renderCtx.m_indexBuffers[_handle.idx].destroy();
  2166. }
  2167. void Context::rendererCreateVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl)
  2168. {
  2169. VertexDecl& decl = s_renderCtx.m_vertexDecls[_handle.idx];
  2170. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  2171. dump(decl);
  2172. }
  2173. void Context::rendererDestroyVertexDecl(VertexDeclHandle /*_handle*/)
  2174. {
  2175. }
  2176. void Context::rendererCreateVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle)
  2177. {
  2178. s_renderCtx.m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  2179. }
  2180. void Context::rendererDestroyVertexBuffer(VertexBufferHandle _handle)
  2181. {
  2182. s_renderCtx.m_vertexBuffers[_handle.idx].destroy();
  2183. }
  2184. void Context::rendererCreateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size)
  2185. {
  2186. s_renderCtx.m_indexBuffers[_handle.idx].create(_size, NULL);
  2187. }
  2188. void Context::rendererUpdateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  2189. {
  2190. s_renderCtx.m_indexBuffers[_handle.idx].update(_offset, uint32_min(_size, _mem->size), _mem->data);
  2191. }
  2192. void Context::rendererDestroyDynamicIndexBuffer(IndexBufferHandle _handle)
  2193. {
  2194. s_renderCtx.m_indexBuffers[_handle.idx].destroy();
  2195. }
  2196. void Context::rendererCreateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size)
  2197. {
  2198. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  2199. s_renderCtx.m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  2200. }
  2201. void Context::rendererUpdateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  2202. {
  2203. s_renderCtx.m_vertexBuffers[_handle.idx].update(_offset, uint32_min(_size, _mem->size), _mem->data);
  2204. }
  2205. void Context::rendererDestroyDynamicVertexBuffer(VertexBufferHandle _handle)
  2206. {
  2207. s_renderCtx.m_vertexBuffers[_handle.idx].destroy();
  2208. }
  2209. void Context::rendererCreateVertexShader(VertexShaderHandle _handle, Memory* _mem)
  2210. {
  2211. s_renderCtx.m_vertexShaders[_handle.idx].create(GL_VERTEX_SHADER, _mem);
  2212. }
  2213. void Context::rendererDestroyVertexShader(VertexShaderHandle _handle)
  2214. {
  2215. s_renderCtx.m_vertexShaders[_handle.idx].destroy();
  2216. }
  2217. void Context::rendererCreateFragmentShader(FragmentShaderHandle _handle, Memory* _mem)
  2218. {
  2219. s_renderCtx.m_fragmentShaders[_handle.idx].create(GL_FRAGMENT_SHADER, _mem);
  2220. }
  2221. void Context::rendererDestroyFragmentShader(FragmentShaderHandle _handle)
  2222. {
  2223. s_renderCtx.m_fragmentShaders[_handle.idx].destroy();
  2224. }
  2225. void Context::rendererCreateProgram(ProgramHandle _handle, VertexShaderHandle _vsh, FragmentShaderHandle _fsh)
  2226. {
  2227. s_renderCtx.m_program[_handle.idx].create(s_renderCtx.m_vertexShaders[_vsh.idx], s_renderCtx.m_fragmentShaders[_fsh.idx]);
  2228. }
  2229. void Context::rendererDestroyProgram(FragmentShaderHandle _handle)
  2230. {
  2231. s_renderCtx.m_program[_handle.idx].destroy();
  2232. }
  2233. void Context::rendererCreateTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags)
  2234. {
  2235. s_renderCtx.m_textures[_handle.idx].create(_mem, _flags);
  2236. }
  2237. void Context::rendererUpdateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/)
  2238. {
  2239. }
  2240. void Context::rendererUpdateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, const Memory* _mem)
  2241. {
  2242. s_renderCtx.m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _mem);
  2243. }
  2244. void Context::rendererUpdateTextureEnd()
  2245. {
  2246. }
  2247. void Context::rendererDestroyTexture(TextureHandle _handle)
  2248. {
  2249. s_renderCtx.m_textures[_handle.idx].destroy();
  2250. }
  2251. void Context::rendererCreateRenderTarget(RenderTargetHandle _handle, uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  2252. {
  2253. s_renderCtx.m_renderTargets[_handle.idx].create(_width, _height, _flags, _textureFlags);
  2254. }
  2255. void Context::rendererDestroyRenderTarget(RenderTargetHandle _handle)
  2256. {
  2257. s_renderCtx.m_renderTargets[_handle.idx].destroy();
  2258. }
  2259. void Context::rendererCreateUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name)
  2260. {
  2261. uint32_t size = g_uniformTypeSize[_type]*_num;
  2262. void* data = g_realloc(NULL, size);
  2263. memset(data, 0, size);
  2264. s_renderCtx.m_uniforms[_handle.idx] = data;
  2265. s_renderCtx.m_uniformReg.add(_name, s_renderCtx.m_uniforms[_handle.idx]);
  2266. }
  2267. void Context::rendererDestroyUniform(UniformHandle _handle)
  2268. {
  2269. g_free(s_renderCtx.m_uniforms[_handle.idx]);
  2270. }
  2271. void Context::rendererSaveScreenShot(const char* _filePath)
  2272. {
  2273. s_renderCtx.saveScreenShot(_filePath);
  2274. }
  2275. void Context::rendererUpdateViewName(uint8_t _id, const char* _name)
  2276. {
  2277. bx::strlcpy(&s_viewName[_id][0], _name, sizeof(s_viewName[0][0]) );
  2278. }
  2279. void Context::rendererUpdateUniform(uint16_t _loc, const void* _data, uint32_t _size)
  2280. {
  2281. memcpy(s_renderCtx.m_uniforms[_loc], _data, _size);
  2282. }
  2283. void Context::rendererSetMarker(const char* _marker, uint32_t /*_size*/)
  2284. {
  2285. GREMEDY_SETMARKER(_marker);
  2286. }
  2287. void Context::rendererSubmit()
  2288. {
  2289. const GLuint defaultVao = s_renderCtx.m_vaoSupport;
  2290. if (0 != defaultVao)
  2291. {
  2292. GL_CHECK(glBindVertexArray(defaultVao) );
  2293. }
  2294. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_backBufferFbo) );
  2295. s_renderCtx.updateResolution(m_render->m_resolution);
  2296. int64_t elapsed = -bx::getHPCounter();
  2297. int64_t captureElapsed = 0;
  2298. #if BGFX_CONFIG_RENDERER_OPENGL
  2299. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2300. {
  2301. s_renderCtx.m_queries.begin(0, GL_TIME_ELAPSED);
  2302. }
  2303. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2304. if (0 < m_render->m_iboffset)
  2305. {
  2306. TransientIndexBuffer* ib = m_render->m_transientIb;
  2307. s_renderCtx.m_indexBuffers[ib->handle.idx].update(0, m_render->m_iboffset, ib->data);
  2308. }
  2309. if (0 < m_render->m_vboffset)
  2310. {
  2311. TransientVertexBuffer* vb = m_render->m_transientVb;
  2312. s_renderCtx.m_vertexBuffers[vb->handle.idx].update(0, m_render->m_vboffset, vb->data);
  2313. }
  2314. m_render->sort();
  2315. RenderState currentState;
  2316. currentState.reset();
  2317. currentState.m_flags = BGFX_STATE_NONE;
  2318. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  2319. Matrix4 viewProj[BGFX_CONFIG_MAX_VIEWS];
  2320. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  2321. {
  2322. mtxMul(viewProj[ii].val, m_render->m_view[ii].val, m_render->m_proj[ii].val);
  2323. }
  2324. uint16_t programIdx = invalidHandle;
  2325. SortKey key;
  2326. uint8_t view = 0xff;
  2327. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  2328. int32_t height = m_render->m_resolution.m_height;
  2329. float alphaRef = 0.0f;
  2330. uint32_t blendFactor = 0;
  2331. GLenum primType = m_render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINES : GL_TRIANGLES;
  2332. uint32_t primNumVerts = 3;
  2333. uint32_t baseVertex = 0;
  2334. GLuint currentVao = 0;
  2335. uint32_t statsNumPrimsSubmitted = 0;
  2336. uint32_t statsNumIndices = 0;
  2337. uint32_t statsNumInstances = 0;
  2338. uint32_t statsNumPrimsRendered = 0;
  2339. if (0 == (m_render->m_debug&BGFX_DEBUG_IFH) )
  2340. {
  2341. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderCtx.m_msaaBackBufferFbo) );
  2342. for (uint32_t item = 0, numItems = m_render->m_num; item < numItems; ++item)
  2343. {
  2344. key.decode(m_render->m_sortKeys[item]);
  2345. const RenderState& state = m_render->m_renderState[m_render->m_sortValues[item] ];
  2346. const uint64_t newFlags = state.m_flags;
  2347. uint64_t changedFlags = currentState.m_flags ^ state.m_flags;
  2348. currentState.m_flags = newFlags;
  2349. const uint64_t newStencil = state.m_stencil;
  2350. uint64_t changedStencil = currentState.m_stencil ^ state.m_stencil;
  2351. currentState.m_stencil = newStencil;
  2352. if (key.m_view != view)
  2353. {
  2354. currentState.clear();
  2355. changedFlags = BGFX_STATE_MASK;
  2356. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  2357. currentState.m_flags = newFlags;
  2358. GREMEDY_SETMARKER(s_viewName[key.m_view]);
  2359. view = key.m_view;
  2360. programIdx = invalidHandle;
  2361. if (m_render->m_rt[view].idx != rt.idx)
  2362. {
  2363. rt = m_render->m_rt[view];
  2364. height = s_renderCtx.setRenderTarget(rt, m_render->m_resolution.m_height);
  2365. }
  2366. Rect& rect = m_render->m_rect[view];
  2367. GL_CHECK(glViewport(rect.m_x, height-rect.m_height-rect.m_y, rect.m_width, rect.m_height) );
  2368. Clear& clear = m_render->m_clear[view];
  2369. if (BGFX_CLEAR_NONE != clear.m_flags)
  2370. {
  2371. m_clearQuad.clear(rect, clear, height);
  2372. }
  2373. Rect& scissorRect = m_render->m_scissor[view];
  2374. bool scissor = !scissorRect.isZero();
  2375. if (scissor)
  2376. {
  2377. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2378. GL_CHECK(glScissor(scissorRect.m_x, height-scissorRect.m_height-scissorRect.m_y, scissorRect.m_width, scissorRect.m_height) );
  2379. }
  2380. else
  2381. {
  2382. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2383. }
  2384. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2385. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2386. GL_CHECK(glDepthFunc(GL_LESS) );
  2387. GL_CHECK(glEnable(GL_CULL_FACE) );
  2388. GL_CHECK(glDisable(GL_BLEND) );
  2389. }
  2390. if (0 != changedStencil)
  2391. {
  2392. if (0 != newStencil)
  2393. {
  2394. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2395. uint32_t bstencil = unpackStencil(1, newStencil);
  2396. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  2397. // uint32_t bchanged = unpackStencil(1, changedStencil);
  2398. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  2399. // {
  2400. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2401. // GL_CHECK(glStencilMask(wmask) );
  2402. // }
  2403. for (uint32_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  2404. {
  2405. uint32_t stencil = unpackStencil(ii, newStencil);
  2406. uint32_t changed = unpackStencil(ii, changedStencil);
  2407. GLenum face = s_stencilFace[frontAndBack+ii];
  2408. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  2409. {
  2410. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  2411. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2412. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  2413. GL_CHECK(glStencilFuncSeparate(face, s_stencilFunc[func], ref, mask));
  2414. }
  2415. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  2416. {
  2417. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  2418. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  2419. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  2420. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  2421. }
  2422. }
  2423. }
  2424. else
  2425. {
  2426. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2427. }
  2428. }
  2429. if ( (0
  2430. | BGFX_STATE_CULL_MASK
  2431. | BGFX_STATE_DEPTH_WRITE
  2432. | BGFX_STATE_DEPTH_TEST_MASK
  2433. | BGFX_STATE_ALPHA_MASK
  2434. | BGFX_STATE_RGB_WRITE
  2435. | BGFX_STATE_BLEND_MASK
  2436. | BGFX_STATE_BLEND_EQUATION_MASK
  2437. | BGFX_STATE_ALPHA_REF_MASK
  2438. | BGFX_STATE_PT_MASK
  2439. | BGFX_STATE_POINT_SIZE_MASK
  2440. | BGFX_STATE_MSAA
  2441. ) & changedFlags)
  2442. {
  2443. if (BGFX_STATE_CULL_MASK & changedFlags)
  2444. {
  2445. if (BGFX_STATE_CULL_CW & newFlags)
  2446. {
  2447. GL_CHECK(glEnable(GL_CULL_FACE) );
  2448. GL_CHECK(glCullFace(GL_BACK) );
  2449. }
  2450. else if (BGFX_STATE_CULL_CCW & newFlags)
  2451. {
  2452. GL_CHECK(glEnable(GL_CULL_FACE) );
  2453. GL_CHECK(glCullFace(GL_FRONT) );
  2454. }
  2455. else
  2456. {
  2457. GL_CHECK(glDisable(GL_CULL_FACE) );
  2458. }
  2459. }
  2460. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  2461. {
  2462. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  2463. }
  2464. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  2465. {
  2466. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  2467. if (0 != func)
  2468. {
  2469. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2470. GL_CHECK(glDepthFunc(s_depthFunc[func]) );
  2471. }
  2472. else
  2473. {
  2474. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2475. }
  2476. }
  2477. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  2478. {
  2479. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  2480. alphaRef = ref/255.0f;
  2481. }
  2482. #if BGFX_CONFIG_RENDERER_OPENGL
  2483. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  2484. {
  2485. float pointSize = (float)(uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  2486. GL_CHECK(glPointSize(pointSize) );
  2487. }
  2488. if (BGFX_STATE_MSAA & changedFlags)
  2489. {
  2490. if (BGFX_STATE_MSAA & newFlags)
  2491. {
  2492. GL_CHECK(glEnable(GL_MULTISAMPLE) );
  2493. }
  2494. else
  2495. {
  2496. GL_CHECK(glDisable(GL_MULTISAMPLE) );
  2497. }
  2498. }
  2499. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2500. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  2501. {
  2502. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  2503. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  2504. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  2505. }
  2506. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK) & changedFlags)
  2507. {
  2508. if (BGFX_STATE_BLEND_MASK & newFlags)
  2509. {
  2510. uint32_t blend = (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT;
  2511. uint32_t equation = (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT;
  2512. uint32_t src = blend&0xf;
  2513. uint32_t dst = (blend>>4)&0xf;
  2514. GL_CHECK(glEnable(GL_BLEND) );
  2515. GL_CHECK(glBlendFunc(s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  2516. GL_CHECK(glBlendEquation(s_blendEquation[equation]) );
  2517. if ( (s_blendFactor[src].m_factor || s_blendFactor[dst].m_factor)
  2518. && blendFactor != state.m_rgba)
  2519. {
  2520. blendFactor = state.m_rgba;
  2521. GLclampf rr = (blendFactor>>24)/255.0f;
  2522. GLclampf gg = ( (blendFactor>>16)&0xff)/255.0f;
  2523. GLclampf bb = ( (blendFactor>>8)&0xff)/255.0f;
  2524. GLclampf aa = (blendFactor&0xff)/255.0f;
  2525. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  2526. }
  2527. }
  2528. else
  2529. {
  2530. GL_CHECK(glDisable(GL_BLEND) );
  2531. }
  2532. }
  2533. uint8_t primIndex = uint8_t( (newFlags&BGFX_STATE_PT_MASK)>>BGFX_STATE_PT_SHIFT);
  2534. primType = m_render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINES : s_primType[primIndex];
  2535. primNumVerts = 3-primIndex;
  2536. }
  2537. bool programChanged = false;
  2538. bool constantsChanged = state.m_constBegin < state.m_constEnd;
  2539. bool bindAttribs = false;
  2540. rendererUpdateUniforms(m_render->m_constantBuffer, state.m_constBegin, state.m_constEnd);
  2541. if (key.m_program != programIdx)
  2542. {
  2543. programIdx = key.m_program;
  2544. GLuint id = invalidHandle == programIdx ? 0 : s_renderCtx.m_program[programIdx].m_id;
  2545. GL_CHECK(glUseProgram(id) );
  2546. programChanged =
  2547. constantsChanged =
  2548. bindAttribs = true;
  2549. }
  2550. if (invalidHandle != programIdx)
  2551. {
  2552. Program& program = s_renderCtx.m_program[programIdx];
  2553. if (constantsChanged)
  2554. {
  2555. program.commit();
  2556. }
  2557. for (uint32_t ii = 0, num = program.m_numPredefined; ii < num; ++ii)
  2558. {
  2559. PredefinedUniform& predefined = program.m_predefined[ii];
  2560. switch (predefined.m_type)
  2561. {
  2562. case PredefinedUniform::ViewRect:
  2563. {
  2564. float rect[4];
  2565. rect[0] = m_render->m_rect[view].m_x;
  2566. rect[1] = m_render->m_rect[view].m_y;
  2567. rect[2] = m_render->m_rect[view].m_width;
  2568. rect[3] = m_render->m_rect[view].m_height;
  2569. GL_CHECK(glUniform4fv(predefined.m_loc
  2570. , 1
  2571. , &rect[0]
  2572. ) );
  2573. }
  2574. break;
  2575. case PredefinedUniform::ViewTexel:
  2576. {
  2577. float rect[4];
  2578. rect[0] = 1.0f/float(m_render->m_rect[view].m_width);
  2579. rect[1] = 1.0f/float(m_render->m_rect[view].m_height);
  2580. GL_CHECK(glUniform4fv(predefined.m_loc
  2581. , 1
  2582. , &rect[0]
  2583. ) );
  2584. }
  2585. break;
  2586. case PredefinedUniform::View:
  2587. {
  2588. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2589. , 1
  2590. , GL_FALSE
  2591. , m_render->m_view[view].val
  2592. ) );
  2593. }
  2594. break;
  2595. case PredefinedUniform::ViewProj:
  2596. {
  2597. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2598. , 1
  2599. , GL_FALSE
  2600. , viewProj[view].val
  2601. ) );
  2602. }
  2603. break;
  2604. case PredefinedUniform::Model:
  2605. {
  2606. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2607. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2608. , uint32_min(predefined.m_count, state.m_num)
  2609. , GL_FALSE
  2610. , model.val
  2611. ) );
  2612. }
  2613. break;
  2614. case PredefinedUniform::ModelView:
  2615. {
  2616. Matrix4 modelView;
  2617. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2618. mtxMul(modelView.val, model.val, m_render->m_view[view].val);
  2619. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2620. , 1
  2621. , GL_FALSE
  2622. , modelView.val
  2623. ) );
  2624. }
  2625. break;
  2626. case PredefinedUniform::ModelViewProj:
  2627. {
  2628. Matrix4 modelViewProj;
  2629. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2630. mtxMul(modelViewProj.val, model.val, viewProj[view].val);
  2631. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2632. , 1
  2633. , GL_FALSE
  2634. , modelViewProj.val
  2635. ) );
  2636. }
  2637. break;
  2638. case PredefinedUniform::ModelViewProjX:
  2639. {
  2640. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2641. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2642. {
  2643. 0.5f, 0.0f, 0.0f, 0.0f,
  2644. 0.0f, 0.5f, 0.0f, 0.0f,
  2645. 0.0f, 0.0f, 0.5f, 0.0f,
  2646. 0.5f, 0.5f, 0.5f, 1.0f,
  2647. };
  2648. uint8_t other = m_render->m_other[view];
  2649. Matrix4 viewProjBias;
  2650. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2651. Matrix4 modelViewProj;
  2652. mtxMul(modelViewProj.val, model.val, viewProjBias.val);
  2653. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2654. , 1
  2655. , GL_FALSE
  2656. , modelViewProj.val
  2657. ) );
  2658. }
  2659. break;
  2660. case PredefinedUniform::ViewProjX:
  2661. {
  2662. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2663. {
  2664. 0.5f, 0.0f, 0.0f, 0.0f,
  2665. 0.0f, 0.5f, 0.0f, 0.0f,
  2666. 0.0f, 0.0f, 0.5f, 0.0f,
  2667. 0.5f, 0.5f, 0.5f, 1.0f,
  2668. };
  2669. uint8_t other = m_render->m_other[view];
  2670. Matrix4 viewProjBias;
  2671. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2672. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  2673. , 1
  2674. , GL_FALSE
  2675. , viewProjBias.val
  2676. ) );
  2677. }
  2678. break;
  2679. case PredefinedUniform::AlphaRef:
  2680. {
  2681. GL_CHECK(glUniform1f(predefined.m_loc, alphaRef) );
  2682. }
  2683. break;
  2684. case PredefinedUniform::Count:
  2685. break;
  2686. }
  2687. }
  2688. // if (BGFX_STATE_TEX_MASK & changedFlags)
  2689. {
  2690. uint64_t flag = BGFX_STATE_TEX0;
  2691. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  2692. {
  2693. const Sampler& sampler = state.m_sampler[stage];
  2694. Sampler& current = currentState.m_sampler[stage];
  2695. if (current.m_idx != sampler.m_idx
  2696. || current.m_flags != sampler.m_flags
  2697. || programChanged)
  2698. {
  2699. if (invalidHandle != sampler.m_idx)
  2700. {
  2701. GL_CHECK(glActiveTexture(GL_TEXTURE0+stage) );
  2702. switch (sampler.m_flags&BGFX_SAMPLER_TYPE_MASK)
  2703. {
  2704. case BGFX_SAMPLER_TEXTURE:
  2705. {
  2706. const Texture& texture = s_renderCtx.m_textures[sampler.m_idx];
  2707. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  2708. }
  2709. break;
  2710. case BGFX_SAMPLER_RENDERTARGET_COLOR:
  2711. {
  2712. const RenderTarget& rt = s_renderCtx.m_renderTargets[sampler.m_idx];
  2713. GL_CHECK(glBindTexture(rt.m_color.m_target, rt.m_color.m_id) );
  2714. }
  2715. break;
  2716. case BGFX_SAMPLER_RENDERTARGET_DEPTH:
  2717. {
  2718. const RenderTarget& rt = s_renderCtx.m_renderTargets[sampler.m_idx];
  2719. GL_CHECK(glBindTexture(rt.m_depth.m_target, rt.m_depth.m_id) );
  2720. }
  2721. break;
  2722. }
  2723. }
  2724. }
  2725. current = sampler;
  2726. flag <<= 1;
  2727. }
  2728. }
  2729. if (0 != defaultVao
  2730. && 0 == state.m_startVertex
  2731. && 0 == state.m_instanceDataOffset)
  2732. {
  2733. if (programChanged
  2734. || currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx
  2735. || currentState.m_indexBuffer.idx != state.m_indexBuffer.idx
  2736. || currentState.m_instanceDataBuffer.idx != state.m_instanceDataBuffer.idx)
  2737. {
  2738. bx::HashMurmur2A murmur;
  2739. murmur.begin();
  2740. murmur.add(state.m_vertexBuffer.idx);
  2741. murmur.add(state.m_indexBuffer.idx);
  2742. murmur.add(state.m_instanceDataBuffer.idx);
  2743. murmur.add(programIdx);
  2744. uint32_t hash = murmur.end();
  2745. currentState.m_vertexBuffer = state.m_vertexBuffer;
  2746. currentState.m_indexBuffer = state.m_indexBuffer;
  2747. baseVertex = state.m_startVertex;
  2748. GLuint id = s_renderCtx.m_vaoCache.find(hash);
  2749. if (UINT32_MAX != id)
  2750. {
  2751. currentVao = id;
  2752. GL_CHECK(glBindVertexArray(id) );
  2753. }
  2754. else
  2755. {
  2756. id = s_renderCtx.m_vaoCache.add(hash);
  2757. currentVao = id;
  2758. GL_CHECK(glBindVertexArray(id) );
  2759. Program& program = s_renderCtx.m_program[programIdx];
  2760. program.add(hash);
  2761. if (invalidHandle != state.m_vertexBuffer.idx)
  2762. {
  2763. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[state.m_vertexBuffer.idx];
  2764. vb.add(hash);
  2765. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2766. uint16_t decl = vb.m_decl.idx == invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2767. program.bindAttributes(s_renderCtx.m_vertexDecls[decl], state.m_startVertex);
  2768. if (invalidHandle != state.m_instanceDataBuffer.idx)
  2769. {
  2770. VertexBuffer& instanceVb = s_renderCtx.m_vertexBuffers[state.m_instanceDataBuffer.idx];
  2771. instanceVb.add(hash);
  2772. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  2773. program.bindInstanceData(state.m_instanceDataStride, state.m_instanceDataOffset);
  2774. }
  2775. }
  2776. else
  2777. {
  2778. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  2779. }
  2780. if (invalidHandle != state.m_indexBuffer.idx)
  2781. {
  2782. IndexBuffer& ib = s_renderCtx.m_indexBuffers[state.m_indexBuffer.idx];
  2783. ib.add(hash);
  2784. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2785. }
  2786. else
  2787. {
  2788. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  2789. }
  2790. }
  2791. }
  2792. }
  2793. else
  2794. {
  2795. if (0 != defaultVao
  2796. && 0 != currentVao)
  2797. {
  2798. GL_CHECK(glBindVertexArray(defaultVao) );
  2799. currentState.m_vertexBuffer.idx = invalidHandle;
  2800. currentState.m_indexBuffer.idx = invalidHandle;
  2801. bindAttribs = true;
  2802. currentVao = 0;
  2803. }
  2804. if (programChanged
  2805. || currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx)
  2806. {
  2807. currentState.m_vertexBuffer = state.m_vertexBuffer;
  2808. uint16_t handle = state.m_vertexBuffer.idx;
  2809. if (invalidHandle != handle)
  2810. {
  2811. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[handle];
  2812. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2813. bindAttribs = true;
  2814. }
  2815. else
  2816. {
  2817. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  2818. }
  2819. }
  2820. if (currentState.m_indexBuffer.idx != state.m_indexBuffer.idx)
  2821. {
  2822. currentState.m_indexBuffer = state.m_indexBuffer;
  2823. uint16_t handle = state.m_indexBuffer.idx;
  2824. if (invalidHandle != handle)
  2825. {
  2826. IndexBuffer& ib = s_renderCtx.m_indexBuffers[handle];
  2827. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2828. }
  2829. else
  2830. {
  2831. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  2832. }
  2833. }
  2834. if (invalidHandle != currentState.m_vertexBuffer.idx)
  2835. {
  2836. if (baseVertex != state.m_startVertex
  2837. || bindAttribs)
  2838. {
  2839. baseVertex = state.m_startVertex;
  2840. const VertexBuffer& vb = s_renderCtx.m_vertexBuffers[state.m_vertexBuffer.idx];
  2841. uint16_t decl = vb.m_decl.idx == invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2842. const Program& program = s_renderCtx.m_program[programIdx];
  2843. program.bindAttributes(s_renderCtx.m_vertexDecls[decl], state.m_startVertex);
  2844. if (invalidHandle != state.m_instanceDataBuffer.idx)
  2845. {
  2846. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, s_renderCtx.m_vertexBuffers[state.m_instanceDataBuffer.idx].m_id) );
  2847. program.bindInstanceData(state.m_instanceDataStride, state.m_instanceDataOffset);
  2848. }
  2849. }
  2850. }
  2851. }
  2852. if (invalidHandle != currentState.m_vertexBuffer.idx)
  2853. {
  2854. uint32_t numVertices = state.m_numVertices;
  2855. if (UINT32_C(0xffffffff) == numVertices)
  2856. {
  2857. const VertexBuffer& vb = s_renderCtx.m_vertexBuffers[currentState.m_vertexBuffer.idx];
  2858. uint16_t decl = vb.m_decl.idx == invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2859. const VertexDecl& vertexDecl = s_renderCtx.m_vertexDecls[decl];
  2860. numVertices = vb.m_size/vertexDecl.m_stride;
  2861. }
  2862. uint32_t numIndices = 0;
  2863. uint32_t numPrimsSubmitted = 0;
  2864. uint32_t numInstances = 0;
  2865. uint32_t numPrimsRendered = 0;
  2866. if (invalidHandle != state.m_indexBuffer.idx)
  2867. {
  2868. if (UINT32_MAX == state.m_numIndices)
  2869. {
  2870. numIndices = s_renderCtx.m_indexBuffers[state.m_indexBuffer.idx].m_size/2;
  2871. numPrimsSubmitted = numIndices/primNumVerts;
  2872. numInstances = state.m_numInstances;
  2873. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2874. GL_CHECK(s_drawElementsInstanced(primType
  2875. , numIndices
  2876. , GL_UNSIGNED_SHORT
  2877. , (void*)0
  2878. , state.m_numInstances
  2879. ) );
  2880. }
  2881. else if (primNumVerts <= state.m_numIndices)
  2882. {
  2883. numIndices = state.m_numIndices;
  2884. numPrimsSubmitted = numIndices/primNumVerts;
  2885. numInstances = state.m_numInstances;
  2886. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2887. GL_CHECK(s_drawElementsInstanced(primType
  2888. , numIndices
  2889. , GL_UNSIGNED_SHORT
  2890. , (void*)(uintptr_t)(state.m_startIndex*2)
  2891. , state.m_numInstances
  2892. ) );
  2893. }
  2894. }
  2895. else
  2896. {
  2897. numPrimsSubmitted = numVertices/primNumVerts;
  2898. numInstances = state.m_numInstances;
  2899. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2900. GL_CHECK(s_drawArraysInstanced(primType
  2901. , 0
  2902. , numVertices
  2903. , state.m_numInstances
  2904. ) );
  2905. }
  2906. statsNumPrimsSubmitted += numPrimsSubmitted;
  2907. statsNumIndices += numIndices;
  2908. statsNumInstances += numInstances;
  2909. statsNumPrimsRendered += numPrimsRendered;
  2910. }
  2911. }
  2912. }
  2913. s_renderCtx.blitMsaaFbo();
  2914. if (0 < m_render->m_num)
  2915. {
  2916. captureElapsed = -bx::getHPCounter();
  2917. s_renderCtx.capture();
  2918. captureElapsed += bx::getHPCounter();
  2919. }
  2920. }
  2921. int64_t now = bx::getHPCounter();
  2922. elapsed += now;
  2923. static int64_t last = now;
  2924. int64_t frameTime = now - last;
  2925. last = now;
  2926. static int64_t min = frameTime;
  2927. static int64_t max = frameTime;
  2928. min = min > frameTime ? frameTime : min;
  2929. max = max < frameTime ? frameTime : max;
  2930. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2931. {
  2932. double elapsedGpuMs = 0.0;
  2933. #if BGFX_CONFIG_RENDERER_OPENGL
  2934. s_renderCtx.m_queries.end(GL_TIME_ELAPSED);
  2935. uint64_t elapsedGl = s_renderCtx.m_queries.getResult(0);
  2936. elapsedGpuMs = double(elapsedGl)/1e6;
  2937. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2938. TextVideoMem& tvm = s_renderCtx.m_textVideoMem;
  2939. static int64_t next = now;
  2940. if (now >= next)
  2941. {
  2942. next = now + bx::getHPFrequency();
  2943. double freq = double(bx::getHPFrequency() );
  2944. double toMs = 1000.0/freq;
  2945. tvm.clear();
  2946. uint16_t pos = 0;
  2947. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " " BGFX_RENDERER_NAME " ");
  2948. tvm.printf(0, pos++, 0x0f, " Vendor: %s", s_renderCtx.m_vendor);
  2949. tvm.printf(0, pos++, 0x0f, " Renderer: %s", s_renderCtx.m_renderer);
  2950. tvm.printf(0, pos++, 0x0f, " Version: %s", s_renderCtx.m_version);
  2951. tvm.printf(0, pos++, 0x0f, "GLSL version: %s", s_renderCtx.m_glslVersion);
  2952. pos = 10;
  2953. tvm.printf(10, pos++, 0x8e, " Frame CPU: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS%s"
  2954. , double(frameTime)*toMs
  2955. , double(min)*toMs
  2956. , double(max)*toMs
  2957. , freq/frameTime
  2958. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? " (vsync)" : ""
  2959. );
  2960. double elapsedCpuMs = double(elapsed)*toMs;
  2961. tvm.printf(10, pos++, 0x8e, " Draw calls: %4d / CPU %3.4f [ms] %c GPU %3.4f [ms]"
  2962. , m_render->m_num
  2963. , elapsedCpuMs
  2964. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  2965. , elapsedGpuMs
  2966. );
  2967. tvm.printf(10, pos++, 0x8e, " Prims: %7d (#inst: %5d), submitted: %7d"
  2968. , statsNumPrimsRendered
  2969. , statsNumInstances
  2970. , statsNumPrimsSubmitted
  2971. );
  2972. double captureMs = double(captureElapsed)*toMs;
  2973. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  2974. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  2975. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", m_render->m_vboffset);
  2976. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", m_render->m_iboffset);
  2977. #if BGFX_CONFIG_RENDERER_OPENGL
  2978. if (s_extension[Extension::ATI_meminfo].m_supported)
  2979. {
  2980. GLint vboFree[4];
  2981. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  2982. GLint texFree[4];
  2983. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  2984. GLint rbfFree[4];
  2985. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  2986. pos++;
  2987. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb");
  2988. tvm.printf(10, pos++, 0x8e, " VBO: %7d, %7d, %7d, %7d", vboFree[0], vboFree[1], vboFree[2], vboFree[3]);
  2989. tvm.printf(10, pos++, 0x8e, " Texture: %7d, %7d, %7d, %7d", texFree[0], texFree[1], texFree[2], texFree[3]);
  2990. tvm.printf(10, pos++, 0x8e, " Render Buffer: %7d, %7d, %7d, %7d", rbfFree[0], rbfFree[1], rbfFree[2], rbfFree[3]);
  2991. }
  2992. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  2993. {
  2994. GLint dedicated;
  2995. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  2996. GLint totalAvail;
  2997. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  2998. GLint currAvail;
  2999. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  3000. GLint evictedCount;
  3001. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  3002. GLint evictedMemory;
  3003. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  3004. pos++;
  3005. tvm.printf(10, pos++, 0x8c, "----------|");
  3006. tvm.printf(10, pos++, 0x8e, " Dedicated: %7d", dedicated);
  3007. tvm.printf(10, pos++, 0x8e, " Available: %7d (%7d)", currAvail, totalAvail);
  3008. tvm.printf(10, pos++, 0x8e, " Eviction: %7d / %7d", evictedCount, evictedMemory);
  3009. }
  3010. #endif // BGFX_CONFIG_RENDERER_OPENGL
  3011. uint8_t attr[2] = { 0x89, 0x8a };
  3012. uint8_t attrIndex = m_render->m_waitSubmit < m_render->m_waitRender;
  3013. pos++;
  3014. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", double(m_render->m_waitSubmit)*toMs);
  3015. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", double(m_render->m_waitRender)*toMs);
  3016. min = frameTime;
  3017. max = frameTime;
  3018. }
  3019. m_textVideoMemBlitter.blit(tvm);
  3020. }
  3021. else if (m_render->m_debug & BGFX_DEBUG_TEXT)
  3022. {
  3023. m_textVideoMemBlitter.blit(m_render->m_textVideoMem);
  3024. }
  3025. GREMEDY_FRAMETERMINATOR();
  3026. }
  3027. }
  3028. #endif // (BGFX_CONFIG_RENDERER_OPENGLES2|BGFX_CONFIG_RENDERER_OPENGLES3|BGFX_CONFIG_RENDERER_OPENGL)