renderer_gl.cpp 96 KB

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