renderer_gl.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. /*
  2. * Copyright 2011-2012 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_OPENGLES|BGFX_CONFIG_RENDERER_OPENGL)
  7. # include "renderer_gl.h"
  8. # include <bx/timer.h>
  9. # include <bx/uint32_t.h>
  10. #if BGFX_CONFIG_RENDERER_OPENGL
  11. # define glClearDepthf(_depth) glClearDepth(_depth)
  12. #endif // BGFX_CONFIG_RENDERER_OPENGL
  13. namespace bgfx
  14. {
  15. #if BGFX_USE_WGL
  16. PFNWGLGETPROCADDRESSPROC wglGetProcAddress;
  17. PFNWGLMAKECURRENTPROC wglMakeCurrent;
  18. PFNWGLCREATECONTEXTPROC wglCreateContext;
  19. PFNWGLDELETECONTEXTPROC wglDeleteContext;
  20. #endif // BGFX_USE_WGL
  21. #define GL_IMPORT(_optional, _proto, _func) _proto _func
  22. #include "glimports.h"
  23. #undef GL_IMPORT
  24. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  25. #if BX_PLATFORM_NACL
  26. void naclSwapCompleteCb(void* _data, int32_t _result);
  27. PP_CompletionCallback naclSwapComplete =
  28. {
  29. naclSwapCompleteCb,
  30. NULL,
  31. PP_COMPLETIONCALLBACK_FLAG_NONE
  32. };
  33. #endif // BX_PLATFORM_NACL
  34. struct RendererContext
  35. {
  36. RendererContext()
  37. : m_dxtSupport(false)
  38. , m_flip(false)
  39. , m_postSwapBuffers(NULL)
  40. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  41. #if BX_PLATFORM_NACL
  42. , m_context(0)
  43. , m_instance(0)
  44. , m_instInterface(NULL)
  45. , m_graphicsInterface(NULL)
  46. #elif BGFX_USE_WGL
  47. , m_context(NULL)
  48. , m_hdc(NULL)
  49. #elif BGFX_USE_EGL
  50. , m_context(NULL)
  51. , m_display(NULL)
  52. , m_surface(NULL)
  53. #elif BX_PLATFORM_LINUX
  54. , m_context(0)
  55. , m_window(0)
  56. , m_display(NULL)
  57. #endif // BX_PLATFORM_
  58. {
  59. memset(&m_resolution, 0, sizeof(m_resolution) );
  60. }
  61. void updateResolution(const Resolution& _resolution)
  62. {
  63. if (m_resolution.m_width != _resolution.m_width
  64. || m_resolution.m_height != _resolution.m_height
  65. || m_resolution.m_flags != _resolution.m_flags)
  66. {
  67. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  68. m_textVideoMem.clear();
  69. m_resolution = _resolution;
  70. setRenderContextSize(_resolution.m_width, _resolution.m_height);
  71. }
  72. }
  73. void setRenderContextSize(uint32_t _width, uint32_t _height)
  74. {
  75. if (_width != 0
  76. || _height != 0)
  77. {
  78. #if BX_PLATFORM_NACL
  79. if (0 == m_context)
  80. {
  81. BX_TRACE("create context");
  82. int32_t attribs[] =
  83. {
  84. PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
  85. PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
  86. PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8,
  87. PP_GRAPHICS3DATTRIB_SAMPLES, 0,
  88. PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0,
  89. PP_GRAPHICS3DATTRIB_WIDTH, _width,
  90. PP_GRAPHICS3DATTRIB_HEIGHT, _height,
  91. PP_GRAPHICS3DATTRIB_NONE
  92. };
  93. m_context = m_graphicsInterface->Create(m_instance, 0, attribs);
  94. m_instInterface->BindGraphics(m_instance, m_context);
  95. glSetCurrentContextPPAPI(m_context);
  96. m_graphicsInterface->SwapBuffers(m_context, naclSwapComplete);
  97. // # define GL_IMPORT(_optional, _proto, _func) \
  98. // { \
  99. // _func = (_proto)eglGetProcAddress(#_func); \
  100. // BGFX_FATAL(_optional || NULL != _func, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to create OpenGL context. eglGetProcAddress(\"%s\")", #_func); \
  101. // }
  102. // # include "glimports.h"
  103. // # undef GL_IMPORT
  104. }
  105. else
  106. {
  107. m_graphicsInterface->ResizeBuffers(m_context, _width, _height);
  108. }
  109. #elif BGFX_USE_WGL
  110. if (NULL == m_hdc)
  111. {
  112. m_opengl32dll = LoadLibrary("opengl32.dll");
  113. BGFX_FATAL(NULL != m_opengl32dll, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to load opengl32.dll.");
  114. wglGetProcAddress = (PFNWGLGETPROCADDRESSPROC)GetProcAddress(m_opengl32dll, "wglGetProcAddress");
  115. BGFX_FATAL(NULL != wglGetProcAddress, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed get wglGetProcAddress.");
  116. wglMakeCurrent = (PFNWGLMAKECURRENTPROC)GetProcAddress(m_opengl32dll, "wglMakeCurrent");
  117. BGFX_FATAL(NULL != wglMakeCurrent, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed get wglMakeCurrent.");
  118. wglCreateContext = (PFNWGLCREATECONTEXTPROC)GetProcAddress(m_opengl32dll, "wglCreateContext");
  119. BGFX_FATAL(NULL != wglCreateContext, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed get wglCreateContext.");
  120. wglDeleteContext = (PFNWGLDELETECONTEXTPROC)GetProcAddress(m_opengl32dll, "wglDeleteContext");
  121. BGFX_FATAL(NULL != wglDeleteContext, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed get wglDeleteContext.");
  122. m_hdc = GetDC(g_bgfxHwnd);
  123. BGFX_FATAL(NULL != m_hdc, bgfx::Fatal::OPENGL_UnableToCreateContext, "GetDC failed!");
  124. PIXELFORMATDESCRIPTOR pfd;
  125. memset(&pfd, 0, sizeof(pfd) );
  126. pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
  127. pfd.nVersion = 1;
  128. pfd.iPixelType = PFD_TYPE_RGBA;
  129. pfd.cColorBits = 32;
  130. pfd.cAlphaBits = 8;
  131. pfd.cDepthBits = 24;
  132. pfd.cStencilBits = 8;
  133. pfd.iLayerType = PFD_MAIN_PLANE;
  134. int pixelFormat = ChoosePixelFormat(m_hdc, &pfd);
  135. BGFX_FATAL(0 != pixelFormat, bgfx::Fatal::OPENGL_UnableToCreateContext, "ChoosePixelFormat failed!");
  136. DescribePixelFormat(m_hdc, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
  137. int result;
  138. result = SetPixelFormat(m_hdc, pixelFormat, &pfd);
  139. BGFX_FATAL(0 != result, bgfx::Fatal::OPENGL_UnableToCreateContext, "SetPixelFormat failed!");
  140. m_context = wglCreateContext(m_hdc);
  141. BGFX_FATAL(NULL != m_context, bgfx::Fatal::OPENGL_UnableToCreateContext, "wglCreateContext failed!");
  142. result = wglMakeCurrent(m_hdc, m_context);
  143. BGFX_FATAL(0 != result, bgfx::Fatal::OPENGL_UnableToCreateContext, "wglMakeCurrent failed!");
  144. # define GL_IMPORT(_optional, _proto, _func) \
  145. { \
  146. _func = (_proto)wglGetProcAddress(#_func); \
  147. if (_func == NULL) \
  148. { \
  149. _func = (_proto)GetProcAddress(m_opengl32dll, #_func); \
  150. } \
  151. BGFX_FATAL(_optional || NULL != _func, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to create OpenGL context. wglGetProcAddress(\"%s\")", #_func); \
  152. }
  153. # include "glimports.h"
  154. # undef GL_IMPORT
  155. }
  156. #elif BX_PLATFORM_LINUX
  157. if (0 == m_display)
  158. {
  159. Display* display = XOpenDisplay(0);
  160. XLockDisplay(display);
  161. BGFX_FATAL(display, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to open X display (0).");
  162. int glxMajor, glxMinor;
  163. if (!glXQueryVersion(display, &glxMajor, &glxMinor))
  164. {
  165. BGFX_FATAL(false, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to query GLX version");
  166. }
  167. BGFX_FATAL((glxMajor == 1 && glxMinor >= 3) || glxMajor > 1, bgfx::Fatal::OPENGL_UnableToCreateContext, "GLX version is not >=1.3 (%d.%d).", glxMajor, glxMinor);
  168. const int glxAttribs[] =
  169. {
  170. GLX_X_RENDERABLE, True,
  171. GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
  172. GLX_RENDER_TYPE, GLX_RGBA_BIT,
  173. GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
  174. GLX_RED_SIZE, 8,
  175. GLX_BLUE_SIZE, 8,
  176. GLX_GREEN_SIZE, 8,
  177. GLX_ALPHA_SIZE, 8,
  178. GLX_DEPTH_SIZE, 24,
  179. GLX_STENCIL_SIZE, 8,
  180. GLX_DOUBLEBUFFER, True,
  181. None,
  182. };
  183. // Find suitable config
  184. GLXFBConfig bestconfig = NULL;
  185. int nconfigs;
  186. GLXFBConfig* configs = glXChooseFBConfig(display, DefaultScreen(display), glxAttribs, &nconfigs);
  187. XVisualInfo* visualInfo = 0;
  188. for (int ii = 0; ii < nconfigs; ++ii)
  189. {
  190. visualInfo = glXGetVisualFromFBConfig(display, configs[ii]);
  191. if (visualInfo)
  192. {
  193. // Check if meets min spec
  194. bool validconfig = true;
  195. for (uint32_t attridx = 0; attridx < countof(glxAttribs)-1 && glxAttribs[attridx] != None; attridx += 2)
  196. {
  197. int value;
  198. glXGetFBConfigAttrib(display, configs[ii], glxAttribs[attridx], &value);
  199. if (value < glxAttribs[attridx + 1])
  200. {
  201. validconfig = false;
  202. break;
  203. }
  204. }
  205. if (validconfig)
  206. {
  207. bestconfig = configs[ii];
  208. break;
  209. }
  210. }
  211. XFree(visualInfo);
  212. visualInfo = 0;
  213. }
  214. XFree(configs);
  215. BGFX_FATAL(visualInfo, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to find a suitable X11 display configuration.");
  216. // Generate colormaps
  217. XSetWindowAttributes windowAttrs;
  218. windowAttrs.colormap = XCreateColormap(display, RootWindow(display, visualInfo->screen), visualInfo->visual, AllocNone);
  219. windowAttrs.background_pixmap = None;
  220. windowAttrs.border_pixel = 0;
  221. Window window = XCreateWindow(
  222. display
  223. , RootWindow(display, visualInfo->screen)
  224. , 0, 0
  225. , _width, _height, 0, visualInfo->depth
  226. , InputOutput
  227. , visualInfo->visual
  228. , CWBorderPixel|CWColormap
  229. , &windowAttrs
  230. );
  231. BGFX_FATAL(window, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to create X11 window.");
  232. XMapRaised(display, window);
  233. XFlush(display);
  234. XFree(visualInfo);
  235. BX_TRACE("create context");
  236. typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
  237. glXCreateContextAttribsARBProc glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
  238. BGFX_FATAL(glXCreateContextAttribsARB, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to get glXCreateContextAttribsARB.");
  239. const int contextArrib[] =
  240. {
  241. GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
  242. GLX_CONTEXT_MINOR_VERSION_ARB, 0,
  243. None,
  244. };
  245. m_context = glXCreateContextAttribsARB(display, bestconfig, 0, True, contextArrib);
  246. BGFX_FATAL(m_context, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to create GLX context.");
  247. glXMakeCurrent(display, window, m_context);
  248. # define GL_IMPORT(_optional, _proto, _func) \
  249. { \
  250. _func = (_proto)glXGetProcAddress((const GLubyte*)#_func); \
  251. BGFX_FATAL(_optional || NULL != _func, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to create OpenGL context. glXGetProcAddress %s", #_func); \
  252. }
  253. # include "glimports.h"
  254. # undef GL_IMPORT
  255. glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  256. glClear(GL_COLOR_BUFFER_BIT);
  257. glXSwapBuffers(display, window);
  258. m_display = display;
  259. m_window = window;
  260. XUnlockDisplay(display);
  261. }
  262. else
  263. {
  264. XResizeWindow(m_display, m_window, _width, _height);
  265. }
  266. #elif BGFX_USE_EGL
  267. if (NULL == m_context)
  268. {
  269. m_display = eglGetDisplay(NULL);
  270. BGFX_FATAL(m_display != EGL_NO_DISPLAY, Fatal::OPENGL_UnableToCreateContext, "Failed to create display 0x%08x", m_display);
  271. EGLint major = 0;
  272. EGLint minor = 0;
  273. EGLBoolean success = eglInitialize(m_display, &major, &minor);
  274. BGFX_FATAL(success && major >= 1 && minor >= 4, Fatal::OPENGL_UnableToCreateContext, "Failed to initialize %d.%d", major, minor);
  275. EGLint attrs[] =
  276. {
  277. # if BX_PLATFORM_ANDROID
  278. EGL_DEPTH_SIZE, 16,
  279. # else
  280. EGL_DEPTH_SIZE, 24,
  281. # endif // BX_PLATFORM_
  282. EGL_NONE
  283. };
  284. EGLint numConfig = 0;
  285. EGLConfig config = 0;
  286. success = eglChooseConfig(m_display, attrs, &config, 1, &numConfig);
  287. BGFX_FATAL(success, Fatal::OPENGL_UnableToCreateContext, "eglChooseConfig");
  288. m_surface = eglCreateWindowSurface(m_display, config, (EGLNativeWindowType)g_bgfxHwnd, NULL);
  289. BGFX_FATAL(m_surface != EGL_NO_SURFACE, Fatal::OPENGL_UnableToCreateContext, "Failed to create surface.");
  290. m_context = eglCreateContext(m_display, config, EGL_NO_CONTEXT, NULL);
  291. BGFX_FATAL(m_context != EGL_NO_CONTEXT, Fatal::OPENGL_UnableToCreateContext, "Failed to create context.");
  292. success = eglMakeCurrent(m_display, m_surface, m_surface, m_context);
  293. BGFX_FATAL(success, Fatal::OPENGL_UnableToCreateContext, "Failed to set context.");
  294. # define GL_IMPORT(_optional, _proto, _func) \
  295. { \
  296. _func = (_proto)eglGetProcAddress(#_func); \
  297. BGFX_FATAL(_optional || NULL != _func, bgfx::Fatal::OPENGL_UnableToCreateContext, "Failed to create OpenGLES context. eglGetProcAddress(\"%s\")", #_func); \
  298. }
  299. # include "glimports.h"
  300. # undef GL_IMPORT
  301. }
  302. #endif // BX_PLATFORM_
  303. }
  304. m_flip = true;
  305. }
  306. void flip()
  307. {
  308. if (m_flip)
  309. {
  310. #if BX_PLATFORM_NACL
  311. glSetCurrentContextPPAPI(m_context);
  312. m_graphicsInterface->SwapBuffers(m_context, naclSwapComplete);
  313. #elif BGFX_USE_WGL
  314. wglMakeCurrent(m_hdc, m_context);
  315. SwapBuffers(m_hdc);
  316. #elif BGFX_USE_EGL
  317. eglMakeCurrent(m_display, m_surface, m_surface, m_context);
  318. eglSwapBuffers(m_display, m_surface);
  319. #elif BX_PLATFORM_LINUX
  320. glXSwapBuffers(m_display, m_window);
  321. #endif // BX_PLATFORM_
  322. }
  323. if (NULL != m_postSwapBuffers)
  324. {
  325. m_postSwapBuffers(m_resolution.m_width, m_resolution.m_height);
  326. }
  327. }
  328. void saveScreenShot(Memory* _mem)
  329. {
  330. #if BGFX_CONFIG_RENDERER_OPENGL
  331. void* data = g_realloc(NULL, m_resolution.m_width*m_resolution.m_height*4);
  332. glReadPixels(0, 0, m_resolution.m_width, m_resolution.m_height, GL_RGBA, GL_UNSIGNED_BYTE, data);
  333. uint8_t* rgba = (uint8_t*)data;
  334. for (uint32_t ii = 0, num = m_resolution.m_width*m_resolution.m_height; ii < num; ++ii)
  335. {
  336. uint8_t temp = rgba[0];
  337. rgba[0] = rgba[2];
  338. rgba[2] = temp;
  339. rgba += 4;
  340. }
  341. saveTga( (const char*)_mem->data, m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, data, false, true);
  342. g_free(data);
  343. #endif // BGFX_CONFIG_RENDERER_OPENGL
  344. }
  345. void init()
  346. {
  347. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  348. }
  349. void shutdown()
  350. {
  351. #if BGFX_USE_WGL
  352. if (NULL != m_hdc)
  353. {
  354. wglMakeCurrent(NULL, NULL);
  355. wglDeleteContext(m_context);
  356. m_context = NULL;
  357. }
  358. FreeLibrary(m_opengl32dll);
  359. #elif BGFX_USE_EGL
  360. eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  361. eglDestroyContext(m_display, m_context);
  362. eglDestroySurface(m_display, m_surface);
  363. eglTerminate(m_display);
  364. m_context = NULL;
  365. #endif // BGFX_USE_
  366. }
  367. IndexBuffer m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  368. VertexBuffer m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  369. Shader m_vertexShaders[BGFX_CONFIG_MAX_VERTEX_SHADERS];
  370. Shader m_fragmentShaders[BGFX_CONFIG_MAX_FRAGMENT_SHADERS];
  371. Material m_materials[BGFX_CONFIG_MAX_MATERIALS];
  372. Texture m_textures[BGFX_CONFIG_MAX_TEXTURES];
  373. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  374. RenderTarget m_renderTargets[BGFX_CONFIG_MAX_RENDER_TARGETS];
  375. UniformRegistry m_uniformReg;
  376. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  377. TextVideoMem m_textVideoMem;
  378. Resolution m_resolution;
  379. bool m_dxtSupport;
  380. bool m_flip;
  381. PostSwapBuffersFn m_postSwapBuffers;
  382. uint64_t m_hash;
  383. #if BX_PLATFORM_NACL
  384. PP_Resource m_context;
  385. PP_Instance m_instance;
  386. const PPB_Instance* m_instInterface;
  387. const PPB_Graphics3D* m_graphicsInterface;
  388. #elif BGFX_USE_WGL
  389. HMODULE m_opengl32dll;
  390. HGLRC m_context;
  391. HDC m_hdc;
  392. #elif BGFX_USE_EGL
  393. EGLContext m_context;
  394. EGLDisplay m_display;
  395. EGLSurface m_surface;
  396. #elif BX_PLATFORM_LINUX
  397. GLXContext m_context;
  398. Window m_window;
  399. Display* m_display;
  400. #endif // BX_PLATFORM_NACL
  401. };
  402. RendererContext s_renderCtx;
  403. #if BX_PLATFORM_NACL
  404. void naclSetIntefraces(PP_Instance _instance, const PPB_Instance* _instInterface, const PPB_Graphics3D* _graphicsInterface, PostSwapBuffersFn _postSwapBuffers)
  405. {
  406. s_renderCtx.m_instance = _instance;
  407. s_renderCtx.m_instInterface = _instInterface;
  408. s_renderCtx.m_graphicsInterface = _graphicsInterface;
  409. s_renderCtx.m_postSwapBuffers = _postSwapBuffers;
  410. s_renderCtx.setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  411. }
  412. void naclSwapCompleteCb(void* /*_data*/, int32_t /*_result*/)
  413. {
  414. renderFrame();
  415. }
  416. #elif BX_PLATFORM_LINUX
  417. bool linuxGetDisplay(Display** _display, Window* _window)
  418. {
  419. if (!s_renderCtx.m_display)
  420. {
  421. return false;
  422. }
  423. *_display = s_renderCtx.m_display;
  424. *_window = s_renderCtx.m_window;
  425. return true;
  426. }
  427. #endif // BX_PLATFORM_
  428. struct Extension
  429. {
  430. enum Enum
  431. {
  432. EXT_texture_format_BGRA8888,
  433. EXT_texture_compression_s3tc,
  434. EXT_texture_compression_dxt1,
  435. CHROMIUM_texture_compression_dxt3,
  436. CHROMIUM_texture_compression_dxt5,
  437. OES_standard_derivatives,
  438. ARB_get_program_binary,
  439. OES_get_program_binary,
  440. EXT_framebuffer_blit,
  441. ARB_timer_query,
  442. EXT_timer_query,
  443. EXT_texture_sRGB,
  444. ARB_framebuffer_sRGB,
  445. EXT_framebuffer_sRGB,
  446. ARB_multisample,
  447. CHROMIUM_framebuffer_multisample,
  448. ANGLE_translated_shader_source,
  449. ANGLE_instanced_arrays,
  450. OES_texture_float,
  451. OES_texture_float_linear,
  452. OES_texture_half_float,
  453. OES_texture_half_float_linear,
  454. EXT_occlusion_query_boolean,
  455. Count
  456. };
  457. const char* m_name;
  458. bool m_supported;
  459. bool m_initialize;
  460. };
  461. static Extension s_extension[Extension::Count] =
  462. {
  463. // Nvidia BGRA on Linux bug:
  464. // https://groups.google.com/a/chromium.org/forum/?fromgroups#!topic/chromium-reviews/yFfbUdyeUCQ
  465. { "GL_EXT_texture_format_BGRA8888", false, !BX_PLATFORM_LINUX },
  466. { "GL_EXT_texture_compression_s3tc", false, true },
  467. { "GL_EXT_texture_compression_dxt1", false, true },
  468. { "GL_CHROMIUM_texture_compression_dxt3", false, true },
  469. { "GL_CHROMIUM_texture_compression_dxt5", false, true },
  470. { "GL_OES_standard_derivatives", false, true },
  471. { "GL_ARB_get_program_binary", false, true },
  472. { "GL_OES_get_program_binary", false, false },
  473. { "GL_EXT_framebuffer_blit", false, true },
  474. { "GL_ARB_timer_query", false, true },
  475. { "GL_EXT_timer_query", false, true },
  476. { "GL_EXT_texture_sRGB", false, true },
  477. { "GL_ARB_framebuffer_sRGB", false, true },
  478. { "GL_EXT_framebuffer_sRGB", false, true },
  479. { "GL_ARB_multisample", false, true },
  480. { "GL_CHROMIUM_framebuffer_multisample", false, true },
  481. { "GL_ANGLE_translated_shader_source", false, true },
  482. { "GL_ANGLE_instanced_arrays", false, true },
  483. { "GL_OES_texture_float", false, true },
  484. { "GL_OES_texture_float_linear", false, true },
  485. { "GL_OES_texture_half_float", false, true },
  486. { "GL_OES_texture_half_float_linear", false, true },
  487. { "GL_EXT_occlusion_query_boolean", false, true },
  488. };
  489. static const GLenum s_primType[] =
  490. {
  491. GL_TRIANGLES,
  492. GL_LINES,
  493. GL_POINTS,
  494. };
  495. static const uint32_t s_primNumVerts[] =
  496. {
  497. 3,
  498. 2,
  499. 1,
  500. };
  501. static const char* s_attribName[Attrib::Count] =
  502. {
  503. "a_position",
  504. "a_normal",
  505. "a_color",
  506. "a_color1",
  507. "a_indices",
  508. "a_weight",
  509. "a_texcoord0",
  510. "a_texcoord1",
  511. "a_texcoord2",
  512. "a_texcoord3",
  513. "a_texcoord4",
  514. "a_texcoord5",
  515. "a_texcoord6",
  516. "a_texcoord7",
  517. };
  518. static const GLenum s_attribType[AttribType::Count] =
  519. {
  520. GL_UNSIGNED_BYTE,
  521. GL_UNSIGNED_SHORT,
  522. GL_FLOAT,
  523. };
  524. static const GLenum s_blendFactor[] =
  525. {
  526. 0, // ignored
  527. GL_ZERO,
  528. GL_ONE,
  529. GL_SRC_COLOR,
  530. GL_ONE_MINUS_SRC_COLOR,
  531. GL_SRC_ALPHA,
  532. GL_ONE_MINUS_SRC_ALPHA,
  533. GL_DST_ALPHA,
  534. GL_ONE_MINUS_DST_ALPHA,
  535. GL_DST_COLOR,
  536. GL_ONE_MINUS_DST_COLOR,
  537. GL_SRC_ALPHA_SATURATE,
  538. };
  539. static const GLenum s_depthFunc[] =
  540. {
  541. 0, // ignored
  542. GL_LESS,
  543. GL_LEQUAL,
  544. GL_EQUAL,
  545. GL_GEQUAL,
  546. GL_GREATER,
  547. GL_NOTEQUAL,
  548. GL_NEVER,
  549. GL_ALWAYS,
  550. };
  551. // Specifies the internal format of the texture.
  552. // Must be one of the following symbolic constants:
  553. // GL_ALPHA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA.
  554. static const GLenum s_colorFormat[] =
  555. {
  556. 0, // ignored
  557. GL_RGBA,
  558. GL_RGBA,
  559. };
  560. static const GLenum s_depthFormat[] =
  561. {
  562. 0, // ignored
  563. 0,
  564. };
  565. static const GLenum s_textureAddress[] =
  566. {
  567. GL_REPEAT,
  568. GL_MIRRORED_REPEAT,
  569. GL_CLAMP_TO_EDGE,
  570. };
  571. static const GLenum s_textureFilter[] =
  572. {
  573. GL_LINEAR,
  574. GL_NEAREST,
  575. };
  576. struct TextureFormatInfo
  577. {
  578. GLenum m_internalFmt;
  579. GLenum m_format;
  580. GLenum m_type;
  581. uint8_t m_bpp;
  582. };
  583. static const TextureFormatInfo s_textureFormat[TextureFormat::Count] =
  584. {
  585. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, GL_ZERO, 1 },
  586. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, GL_ZERO, 1 },
  587. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, GL_ZERO, 1 },
  588. { GL_ZERO, GL_ZERO, GL_ZERO, 0 },
  589. { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1 },
  590. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 4 },
  591. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 4 },
  592. #if BGFX_CONFIG_RENDERER_OPENGL
  593. { GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT, 8 },
  594. #else
  595. { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 8 },
  596. #endif // BGFX_CONFIG_RENDERER_OPENGL
  597. };
  598. const char* glslTypeName(GLuint _type)
  599. {
  600. #define GLSL_TYPE(_ty) case _ty: return #_ty
  601. switch (_type)
  602. {
  603. GLSL_TYPE(GL_FLOAT);
  604. GLSL_TYPE(GL_FLOAT_VEC2);
  605. GLSL_TYPE(GL_FLOAT_VEC3);
  606. GLSL_TYPE(GL_FLOAT_VEC4);
  607. GLSL_TYPE(GL_FLOAT_MAT2);
  608. GLSL_TYPE(GL_FLOAT_MAT3);
  609. GLSL_TYPE(GL_FLOAT_MAT4);
  610. // GLSL_TYPE(GL_FLOAT_MAT2x3);
  611. // GLSL_TYPE(GL_FLOAT_MAT2x4);
  612. // GLSL_TYPE(GL_FLOAT_MAT3x2);
  613. // GLSL_TYPE(GL_FLOAT_MAT3x4);
  614. // GLSL_TYPE(GL_FLOAT_MAT4x2);
  615. // GLSL_TYPE(GL_FLOAT_MAT4x3);
  616. // GLSL_TYPE(GL_SAMPLER_1D);
  617. GLSL_TYPE(GL_SAMPLER_2D);
  618. // GLSL_TYPE(GL_SAMPLER_3D);
  619. GLSL_TYPE(GL_SAMPLER_CUBE);
  620. // GLSL_TYPE(GL_SAMPLER_1D_SHADOW);
  621. // GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  622. }
  623. #undef GLSL_TYPE
  624. return "UNKNOWN GLSL TYPE!";
  625. }
  626. const char* glEnumName(GLenum _enum)
  627. {
  628. #define GLENUM(_ty) case _ty: return #_ty
  629. switch (_enum)
  630. {
  631. GLENUM(GL_TEXTURE);
  632. GLENUM(GL_RENDERBUFFER);
  633. }
  634. #undef GLENUM
  635. return "UNKNOWN GLENUM!";
  636. }
  637. ConstantType::Enum convertGlType(GLenum _type)
  638. {
  639. switch (_type)
  640. {
  641. case GL_FLOAT:
  642. return ConstantType::Uniform1fv;
  643. case GL_FLOAT_VEC2:
  644. return ConstantType::Uniform2fv;
  645. case GL_FLOAT_VEC3:
  646. return ConstantType::Uniform3fv;
  647. case GL_FLOAT_VEC4:
  648. return ConstantType::Uniform4fv;
  649. case GL_FLOAT_MAT2:
  650. break;
  651. case GL_FLOAT_MAT3:
  652. return ConstantType::Uniform3x3fv;
  653. case GL_FLOAT_MAT4:
  654. return ConstantType::Uniform4x4fv;
  655. // case GL_FLOAT_MAT2x3:
  656. // case GL_FLOAT_MAT2x4:
  657. // case GL_FLOAT_MAT3x2:
  658. // case GL_FLOAT_MAT3x4:
  659. // case GL_FLOAT_MAT4x2:
  660. // case GL_FLOAT_MAT4x3:
  661. // break;
  662. case GL_SAMPLER_2D:
  663. case GL_SAMPLER_CUBE:
  664. // case GL_SAMPLER_1D:
  665. // case GL_SAMPLER_3D:
  666. // case GL_SAMPLER_1D_SHADOW:
  667. // case GL_SAMPLER_2D_SHADOW:
  668. return ConstantType::Uniform1iv;
  669. };
  670. return ConstantType::End;
  671. }
  672. void Material::create(const Shader& _vsh, const Shader& _fsh)
  673. {
  674. m_id = glCreateProgram();
  675. BX_TRACE("material create: %d: %d, %d", m_id, _vsh.m_id, _fsh.m_id);
  676. bool cached = false;
  677. #if BGFX_CONFIG_RENDERER_OPENGL
  678. uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  679. id ^= s_renderCtx.m_hash;
  680. if (s_extension[Extension::ARB_get_program_binary].m_supported)
  681. {
  682. uint32_t length;
  683. g_cache(id, false, NULL, length);
  684. cached = length > 0;
  685. if (cached)
  686. {
  687. void* data = g_realloc(NULL, length);
  688. g_cache(id, false, data, length);
  689. StreamRead stream(data, length);
  690. GLenum format;
  691. stream.read(format);
  692. GL_CHECK(glProgramBinary(m_id, format, stream.getDataPtr(), stream.remaining() ) );
  693. g_free(data);
  694. }
  695. else
  696. {
  697. GL_CHECK(glProgramParameteri(m_id, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  698. }
  699. }
  700. #endif // BGFX_CONFIG_RENDERER_OPENGL
  701. if (!cached)
  702. {
  703. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  704. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  705. GL_CHECK(glLinkProgram(m_id) );
  706. GLint linked = 0;
  707. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  708. if (0 == linked)
  709. {
  710. char log[1024];
  711. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  712. BX_TRACE("%d: %s", linked, log);
  713. GL_CHECK(glDeleteProgram(m_id) );
  714. return;
  715. }
  716. #if BGFX_CONFIG_RENDERER_OPENGL
  717. if (s_extension[Extension::ARB_get_program_binary].m_supported)
  718. {
  719. GLint programLength;
  720. GLenum format;
  721. GL_CHECK(glGetProgramiv(m_id, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  722. uint32_t length = programLength + 4;
  723. uint8_t* data = (uint8_t*)g_realloc(NULL, length);
  724. GL_CHECK(glGetProgramBinary(m_id, programLength, NULL, &format, &data[4]) );
  725. *(uint32_t*)data = format;
  726. g_cache(id, true, data, length);
  727. g_free(data);
  728. }
  729. #endif // BGFX_CONFIG_RENDERER_OPENGL
  730. }
  731. init();
  732. }
  733. void Material::destroy()
  734. {
  735. GL_CHECK(glUseProgram(0) );
  736. GL_CHECK(glDeleteProgram(m_id) );
  737. }
  738. void Material::init()
  739. {
  740. GLint activeAttribs;
  741. GLint activeUniforms;
  742. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs) );
  743. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  744. GLint max0, max1;
  745. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  746. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  747. GLint maxLength = uint32_max(max0, max1);
  748. char* name = (char*)g_realloc(NULL, maxLength + 1);
  749. BX_TRACE("Program %d", m_id);
  750. BX_TRACE("Attributes:");
  751. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  752. {
  753. GLint size;
  754. GLenum type;
  755. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  756. BX_TRACE("\t%s %s is at location %d"
  757. , glslTypeName(type)
  758. , name
  759. , glGetAttribLocation(m_id, name)
  760. );
  761. }
  762. m_numPredefined = 0;
  763. m_constantBuffer = ConstantBuffer::create(1024);
  764. m_numSamplers = 0;
  765. BX_TRACE("Uniforms:");
  766. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  767. {
  768. GLint num;
  769. GLenum gltype;
  770. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  771. GLint loc = glGetUniformLocation(m_id, name);
  772. int offset = 0;
  773. char* array = strchr(name, '[');
  774. if (NULL != array)
  775. {
  776. BX_TRACE("--- %s", name);
  777. *array = '\0';
  778. array++;
  779. char* end = strchr(array, ']');
  780. *end = '\0';
  781. offset = atoi(array);
  782. }
  783. if (GL_SAMPLER_2D == gltype)
  784. {
  785. BX_TRACE("Sampler %d at %d.", m_numSamplers, loc);
  786. m_sampler[m_numSamplers] = loc;
  787. m_numSamplers++;
  788. }
  789. const void* data = NULL;
  790. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  791. if (PredefinedUniform::Count != predefined)
  792. {
  793. m_predefined[m_numPredefined].m_loc = loc;
  794. m_predefined[m_numPredefined].m_type = predefined;
  795. m_predefined[m_numPredefined].m_count = num;
  796. m_numPredefined++;
  797. }
  798. else
  799. {
  800. const UniformInfo* info = s_renderCtx.m_uniformReg.find(name);
  801. if (NULL != info)
  802. {
  803. data = info->m_data;
  804. ConstantType::Enum type = convertGlType(gltype);
  805. m_constantBuffer->writeUniformRef(type, loc, data, num);
  806. BX_TRACE("store %s %p", name, data);
  807. }
  808. }
  809. BX_TRACE("\tuniform %s %s%s is at location %d, size %d (%p), offset %d"
  810. , glslTypeName(gltype)
  811. , name
  812. , PredefinedUniform::Count != predefined ? "*" : ""
  813. , loc
  814. , num
  815. , data
  816. , offset
  817. );
  818. }
  819. m_constantBuffer->finish();
  820. g_free(name);
  821. memset(m_attributes, 0xff, sizeof(m_attributes) );
  822. uint32_t used = 0;
  823. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  824. {
  825. GLuint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  826. if ( GLuint(-1) != loc )
  827. {
  828. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  829. m_attributes[ii] = loc;
  830. m_used[used++] = ii;
  831. }
  832. }
  833. m_used[used] = Attrib::Count;
  834. }
  835. void Material::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex)
  836. {
  837. uint32_t enabled = 0;
  838. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  839. {
  840. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  841. GLuint loc = m_attributes[attr];
  842. uint8_t num;
  843. AttribType::Enum type;
  844. bool normalized;
  845. _vertexDecl.decode(attr, num, type, normalized);
  846. if (0xffff != loc
  847. && 0xff != _vertexDecl.m_attributes[attr])
  848. {
  849. GL_CHECK(glEnableVertexAttribArray(loc) );
  850. enabled |= 1<<attr;
  851. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  852. GL_CHECK(glVertexAttribPointer(loc, num, s_attribType[type], normalized, _vertexDecl.m_stride, (void*)(uintptr_t)baseVertex) );
  853. }
  854. else
  855. {
  856. GL_CHECK(glDisableVertexAttribArray(loc) );
  857. switch (num)
  858. {
  859. case 1:
  860. GL_CHECK(glVertexAttrib1f(loc, 0.0f) );
  861. break;
  862. case 2:
  863. GL_CHECK(glVertexAttrib2f(loc, 0.0f, 0.0f) );
  864. break;
  865. case 3:
  866. GL_CHECK(glVertexAttrib3f(loc, 0.0f, 0.0f, 0.0f) );
  867. break;
  868. case 4:
  869. GL_CHECK(glVertexAttrib4f(loc, 0.0f, 0.0f, 0.0f, 0.0f) );
  870. break;
  871. default:
  872. BX_CHECK(false, "You should not be here!");
  873. break;
  874. }
  875. }
  876. }
  877. //
  878. // uint32_t changed = enabled^m_enabled;
  879. // m_enabled = enabled;
  880. //
  881. // if (0 != changed)
  882. // {
  883. // uint32_t test = 1;
  884. // for (uint32_t attr = 0; attr != Attrib::Count; ++attr)
  885. // {
  886. // if ( (changed & test)
  887. // && !(enabled & test) )
  888. // {
  889. // GLuint loc = m_attributes[attr];
  890. // GL_CHECK(glDisableVertexAttribArray(loc) );
  891. // }
  892. //
  893. // test <<= 1;
  894. // }
  895. // }
  896. }
  897. void Texture::create(const Memory* _mem, uint32_t _flags)
  898. {
  899. Dds dds;
  900. uint8_t numMips = 0;
  901. if (parseDds(dds, _mem) )
  902. {
  903. numMips = dds.m_numMips;
  904. if (dds.m_cubeMap)
  905. {
  906. m_target = GL_TEXTURE_CUBE_MAP;
  907. }
  908. #if BGFX_CONFIG_RENDERER_OPENGL
  909. else if (dds.m_depth > 1)
  910. {
  911. m_target = GL_TEXTURE_3D;
  912. }
  913. #endif // BGFX_CONFIG_RENDERER_OPENGL
  914. else
  915. {
  916. m_target = GL_TEXTURE_2D;
  917. }
  918. GL_CHECK(glGenTextures(1, &m_id) );
  919. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  920. GL_CHECK(glBindTexture(m_target, m_id) );
  921. const TextureFormatInfo& tfi = s_textureFormat[dds.m_type];
  922. GLenum internalFmt = tfi.m_internalFmt;
  923. GLenum fmt = tfi.m_format;
  924. GLenum target = m_target;
  925. if (dds.m_cubeMap)
  926. {
  927. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  928. }
  929. if (!s_renderCtx.m_dxtSupport
  930. || TextureFormat::Unknown < dds.m_type)
  931. {
  932. if (GL_RGBA == internalFmt)
  933. {
  934. internalFmt = s_extension[Extension::EXT_texture_format_BGRA8888].m_supported ? GL_BGRA_EXT : GL_RGBA;
  935. fmt = internalFmt;
  936. }
  937. uint8_t* bits = (uint8_t*)g_realloc(NULL, dds.m_width*dds.m_height*tfi.m_bpp);
  938. for (uint8_t side = 0, numSides = dds.m_cubeMap ? 6 : 1; side < numSides; ++side)
  939. {
  940. uint32_t width = dds.m_width;
  941. uint32_t height = dds.m_height;
  942. uint32_t depth = dds.m_depth;
  943. for (uint32_t lod = 0, num = dds.m_numMips; lod < num; ++lod)
  944. {
  945. width = uint32_max(1, width);
  946. height = uint32_max(1, height);
  947. depth = uint32_max(1, depth);
  948. Mip mip;
  949. if (getRawImageData(dds, 0, lod, _mem, mip) )
  950. {
  951. mip.decode(bits);
  952. if (GL_RGBA == internalFmt)
  953. {
  954. uint32_t dstpitch = width*4;
  955. for (uint32_t yy = 0; yy < height; ++yy)
  956. {
  957. uint8_t* dst = &bits[yy*dstpitch];
  958. for (uint32_t xx = 0; xx < width; ++xx)
  959. {
  960. uint8_t tmp = dst[0];
  961. dst[0] = dst[2];
  962. dst[2] = tmp;
  963. dst += 4;
  964. }
  965. }
  966. }
  967. #if BGFX_CONFIG_RENDERER_OPENGL
  968. if (target == GL_TEXTURE_3D)
  969. {
  970. GL_CHECK(glTexImage3D(target
  971. , lod
  972. , internalFmt
  973. , width
  974. , height
  975. , depth
  976. , 0
  977. , fmt
  978. , tfi.m_type
  979. , bits
  980. ) );
  981. }
  982. else
  983. #endif // BGFX_CONFIG_RENDERER_OPENGL
  984. {
  985. GL_CHECK(glTexImage2D(target+side
  986. , lod
  987. , internalFmt
  988. , width
  989. , height
  990. , 0
  991. , fmt
  992. , tfi.m_type
  993. , bits
  994. ) );
  995. }
  996. }
  997. width >>= 1;
  998. height >>= 1;
  999. depth >>= 1;
  1000. }
  1001. }
  1002. g_free(bits);
  1003. }
  1004. else
  1005. {
  1006. for (uint8_t side = 0, numSides = dds.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1007. {
  1008. uint32_t width = dds.m_width;
  1009. uint32_t height = dds.m_height;
  1010. uint32_t depth = dds.m_depth;
  1011. for (uint32_t ii = 0, num = dds.m_numMips; ii < num; ++ii)
  1012. {
  1013. width = uint32_max(1, width);
  1014. height = uint32_max(1, height);
  1015. depth = uint32_max(1, depth);
  1016. Mip mip;
  1017. if (getRawImageData(dds, 0, ii, _mem, mip) )
  1018. {
  1019. #if BGFX_CONFIG_RENDERER_OPENGL
  1020. if (m_target == GL_TEXTURE_3D)
  1021. {
  1022. GL_CHECK(glCompressedTexImage3D(target
  1023. , ii
  1024. , internalFmt
  1025. , width
  1026. , height
  1027. , depth
  1028. , 0
  1029. , mip.m_size
  1030. , mip.m_data
  1031. ) );
  1032. }
  1033. else
  1034. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1035. {
  1036. GL_CHECK(glCompressedTexImage2D(target+side
  1037. , ii
  1038. , internalFmt
  1039. , width
  1040. , height
  1041. , 0
  1042. , mip.m_size
  1043. , mip.m_data
  1044. ) );
  1045. }
  1046. }
  1047. width >>= 1;
  1048. height >>= 1;
  1049. depth >>= 1;
  1050. }
  1051. }
  1052. }
  1053. }
  1054. else
  1055. {
  1056. m_target = GL_TEXTURE_2D;
  1057. GL_CHECK(glGenTextures(1, &m_id) );
  1058. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1059. GL_CHECK(glBindTexture(m_target, m_id) );
  1060. StreamRead stream(_mem->data, _mem->size);
  1061. uint32_t magic;
  1062. stream.read(magic);
  1063. if (BGFX_MAGIC == magic)
  1064. {
  1065. uint16_t width;
  1066. stream.read(width);
  1067. uint16_t height;
  1068. stream.read(height);
  1069. uint8_t bpp;
  1070. stream.read(bpp);
  1071. stream.read(numMips);
  1072. stream.align(16);
  1073. for (uint8_t mip = 0; mip < numMips; ++mip)
  1074. {
  1075. width = uint32_max(width, 1);
  1076. height = uint32_max(height, 1);
  1077. const uint8_t* data = stream.getDataPtr();
  1078. stream.skip(width*height*bpp);
  1079. GL_CHECK(glTexImage2D(m_target
  1080. , mip
  1081. , 1 == bpp ? GL_LUMINANCE : GL_RGBA
  1082. , width
  1083. , height
  1084. , 0
  1085. , 1 == bpp ? GL_LUMINANCE : GL_RGBA
  1086. , GL_UNSIGNED_BYTE
  1087. , data
  1088. ) );
  1089. width >>= 1;
  1090. height >>= 1;
  1091. }
  1092. }
  1093. else
  1094. {
  1095. //
  1096. }
  1097. }
  1098. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  1099. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  1100. #if BGFX_CONFIG_RENDERER_OPENGL
  1101. if (m_target == GL_TEXTURE_3D)
  1102. {
  1103. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_R, s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  1104. }
  1105. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1106. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, s_textureFilter[(_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT]) );
  1107. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, s_textureFilter[(_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT]) );
  1108. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, 1 < numMips ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR) );
  1109. GL_CHECK(glBindTexture(m_target, 0) );
  1110. }
  1111. void Texture::createColor(uint32_t _width, uint32_t _height, GLenum _min, GLenum _mag)
  1112. {
  1113. GLenum internalFormat = /*_fp ? GL_RGBA16F_ARB :*/ GL_RGBA;
  1114. GLenum type = /*_fp ? GL_HALF_FLOAT_ARB :*/ GL_UNSIGNED_BYTE;
  1115. m_target = /*0 != _depth ? GL_TEXTURE_3D :*/ GL_TEXTURE_2D;
  1116. GL_CHECK(glGenTextures(1, &m_id) );
  1117. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1118. GL_CHECK(glBindTexture(m_target, m_id) );
  1119. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, _min) );
  1120. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, _mag) );
  1121. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  1122. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  1123. GL_CHECK(glTexImage2D(m_target
  1124. , 0
  1125. , internalFormat
  1126. , _width
  1127. , _height
  1128. , 0
  1129. , GL_RGBA
  1130. , type
  1131. , NULL
  1132. ) );
  1133. GL_CHECK(glBindTexture(m_target, 0) );
  1134. }
  1135. void Texture::createDepth(uint32_t _width, uint32_t _height)
  1136. {
  1137. m_target = GL_TEXTURE_2D;
  1138. GL_CHECK(glGenTextures(1, &m_id) );
  1139. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  1140. GL_CHECK(glBindTexture(m_target, m_id) );
  1141. // glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  1142. // glTexParameteri(m_target, GL_DEPTH_TEXTURE_MODE, GL_NONE);
  1143. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  1144. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  1145. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  1146. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  1147. // OpenGL ES 2.0 doesn't support GL_DEPTH_COMPONENT... this will fail.
  1148. GL_CHECK(glTexImage2D(m_target
  1149. , 0
  1150. , GL_DEPTH_COMPONENT
  1151. , _width
  1152. , _height
  1153. , 0
  1154. , GL_DEPTH_COMPONENT
  1155. , GL_FLOAT
  1156. , NULL
  1157. ) );
  1158. GL_CHECK(glBindTexture(m_target, 0) );
  1159. }
  1160. void Texture::destroy()
  1161. {
  1162. if (0 != m_id)
  1163. {
  1164. GL_CHECK(glBindTexture(m_target, 0) );
  1165. GL_CHECK(glDeleteTextures(1, &m_id) );
  1166. m_id = 0;
  1167. }
  1168. }
  1169. void RenderTarget::create(uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1170. {
  1171. BX_TRACE("Create render target %dx%d 0x%02x", _width, _height, _flags);
  1172. m_width = _width;
  1173. m_height = _height;
  1174. // m_msaa = s_msaa[(m_flags&BGFX_RENDER_TARGET_MSAA_MASK)>>BGFX_RENDER_TARGET_MSAA_SHIFT];
  1175. uint32_t colorFormat = (_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1176. uint32_t depthFormat = (_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1177. GLenum minFilter = s_textureFilter[(_textureFlags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT];
  1178. GLenum magFilter = s_textureFilter[(_textureFlags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  1179. if (0 < colorFormat)
  1180. {
  1181. m_color.createColor(_width, _height, minFilter, magFilter);
  1182. }
  1183. #if 0 // GLES can't create texture with depth texture format...
  1184. if (0 < depthFormat)
  1185. {
  1186. m_depth.createDepth(_width, _height);
  1187. }
  1188. #endif //
  1189. GL_CHECK(glGenFramebuffers(1, &m_fbo) );
  1190. BX_CHECK(0 != m_fbo, "Failed to generate framebuffer id.");
  1191. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo) );
  1192. if (0 < colorFormat)
  1193. {
  1194. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1195. , GL_COLOR_ATTACHMENT0
  1196. , m_color.m_target
  1197. , m_color.m_id
  1198. , 0
  1199. ) );
  1200. }
  1201. if (0 < depthFormat)
  1202. {
  1203. if (0 < colorFormat)
  1204. {
  1205. #if BGFX_CONFIG_RENDERER_OPENGL
  1206. GLenum depthComponent = GL_DEPTH_COMPONENT32;
  1207. #else
  1208. GLenum depthComponent = GL_DEPTH_COMPONENT16;
  1209. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1210. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  1211. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  1212. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  1213. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, depthComponent, _width, _height) );
  1214. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  1215. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  1216. , GL_DEPTH_ATTACHMENT
  1217. , GL_RENDERBUFFER
  1218. , m_rbo
  1219. ) );
  1220. }
  1221. else
  1222. {
  1223. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  1224. , GL_DEPTH_ATTACHMENT
  1225. , m_depth.m_target
  1226. , m_depth.m_id
  1227. , 0
  1228. ) );
  1229. }
  1230. }
  1231. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1232. , "glCheckFramebufferStatus failed 0x%08x"
  1233. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1234. );
  1235. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1236. }
  1237. void RenderTarget::destroy()
  1238. {
  1239. GL_CHECK(glDeleteFramebuffers(1, &m_fbo) );
  1240. if (0 != m_rbo)
  1241. {
  1242. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  1243. }
  1244. m_color.destroy();
  1245. m_depth.destroy();
  1246. }
  1247. void ConstantBuffer::commit(bool _force)
  1248. {
  1249. reset();
  1250. do
  1251. {
  1252. uint32_t opcode = read();
  1253. if (ConstantType::End == opcode)
  1254. {
  1255. break;
  1256. }
  1257. ConstantType::Enum type;
  1258. uint16_t loc;
  1259. uint16_t num;
  1260. uint16_t copy;
  1261. decodeOpcode(opcode, type, loc, num, copy);
  1262. const char* data;
  1263. if (copy)
  1264. {
  1265. data = read(g_constantTypeSize[type]*num);
  1266. }
  1267. else
  1268. {
  1269. memcpy(&data, read(sizeof(void*) ), sizeof(void*) );
  1270. }
  1271. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  1272. case ConstantType::_uniform: \
  1273. { \
  1274. _type* value = (_type*)data; \
  1275. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  1276. } \
  1277. break;
  1278. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  1279. case ConstantType::_uniform: \
  1280. { \
  1281. _type* value = (_type*)data; \
  1282. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  1283. } \
  1284. break;
  1285. switch (type)
  1286. {
  1287. // case ConstantType::Uniform1iv:
  1288. // {
  1289. // int* value = (int*)data;
  1290. // BX_TRACE("Uniform1iv sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  1291. // GL_CHECK(glUniform1iv(loc, num, value) );
  1292. // }
  1293. // break;
  1294. //
  1295. CASE_IMPLEMENT_UNIFORM(Uniform1i, 1iv, I, int);
  1296. CASE_IMPLEMENT_UNIFORM(Uniform1f, 1fv, F, float);
  1297. CASE_IMPLEMENT_UNIFORM(Uniform1iv, 1iv, I, int);
  1298. CASE_IMPLEMENT_UNIFORM(Uniform1fv, 1fv, F, float);
  1299. CASE_IMPLEMENT_UNIFORM(Uniform2fv, 2fv, F, float);
  1300. CASE_IMPLEMENT_UNIFORM(Uniform3fv, 3fv, F, float);
  1301. CASE_IMPLEMENT_UNIFORM(Uniform4fv, 4fv, F, float);
  1302. CASE_IMPLEMENT_UNIFORM_T(Uniform3x3fv, Matrix3fv, F, float);
  1303. CASE_IMPLEMENT_UNIFORM_T(Uniform4x4fv, Matrix4fv, F, float);
  1304. case ConstantType::End:
  1305. break;
  1306. default:
  1307. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", m_pos, opcode, type, loc, num, copy);
  1308. break;
  1309. }
  1310. #undef CASE_IMPLEMENT_UNIFORM
  1311. #undef CASE_IMPLEMENT_UNIFORM_T
  1312. } while (true);
  1313. }
  1314. void TextVideoMemBlitter::setup()
  1315. {
  1316. uint32_t width = s_renderCtx.m_resolution.m_width;
  1317. uint32_t height = s_renderCtx.m_resolution.m_height;
  1318. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1319. GL_CHECK(glViewport(0, 0, width, height) );
  1320. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1321. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1322. GL_CHECK(glDisable(GL_CULL_FACE) );
  1323. GL_CHECK(glDisable(GL_BLEND) );
  1324. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1325. #if BGFX_CONFIG_RENDERER_OPENGL
  1326. GL_CHECK(glDisable(GL_ALPHA_TEST) );
  1327. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1328. Material& material = s_renderCtx.m_materials[m_material.idx];
  1329. GL_CHECK(glUseProgram(material.m_id) );
  1330. GL_CHECK(glUniform1i(material.m_sampler[0], 0) );
  1331. float proj[16];
  1332. matrix_ortho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1333. GL_CHECK(glUniformMatrix4fv(material.m_predefined[0].m_loc
  1334. , 1
  1335. , GL_FALSE
  1336. , proj
  1337. ) );
  1338. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1339. GL_CHECK(glBindTexture(GL_TEXTURE_2D, s_renderCtx.m_textures[m_texture.idx].m_id) );
  1340. }
  1341. void TextVideoMemBlitter::render(uint32_t _numIndices)
  1342. {
  1343. uint32_t numVertices = _numIndices*4/6;
  1344. s_renderCtx.m_indexBuffers[m_ib->handle.idx].update(0, _numIndices*2, m_ib->data);
  1345. s_renderCtx.m_vertexBuffers[m_vb->handle.idx].update(0, numVertices*m_decl.m_stride, m_vb->data);
  1346. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[m_vb->handle.idx];
  1347. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1348. IndexBuffer& ib = s_renderCtx.m_indexBuffers[m_ib->handle.idx];
  1349. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1350. Material& material = s_renderCtx.m_materials[m_material.idx];
  1351. material.bindAttributes(m_decl, 0);
  1352. GL_CHECK(glDrawElements(GL_TRIANGLES
  1353. , _numIndices
  1354. , GL_UNSIGNED_SHORT
  1355. , (void*)0
  1356. ) );
  1357. }
  1358. void Context::flip()
  1359. {
  1360. s_renderCtx.flip();
  1361. }
  1362. GLint glGet(GLenum _pname)
  1363. {
  1364. GLint result;
  1365. GL_CHECK(glGetIntegerv(_pname, &result) );
  1366. return result;
  1367. }
  1368. void Context::rendererInit()
  1369. {
  1370. s_renderCtx.init();
  1371. #if BGFX_CONFIG_DEBUG
  1372. GLint numCmpFormats;
  1373. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1374. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1375. GLint* formats = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1376. glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats);
  1377. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1378. {
  1379. BX_TRACE("\t%3d: %8x", ii, formats[ii]);
  1380. }
  1381. # define GL_GET(_pname, _min) BX_TRACE(#_pname " %d (min: %d)", glGet(_pname), _min)
  1382. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1383. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1384. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1385. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1386. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1387. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1388. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1389. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1390. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1391. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1392. #endif // BGFX_CONFIG_DEBUG
  1393. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1394. char name[1024];
  1395. const char* pos = extensions;
  1396. const char* end = extensions + strlen(extensions);
  1397. while (pos < end)
  1398. {
  1399. uint32_t len;
  1400. const char* space = strchr(pos, ' ');
  1401. if (NULL != space)
  1402. {
  1403. len = uint32_min(sizeof(name), (uint32_t)(space - pos) );
  1404. }
  1405. else
  1406. {
  1407. len = uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  1408. }
  1409. strncpy(name, pos, len);
  1410. name[len] = '\0';
  1411. bool supported = false;
  1412. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1413. {
  1414. Extension& extension = s_extension[ii];
  1415. if (!extension.m_supported
  1416. && extension.m_initialize)
  1417. {
  1418. if (0 == strcmp(name, extension.m_name) )
  1419. {
  1420. extension.m_supported = true;
  1421. supported = true;
  1422. break;
  1423. }
  1424. }
  1425. }
  1426. BX_TRACE("GL_EXTENSION%s: %s", supported ? " (supported)" : "", name);
  1427. pos += len+1;
  1428. }
  1429. BX_TRACE("Supported extensions:");
  1430. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1431. {
  1432. if (s_extension[ii].m_supported)
  1433. {
  1434. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1435. }
  1436. }
  1437. s_renderCtx.m_dxtSupport = true
  1438. && s_extension[Extension::EXT_texture_compression_dxt1].m_supported
  1439. && s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1440. && s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1441. ;
  1442. s_renderCtx.m_dxtSupport |=
  1443. s_extension[Extension::EXT_texture_compression_s3tc].m_supported
  1444. ;
  1445. }
  1446. void Context::rendererShutdown()
  1447. {
  1448. s_renderCtx.shutdown();
  1449. }
  1450. void Context::rendererCreateIndexBuffer(IndexBufferHandle _handle, Memory* _mem)
  1451. {
  1452. s_renderCtx.m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  1453. }
  1454. void Context::rendererDestroyIndexBuffer(IndexBufferHandle _handle)
  1455. {
  1456. s_renderCtx.m_indexBuffers[_handle.idx].destroy();
  1457. }
  1458. void Context::rendererCreateVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl)
  1459. {
  1460. VertexDecl& decl = s_renderCtx.m_vertexDecls[_handle.idx];
  1461. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  1462. dump(decl);
  1463. }
  1464. void Context::rendererDestroyVertexDecl(VertexDeclHandle _handle)
  1465. {
  1466. }
  1467. void Context::rendererCreateVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle)
  1468. {
  1469. s_renderCtx.m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  1470. }
  1471. void Context::rendererDestroyVertexBuffer(VertexBufferHandle _handle)
  1472. {
  1473. s_renderCtx.m_vertexBuffers[_handle.idx].destroy();
  1474. }
  1475. void Context::rendererCreateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size)
  1476. {
  1477. s_renderCtx.m_indexBuffers[_handle.idx].create(_size, NULL);
  1478. }
  1479. void Context::rendererUpdateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  1480. {
  1481. s_renderCtx.m_indexBuffers[_handle.idx].update(_offset, uint32_min(_size, _mem->size), _mem->data);
  1482. }
  1483. void Context::rendererDestroyDynamicIndexBuffer(IndexBufferHandle _handle)
  1484. {
  1485. s_renderCtx.m_indexBuffers[_handle.idx].destroy();
  1486. }
  1487. void Context::rendererCreateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size)
  1488. {
  1489. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1490. s_renderCtx.m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  1491. }
  1492. void Context::rendererUpdateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  1493. {
  1494. s_renderCtx.m_vertexBuffers[_handle.idx].update(_offset, uint32_min(_size, _mem->size), _mem->data);
  1495. }
  1496. void Context::rendererDestroyDynamicVertexBuffer(VertexBufferHandle _handle)
  1497. {
  1498. s_renderCtx.m_vertexBuffers[_handle.idx].destroy();
  1499. }
  1500. void Context::rendererCreateVertexShader(VertexShaderHandle _handle, Memory* _mem)
  1501. {
  1502. s_renderCtx.m_vertexShaders[_handle.idx].create(GL_VERTEX_SHADER, _mem->data);
  1503. }
  1504. void Context::rendererDestroyVertexShader(VertexShaderHandle _handle)
  1505. {
  1506. s_renderCtx.m_vertexShaders[_handle.idx].destroy();
  1507. }
  1508. void Context::rendererCreateFragmentShader(FragmentShaderHandle _handle, Memory* _mem)
  1509. {
  1510. s_renderCtx.m_fragmentShaders[_handle.idx].create(GL_FRAGMENT_SHADER, _mem->data);
  1511. }
  1512. void Context::rendererDestroyFragmentShader(FragmentShaderHandle _handle)
  1513. {
  1514. s_renderCtx.m_fragmentShaders[_handle.idx].destroy();
  1515. }
  1516. void Context::rendererCreateMaterial(MaterialHandle _handle, VertexShaderHandle _vsh, FragmentShaderHandle _fsh)
  1517. {
  1518. s_renderCtx.m_materials[_handle.idx].create(s_renderCtx.m_vertexShaders[_vsh.idx], s_renderCtx.m_fragmentShaders[_fsh.idx]);
  1519. }
  1520. void Context::rendererDestroyMaterial(FragmentShaderHandle _handle)
  1521. {
  1522. s_renderCtx.m_materials[_handle.idx].destroy();
  1523. }
  1524. void Context::rendererCreateTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags)
  1525. {
  1526. s_renderCtx.m_textures[_handle.idx].create(_mem, _flags);
  1527. }
  1528. void Context::rendererDestroyTexture(TextureHandle _handle)
  1529. {
  1530. s_renderCtx.m_textures[_handle.idx].destroy();
  1531. }
  1532. void Context::rendererCreateRenderTarget(RenderTargetHandle _handle, uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1533. {
  1534. s_renderCtx.m_renderTargets[_handle.idx].create(_width, _height, _flags, _textureFlags);
  1535. }
  1536. void Context::rendererDestroyRenderTarget(RenderTargetHandle _handle)
  1537. {
  1538. s_renderCtx.m_renderTargets[_handle.idx].destroy();
  1539. }
  1540. void Context::rendererCreateUniform(UniformHandle _handle, ConstantType::Enum _type, uint16_t _num, const char* _name)
  1541. {
  1542. uint32_t size = g_constantTypeSize[_type]*_num;
  1543. void* data = g_realloc(NULL, size);
  1544. s_renderCtx.m_uniforms[_handle.idx] = data;
  1545. s_renderCtx.m_uniformReg.reg(_name, s_renderCtx.m_uniforms[_handle.idx]);
  1546. }
  1547. void Context::rendererDestroyUniform(UniformHandle _handle)
  1548. {
  1549. g_free(s_renderCtx.m_uniforms[_handle.idx]);
  1550. }
  1551. void Context::rendererSaveScreenShot(Memory* _mem)
  1552. {
  1553. s_renderCtx.saveScreenShot(_mem);
  1554. }
  1555. void Context::rendererUpdateUniform(uint16_t _loc, const void* _data, uint32_t _size)
  1556. {
  1557. memcpy(s_renderCtx.m_uniforms[_loc], _data, _size);
  1558. }
  1559. void Context::rendererSubmit()
  1560. {
  1561. s_renderCtx.updateResolution(m_render->m_resolution);
  1562. if (0 < m_render->m_iboffset)
  1563. {
  1564. TransientIndexBuffer* ib = m_render->m_transientIb;
  1565. s_renderCtx.m_indexBuffers[ib->handle.idx].update(0, m_render->m_iboffset, ib->data);
  1566. }
  1567. if (0 < m_render->m_vboffset)
  1568. {
  1569. TransientVertexBuffer* vb = m_render->m_transientVb;
  1570. s_renderCtx.m_vertexBuffers[vb->handle.idx].update(0, m_render->m_vboffset, vb->data);
  1571. }
  1572. m_render->sort();
  1573. RenderState currentState;
  1574. currentState.reset();
  1575. currentState.m_flags = BGFX_STATE_NONE;
  1576. Matrix4 viewProj[BGFX_CONFIG_MAX_VIEWS];
  1577. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1578. {
  1579. matrix_mul(viewProj[ii].val, m_render->m_view[ii].val, m_render->m_proj[ii].val);
  1580. }
  1581. uint16_t materialIdx = bgfx::invalidHandle;
  1582. SortKey key;
  1583. uint8_t view = 0xff;
  1584. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  1585. int32_t height = m_render->m_resolution.m_height;
  1586. float alphaRef = 0.0f;
  1587. GLenum primType = m_render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINES : GL_TRIANGLES;
  1588. uint32_t primNumVerts = 3;
  1589. uint32_t baseVertex = 0;
  1590. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1591. uint32_t statsNumPrims = 0;
  1592. uint32_t statsNumIndices = 0;
  1593. int64_t elapsed = -bx::getHPCounter();
  1594. if (0 == (m_render->m_debug&BGFX_DEBUG_IFH) )
  1595. {
  1596. for (uint32_t item = 0, numItems = m_render->m_num; item < numItems; ++item)
  1597. {
  1598. key.decode(m_render->m_sortKeys[item]);
  1599. const RenderState& state = m_render->m_renderState[m_render->m_sortValues[item] ];
  1600. const uint64_t newFlags = state.m_flags;
  1601. uint64_t changedFlags = currentState.m_flags ^ state.m_flags;
  1602. currentState.m_flags = newFlags;
  1603. if (key.m_view != view)
  1604. {
  1605. currentState.clear();
  1606. changedFlags = BGFX_STATE_MASK;
  1607. currentState.m_flags = newFlags;
  1608. GREMEDY_SETMARKER("view");
  1609. view = key.m_view;
  1610. materialIdx = bgfx::invalidHandle;
  1611. if (m_render->m_rt[view].idx != rt.idx)
  1612. {
  1613. rt = m_render->m_rt[view];
  1614. if (rt.idx == bgfx::invalidHandle)
  1615. {
  1616. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1617. height = m_render->m_resolution.m_height;
  1618. }
  1619. else
  1620. {
  1621. RenderTarget& renderTarget = s_renderCtx.m_renderTargets[rt.idx];
  1622. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, renderTarget.m_fbo) );
  1623. height = renderTarget.m_height;
  1624. }
  1625. }
  1626. Rect& rect = m_render->m_rect[view];
  1627. GL_CHECK(glViewport(rect.m_x, height-rect.m_height-rect.m_y, rect.m_width, rect.m_height) );
  1628. Clear& clear = m_render->m_clear[view];
  1629. if (BGFX_CLEAR_NONE != clear.m_flags)
  1630. {
  1631. GLuint flags = 0;
  1632. if (BGFX_CLEAR_COLOR_BIT & clear.m_flags)
  1633. {
  1634. flags |= GL_COLOR_BUFFER_BIT;
  1635. uint32_t rgba = clear.m_rgba;
  1636. float rr = (rgba>>24)/255.0f;
  1637. float gg = ( (rgba>>16)&0xff)/255.0f;
  1638. float bb = ( (rgba>>8)&0xff)/255.0f;
  1639. float aa = (rgba&0xff)/255.0f;
  1640. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  1641. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1642. }
  1643. if (BGFX_CLEAR_DEPTH_BIT & clear.m_flags)
  1644. {
  1645. flags |= GL_DEPTH_BUFFER_BIT;
  1646. GL_CHECK(glClearDepthf(clear.m_depth) );
  1647. GL_CHECK(glDepthMask(GL_TRUE) );
  1648. }
  1649. if (BGFX_CLEAR_STENCIL_BIT & clear.m_flags)
  1650. {
  1651. flags |= GL_STENCIL_BUFFER_BIT;
  1652. GL_CHECK(glClearStencil(clear.m_stencil) );
  1653. }
  1654. if (0 != flags)
  1655. {
  1656. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  1657. GL_CHECK(glScissor(rect.m_x, height-rect.m_height-rect.m_y, rect.m_width, rect.m_height) );
  1658. GL_CHECK(glClear(flags) );
  1659. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1660. }
  1661. }
  1662. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  1663. GL_CHECK(glDepthFunc(GL_LESS) );
  1664. GL_CHECK(glEnable(GL_CULL_FACE) );
  1665. GL_CHECK(glDisable(GL_BLEND) );
  1666. }
  1667. if ( (BGFX_STATE_CULL_MASK|BGFX_STATE_DEPTH_WRITE|BGFX_STATE_DEPTH_TEST_MASK
  1668. |BGFX_STATE_ALPHA_MASK|BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE
  1669. |BGFX_STATE_BLEND_MASK|BGFX_STATE_ALPHA_REF_MASK|BGFX_STATE_PT_MASK
  1670. |BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  1671. {
  1672. if (BGFX_STATE_CULL_MASK & changedFlags)
  1673. {
  1674. if (BGFX_STATE_CULL_CW & newFlags)
  1675. {
  1676. GL_CHECK(glEnable(GL_CULL_FACE) );
  1677. GL_CHECK(glCullFace(GL_BACK) );
  1678. }
  1679. else if (BGFX_STATE_CULL_CCW & newFlags)
  1680. {
  1681. GL_CHECK(glEnable(GL_CULL_FACE) );
  1682. GL_CHECK(glCullFace(GL_FRONT) );
  1683. }
  1684. else
  1685. {
  1686. GL_CHECK(glDisable(GL_CULL_FACE) );
  1687. }
  1688. }
  1689. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  1690. {
  1691. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  1692. }
  1693. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  1694. {
  1695. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  1696. if (0 != func)
  1697. {
  1698. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  1699. GL_CHECK(glDepthFunc(s_depthFunc[func]) );
  1700. }
  1701. else
  1702. {
  1703. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1704. }
  1705. }
  1706. if ( (BGFX_STATE_ALPHA_TEST|BGFX_STATE_ALPHA_REF_MASK) & changedFlags)
  1707. {
  1708. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  1709. alphaRef = ref/255.0f;
  1710. #if BGFX_CONFIG_RENDERER_OPENGL
  1711. if (BGFX_STATE_ALPHA_TEST & newFlags)
  1712. {
  1713. GL_CHECK(glEnable(GL_ALPHA_TEST) );
  1714. }
  1715. else
  1716. {
  1717. GL_CHECK(glDisable(GL_ALPHA_TEST) );
  1718. }
  1719. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1720. }
  1721. #if BGFX_CONFIG_RENDERER_OPENGL
  1722. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  1723. {
  1724. float pointSize = (float)(uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  1725. GL_CHECK(glPointSize(pointSize) );
  1726. }
  1727. #endif // BGFX_CONFIG_RENDERER_OPENGL
  1728. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  1729. {
  1730. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  1731. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  1732. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  1733. }
  1734. if (BGFX_STATE_BLEND_MASK & changedFlags)
  1735. {
  1736. if (BGFX_STATE_BLEND_MASK & newFlags)
  1737. {
  1738. uint32_t blend = (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT;
  1739. uint32_t src = blend&0xf;
  1740. uint32_t dst = (blend>>4)&0xf;
  1741. GL_CHECK(glEnable(GL_BLEND) );
  1742. GL_CHECK(glBlendFunc(s_blendFactor[src], s_blendFactor[dst]) );
  1743. }
  1744. else
  1745. {
  1746. GL_CHECK(glDisable(GL_BLEND) );
  1747. }
  1748. }
  1749. uint8_t primIndex = uint8_t( (newFlags&BGFX_STATE_PT_MASK)>>BGFX_STATE_PT_SHIFT);
  1750. primType = m_render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINES : s_primType[primIndex];
  1751. primNumVerts = s_primNumVerts[primIndex];
  1752. }
  1753. bool materialChanged = false;
  1754. bool constantsChanged = state.m_constBegin < state.m_constEnd;
  1755. bool bindAttribs = false;
  1756. rendererUpdateUniforms(m_render->m_constantBuffer, state.m_constBegin, state.m_constEnd);
  1757. if (key.m_material != materialIdx)
  1758. {
  1759. materialIdx = key.m_material;
  1760. GLuint id = bgfx::invalidHandle == materialIdx ? 0 : s_renderCtx.m_materials[materialIdx].m_id;
  1761. GL_CHECK(glUseProgram(id) );
  1762. materialChanged =
  1763. constantsChanged =
  1764. bindAttribs = true;
  1765. }
  1766. if (bgfx::invalidHandle != materialIdx)
  1767. {
  1768. Material& material = s_renderCtx.m_materials[materialIdx];
  1769. if (constantsChanged)
  1770. {
  1771. material.m_constantBuffer->commit(materialChanged);
  1772. }
  1773. for (uint32_t ii = 0, num = material.m_numPredefined; ii < num; ++ii)
  1774. {
  1775. PredefinedUniform& predefined = material.m_predefined[ii];
  1776. switch (predefined.m_type)
  1777. {
  1778. case PredefinedUniform::ViewRect:
  1779. {
  1780. float rect[4];
  1781. rect[0] = m_render->m_rect[view].m_x;
  1782. rect[1] = m_render->m_rect[view].m_y;
  1783. rect[2] = m_render->m_rect[view].m_width;
  1784. rect[3] = m_render->m_rect[view].m_height;
  1785. GL_CHECK(glUniform4fv(predefined.m_loc
  1786. , 1
  1787. , &rect[0]
  1788. ) );
  1789. }
  1790. break;
  1791. case PredefinedUniform::ViewTexel:
  1792. {
  1793. float rect[4];
  1794. rect[0] = 1.0f/float(m_render->m_rect[view].m_width);
  1795. rect[1] = 1.0f/float(m_render->m_rect[view].m_height);
  1796. GL_CHECK(glUniform4fv(predefined.m_loc
  1797. , 1
  1798. , &rect[0]
  1799. ) );
  1800. }
  1801. break;
  1802. case PredefinedUniform::View:
  1803. {
  1804. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  1805. , 1
  1806. , GL_FALSE
  1807. , m_render->m_view[view].val
  1808. ) );
  1809. }
  1810. break;
  1811. case PredefinedUniform::ViewProj:
  1812. {
  1813. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  1814. , 1
  1815. , GL_FALSE
  1816. , viewProj[view].val
  1817. ) );
  1818. }
  1819. break;
  1820. case PredefinedUniform::Model:
  1821. {
  1822. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  1823. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  1824. , uint32_min(predefined.m_count, state.m_num)
  1825. , GL_FALSE
  1826. , model.val
  1827. ) );
  1828. }
  1829. break;
  1830. case PredefinedUniform::ModelViewProj:
  1831. {
  1832. Matrix4 modelViewProj;
  1833. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  1834. matrix_mul(modelViewProj.val, model.val, viewProj[view].val);
  1835. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  1836. , 1
  1837. , GL_FALSE
  1838. , modelViewProj.val
  1839. ) );
  1840. }
  1841. break;
  1842. case PredefinedUniform::ModelViewProjX:
  1843. {
  1844. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  1845. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  1846. {
  1847. 0.5f, 0.0f, 0.0f, 0.0f,
  1848. 0.0f, 0.5f, 0.0f, 0.0f,
  1849. 0.0f, 0.0f, 0.5f, 0.0f,
  1850. 0.5f, 0.5f, 0.5f, 1.0f,
  1851. };
  1852. uint8_t other = m_render->m_other[view];
  1853. Matrix4 viewProjBias;
  1854. matrix_mul(viewProjBias.val, viewProj[other].val, s_bias);
  1855. Matrix4 modelViewProj;
  1856. matrix_mul(modelViewProj.val, model.val, viewProjBias.val);
  1857. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  1858. , 1
  1859. , GL_FALSE
  1860. , modelViewProj.val
  1861. ) );
  1862. }
  1863. break;
  1864. case PredefinedUniform::ViewProjX:
  1865. {
  1866. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  1867. {
  1868. 0.5f, 0.0f, 0.0f, 0.0f,
  1869. 0.0f, 0.5f, 0.0f, 0.0f,
  1870. 0.0f, 0.0f, 0.5f, 0.0f,
  1871. 0.5f, 0.5f, 0.5f, 1.0f,
  1872. };
  1873. uint8_t other = m_render->m_other[view];
  1874. Matrix4 viewProjBias;
  1875. matrix_mul(viewProjBias.val, viewProj[other].val, s_bias);
  1876. GL_CHECK(glUniformMatrix4fv(predefined.m_loc
  1877. , 1
  1878. , GL_FALSE
  1879. , viewProjBias.val
  1880. ) );
  1881. }
  1882. break;
  1883. case PredefinedUniform::AlphaRef:
  1884. {
  1885. GL_CHECK(glUniform1f(predefined.m_loc, alphaRef) );
  1886. }
  1887. break;
  1888. case PredefinedUniform::Count:
  1889. break;
  1890. }
  1891. }
  1892. // if (BGFX_STATE_TEX_MASK & changedFlags)
  1893. {
  1894. uint64_t flag = BGFX_STATE_TEX0;
  1895. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  1896. {
  1897. const Sampler& sampler = state.m_sampler[stage];
  1898. Sampler& current = currentState.m_sampler[stage];
  1899. if (current.m_idx != sampler.m_idx
  1900. || current.m_flags != sampler.m_flags
  1901. || materialChanged)
  1902. {
  1903. GL_CHECK(glActiveTexture(GL_TEXTURE0+stage) );
  1904. if (bgfx::invalidHandle != sampler.m_idx)
  1905. {
  1906. switch (sampler.m_flags&BGFX_SAMPLER_TYPE_MASK)
  1907. {
  1908. case BGFX_SAMPLER_TEXTURE:
  1909. {
  1910. const Texture& texture = s_renderCtx.m_textures[sampler.m_idx];
  1911. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  1912. }
  1913. break;
  1914. case BGFX_SAMPLER_RENDERTARGET_COLOR:
  1915. {
  1916. const RenderTarget& rt = s_renderCtx.m_renderTargets[sampler.m_idx];
  1917. GL_CHECK(glBindTexture(rt.m_color.m_target, rt.m_color.m_id) );
  1918. }
  1919. break;
  1920. case BGFX_SAMPLER_RENDERTARGET_DEPTH:
  1921. {
  1922. const RenderTarget& rt = s_renderCtx.m_renderTargets[sampler.m_idx];
  1923. GL_CHECK(glBindTexture(rt.m_depth.m_target, rt.m_depth.m_id) );
  1924. }
  1925. break;
  1926. }
  1927. }
  1928. }
  1929. current = sampler;
  1930. flag <<= 1;
  1931. }
  1932. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1933. }
  1934. if (currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx || materialChanged)
  1935. {
  1936. currentState.m_vertexBuffer = state.m_vertexBuffer;
  1937. uint16_t handle = state.m_vertexBuffer.idx;
  1938. if (bgfx::invalidHandle != handle)
  1939. {
  1940. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[handle];
  1941. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1942. bindAttribs = true;
  1943. }
  1944. else
  1945. {
  1946. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  1947. }
  1948. }
  1949. if (currentState.m_indexBuffer.idx != state.m_indexBuffer.idx)
  1950. {
  1951. currentState.m_indexBuffer = state.m_indexBuffer;
  1952. uint16_t handle = state.m_indexBuffer.idx;
  1953. if (bgfx::invalidHandle != handle)
  1954. {
  1955. IndexBuffer& ib = s_renderCtx.m_indexBuffers[handle];
  1956. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1957. }
  1958. else
  1959. {
  1960. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  1961. }
  1962. }
  1963. if (bgfx::invalidHandle != currentState.m_vertexBuffer.idx)
  1964. {
  1965. if (baseVertex != state.m_startVertex
  1966. || bindAttribs)
  1967. {
  1968. baseVertex = state.m_startVertex;
  1969. VertexBuffer& vb = s_renderCtx.m_vertexBuffers[state.m_vertexBuffer.idx];
  1970. uint16_t decl = vb.m_decl.idx == bgfx::invalidHandle ? state.m_vertexDecl.idx : vb.m_decl.idx;
  1971. s_renderCtx.m_materials[materialIdx].bindAttributes(s_renderCtx.m_vertexDecls[decl], state.m_startVertex);
  1972. }
  1973. uint32_t numIndices = 0;
  1974. uint32_t numPrims = 0;
  1975. if (bgfx::invalidHandle != state.m_indexBuffer.idx)
  1976. {
  1977. if (BGFX_DRAW_WHOLE_INDEX_BUFFER == state.m_startIndex)
  1978. {
  1979. numIndices = s_renderCtx.m_indexBuffers[state.m_indexBuffer.idx].m_size/2;
  1980. numPrims = numIndices/primNumVerts;
  1981. GL_CHECK(glDrawElements(primType
  1982. , s_renderCtx.m_indexBuffers[state.m_indexBuffer.idx].m_size/2
  1983. , GL_UNSIGNED_SHORT
  1984. , (void*)0
  1985. ) );
  1986. }
  1987. else if (primNumVerts <= state.m_numIndices)
  1988. {
  1989. numIndices = state.m_numIndices;
  1990. numPrims = numIndices/primNumVerts;
  1991. GL_CHECK(glDrawElements(primType
  1992. , numIndices
  1993. , GL_UNSIGNED_SHORT
  1994. , (void*)(uintptr_t)(state.m_startIndex*2)
  1995. ) );
  1996. }
  1997. }
  1998. else
  1999. {
  2000. numPrims = state.m_numVertices/primNumVerts;
  2001. GL_CHECK(glDrawArrays(primType
  2002. , 0
  2003. , state.m_numVertices
  2004. ) );
  2005. }
  2006. statsNumPrims += numPrims;
  2007. statsNumIndices += numIndices;
  2008. }
  2009. }
  2010. }
  2011. }
  2012. int64_t now = bx::getHPCounter();
  2013. elapsed += now;
  2014. static int64_t last = now;
  2015. int64_t frameTime = now - last;
  2016. last = now;
  2017. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2018. {
  2019. TextVideoMem& tvm = s_renderCtx.m_textVideoMem;
  2020. static int64_t next = now;
  2021. if (now >= next)
  2022. {
  2023. next = now + bx::getHPFrequency();
  2024. double freq = double(bx::getHPFrequency() );
  2025. double toMs = 1000.0/freq;
  2026. tvm.clear();
  2027. uint16_t pos = 10;
  2028. tvm.printf(10, pos++, 0x8e, " Frame: %3.4f [ms] / %3.2f", double(frameTime)*toMs, freq/frameTime);
  2029. tvm.printf(10, pos++, 0x8e, " Draw calls: %4d / %3.4f [ms]", m_render->m_num, double(elapsed)*toMs);
  2030. tvm.printf(10, pos++, 0x8e, " Prims: %7d", statsNumPrims);
  2031. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  2032. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", m_render->m_vboffset);
  2033. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", m_render->m_iboffset);
  2034. uint8_t attr[2] = { 0x89, 0x8a };
  2035. uint8_t attrIndex = m_render->m_waitSubmit < m_render->m_waitRender;
  2036. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", double(m_render->m_waitSubmit)*toMs);
  2037. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", double(m_render->m_waitRender)*toMs);
  2038. }
  2039. g_textVideoMemBlitter.blit(tvm);
  2040. }
  2041. else if (m_render->m_debug & BGFX_DEBUG_TEXT)
  2042. {
  2043. g_textVideoMemBlitter.blit(m_render->m_textVideoMem);
  2044. }
  2045. GREMEDY_FRAMETERMINATOR();
  2046. }
  2047. }
  2048. #endif // (BGFX_CONFIG_RENDERER_OPENGLES|BGFX_CONFIG_RENDERER_OPENGL)