OpenGL.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /**
  2. * Copyright (c) 2006-2017 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #ifndef LOVE_GRAPHICS_OPENGL_OPENGL_H
  21. #define LOVE_GRAPHICS_OPENGL_OPENGL_H
  22. // LOVE
  23. #include "common/config.h"
  24. #include "common/int.h"
  25. #include "common/math.h"
  26. #include "graphics/Color.h"
  27. #include "graphics/Texture.h"
  28. #include "graphics/vertex.h"
  29. #include "common/Matrix.h"
  30. // GLAD
  31. #include "libraries/glad/gladfuncs.hpp"
  32. // C++
  33. #include <vector>
  34. #include <stack>
  35. // The last argument to AttribPointer takes a buffer offset casted to a pointer.
  36. #define BUFFER_OFFSET(i) ((char *) NULL + (i))
  37. namespace love
  38. {
  39. namespace graphics
  40. {
  41. namespace opengl
  42. {
  43. // Awful, but the library uses the namespace in order to use the functions sanely
  44. // with proper autocomplete in IDEs while having name mangling safety -
  45. // no clashes with other GL libraries when linking, etc.
  46. using namespace glad;
  47. /**
  48. * Thin layer between OpenGL and the rest of the program.
  49. * Internally shadows some OpenGL context state for improved efficiency and
  50. * accuracy (compared to glGet etc.)
  51. * A class is more convenient and readable than plain namespaced functions, but
  52. * typically only one OpenGL object should be used (singleton.)
  53. **/
  54. class OpenGL
  55. {
  56. public:
  57. // OpenGL GPU vendors.
  58. enum Vendor
  59. {
  60. VENDOR_AMD,
  61. VENDOR_NVIDIA,
  62. VENDOR_INTEL,
  63. VENDOR_MESA_SOFT, // Software renderer.
  64. VENDOR_APPLE, // Software renderer on desktops.
  65. VENDOR_MICROSOFT, // Software renderer.
  66. VENDOR_IMGTEC,
  67. VENDOR_ARM,
  68. VENDOR_QUALCOMM,
  69. VENDOR_BROADCOM,
  70. VENDOR_VIVANTE,
  71. VENDOR_UNKNOWN
  72. };
  73. enum FramebufferTarget
  74. {
  75. FRAMEBUFFER_READ = (1 << 0),
  76. FRAMEBUFFER_DRAW = (1 << 1),
  77. FRAMEBUFFER_ALL = (FRAMEBUFFER_READ | FRAMEBUFFER_DRAW),
  78. };
  79. struct TextureFormat
  80. {
  81. GLenum internalformat = 0;
  82. GLenum externalformat = 0;
  83. GLenum type = 0;
  84. bool swizzled = false;
  85. GLint swizzle[4];
  86. };
  87. class TempDebugGroup
  88. {
  89. public:
  90. TempDebugGroup(const char *name);
  91. ~TempDebugGroup();
  92. };
  93. struct Stats
  94. {
  95. size_t textureMemory;
  96. int drawCalls;
  97. int shaderSwitches;
  98. } stats;
  99. struct Bugs
  100. {
  101. /**
  102. * On AMD's Windows (and probably Linux) drivers,
  103. * glBindFramebuffer + glClear + glBindFramebuffer + draw(fbo_tex) won't
  104. * work unless there's some kind of draw or state change which causes
  105. * the driver to update the texture's contents (just drawing the texture
  106. * won't always do it, with this driver bug).
  107. * Activating shader program 0 and then activating the actual program
  108. * seems to always 'fix' it for me.
  109. * Bug observed January 2016 with multiple AMD GPUs and driver versions.
  110. * https://love2d.org/forums/viewtopic.php?f=4&t=81496
  111. **/
  112. bool clearRequiresDriverTextureStateUpdate;
  113. /**
  114. * AMD's Windows drivers don't always properly generate mipmaps unless
  115. * glEnable(GL_TEXTURE_2D) is called directly before glGenerateMipmap.
  116. * This only applies to legacy and Compatibility Profile contexts, of
  117. * course.
  118. * https://www.opengl.org/wiki/Common_Mistakes#Automatic_mipmap_generation
  119. **/
  120. bool generateMipmapsRequiresTexture2DEnable;
  121. /**
  122. * Other bugs which have workarounds that don't use conditional code at
  123. * the moment:
  124. *
  125. * Kepler nvidia GPUs in at least OS X 10.10 and 10.11 fail to render
  126. * geometry with glDrawElements if index data comes from a Buffer Object
  127. * and vertex data doesn't. One workaround is to use a CPU-side index
  128. * array when there's also a CPU-side vertex array.
  129. * https://love2d.org/forums/viewtopic.php?f=4&t=81401&start=10
  130. *
  131. * Some android drivers don't seem to initialize the sampler index
  132. * values of sampler uniforms in shaders to 0 (which is required by the
  133. * GLSL ES specification) when linking the shader program. One
  134. * workaround is to always set the values of said sampler uniforms to 0
  135. * just after linking the shader program.
  136. * https://love2d.org/forums/viewtopic.php?f=4&t=81458
  137. **/
  138. } bugs;
  139. OpenGL();
  140. /**
  141. * Initializes the active OpenGL context.
  142. **/
  143. bool initContext();
  144. /**
  145. * Sets up some required context state based on current and default OpenGL
  146. * state. Call this directly after initializing an OpenGL context!
  147. **/
  148. void setupContext();
  149. /**
  150. * Marks current context state as invalid and deletes OpenGL objects owned
  151. * by this class instance. Call this directly before potentially deleting
  152. * an OpenGL context!
  153. **/
  154. void deInitContext();
  155. /**
  156. * Set up necessary state (LOVE-provided shader uniforms, etc.) for drawing.
  157. * This *MUST* be called directly before OpenGL drawing functions.
  158. **/
  159. void prepareDraw();
  160. /**
  161. * State-tracked glBindBuffer.
  162. * NOTE: This does not account for multiple VAOs being used! Index buffer
  163. * bindings are per-VAO in OpenGL, but this doesn't know about that.
  164. **/
  165. void bindBuffer(BufferType type, GLuint buffer);
  166. /**
  167. * glDeleteBuffers which updates our shadowed state.
  168. **/
  169. void deleteBuffer(GLuint buffer);
  170. /**
  171. * glDrawArrays and glDrawElements which increment the draw-call counter by
  172. * themselves.
  173. **/
  174. void drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instancecount = 1);
  175. void drawElements(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount = 1);
  176. /**
  177. * Sets the enabled vertex attribute arrays based on the specified attribute
  178. * bits. Each bit in the uint32 represents an enabled attribute array index.
  179. * For example, useVertexAttribArrays(1 << 0) will enable attribute index 0.
  180. * See the VertexAttribFlags enum for the standard vertex attributes.
  181. * This function *must* be used instead of glEnable/DisableVertexAttribArray.
  182. **/
  183. void useVertexAttribArrays(uint32 arraybits, uint32 instancedbits = 0);
  184. /**
  185. * Sets the OpenGL rendering viewport to the specified rectangle.
  186. * The y-coordinate starts at the top.
  187. **/
  188. void setViewport(const Rect &v);
  189. Rect getViewport() const;
  190. /**
  191. * Sets the scissor box to the specified rectangle.
  192. * The y-coordinate starts at the top and is flipped internally.
  193. **/
  194. void setScissor(const Rect &v, bool canvasActive);
  195. /**
  196. * Sets the constant color (vertex attribute). This may be applied
  197. * internally at draw-time. This gets gamma-corrected internally as well.
  198. **/
  199. void setConstantColor(const Colorf &color);
  200. const Colorf &getConstantColor() const;
  201. /**
  202. * Sets the global point size.
  203. **/
  204. void setPointSize(float size);
  205. float getPointSize() const;
  206. /**
  207. * Calls glEnable/glDisable(GL_FRAMEBUFFER_SRGB).
  208. **/
  209. void setFramebufferSRGB(bool enable);
  210. bool hasFramebufferSRGB() const;
  211. /**
  212. * Binds a Framebuffer Object to the specified target.
  213. **/
  214. void bindFramebuffer(FramebufferTarget target, GLuint framebuffer);
  215. GLuint getFramebuffer(FramebufferTarget target) const;
  216. void deleteFramebuffer(GLuint framebuffer);
  217. void framebufferTexture(GLenum attachment, TextureType texType, GLuint texture, int level, int layer = 0, int face = 0);
  218. /**
  219. * Calls glUseProgram.
  220. **/
  221. void useProgram(GLuint program);
  222. /**
  223. * This will usually be 0 (system drawable), but some platforms require a
  224. * non-zero FBO for rendering.
  225. **/
  226. GLuint getDefaultFBO() const;
  227. /**
  228. * Gets the ID for love's default texture (used for "untextured" primitives.)
  229. **/
  230. GLuint getDefaultTexture(TextureType type) const;
  231. /**
  232. * Helper for setting the active texture unit.
  233. *
  234. * @param textureunit Index in the range of [0, maxtextureunits-1]
  235. **/
  236. void setTextureUnit(int textureunit);
  237. /**
  238. * Helper for binding a texture to a specific texture unit.
  239. *
  240. * @param textureunit Index in the range of [0, maxtextureunits-1]
  241. * @param restoreprev Restore previously bound texture unit when done.
  242. **/
  243. void bindTextureToUnit(TextureType target, GLuint texture, int textureunit, bool restoreprev);
  244. void bindTextureToUnit(Texture *texture, int textureunit, bool restoreprev);
  245. /**
  246. * Helper for deleting an OpenGL texture.
  247. * Cleans up if the texture is currently bound.
  248. **/
  249. void deleteTexture(GLuint texture);
  250. /**
  251. * Sets the texture filter mode for the currently bound texture.
  252. * The anisotropy parameter of the argument is set to the actual amount of
  253. * anisotropy that was used.
  254. **/
  255. void setTextureFilter(TextureType target, graphics::Texture::Filter &f);
  256. /**
  257. * Sets the texture wrap mode for the currently bound texture.
  258. **/
  259. void setTextureWrap(TextureType target, const graphics::Texture::Wrap &w);
  260. /**
  261. * Equivalent to glTexStorage2D/3D on platforms that support it. Equivalent
  262. * to glTexImage2D/3D for all levels and slices of a texture otherwise.
  263. * NOTE: this does not handle compressed texture formats.
  264. **/
  265. bool rawTexStorage(TextureType target, int levels, PixelFormat pixelformat, bool &isSRGB, int width, int height, int depth = 1);
  266. bool isTextureTypeSupported(TextureType type) const;
  267. bool isClampZeroTextureWrapSupported() const;
  268. bool isPixelShaderHighpSupported() const;
  269. bool isInstancingSupported() const;
  270. /**
  271. * Returns the maximum supported width or height of a texture.
  272. **/
  273. int getMax2DTextureSize() const;
  274. int getMax3DTextureSize() const;
  275. int getMaxCubeTextureSize() const;
  276. int getMaxTextureLayers() const;
  277. /**
  278. * Returns the maximum supported number of simultaneous render targets.
  279. **/
  280. int getMaxRenderTargets() const;
  281. /**
  282. * Returns the maximum supported number of MSAA samples for renderbuffers.
  283. **/
  284. int getMaxRenderbufferSamples() const;
  285. /**
  286. * Returns the maximum number of accessible texture units.
  287. **/
  288. int getMaxTextureUnits() const;
  289. /**
  290. * Returns the maximum point size.
  291. **/
  292. float getMaxPointSize() const;
  293. /**
  294. * Returns the maximum anisotropic filtering value that can be used for
  295. * Texture filtering.
  296. **/
  297. float getMaxAnisotropy() const;
  298. void updateTextureMemorySize(size_t oldsize, size_t newsize);
  299. /**
  300. * Gets whether the context is Core Profile OpenGL 3.2+.
  301. **/
  302. bool isCoreProfile() const;
  303. /**
  304. * Get the GPU vendor of this OpenGL context.
  305. **/
  306. Vendor getVendor() const;
  307. static GLenum getGLBufferType(BufferType type);
  308. static GLenum getGLIndexDataType(IndexDataType type);
  309. static GLenum getGLBufferUsage(vertex::Usage usage);
  310. static GLenum getGLTextureType(TextureType type);
  311. static GLint getGLWrapMode(Texture::WrapMode wmode);
  312. static TextureFormat convertPixelFormat(PixelFormat pixelformat, bool renderbuffer, bool &isSRGB);
  313. static bool isPixelFormatSupported(PixelFormat pixelformat, bool rendertarget, bool isSRGB);
  314. static bool hasTextureFilteringSupport(PixelFormat pixelformat);
  315. static const char *errorString(GLenum errorcode);
  316. static const char *framebufferStatusString(GLenum status);
  317. // Get human-readable strings for debug info.
  318. static const char *debugSeverityString(GLenum severity);
  319. static const char *debugSourceString(GLenum source);
  320. static const char *debugTypeString(GLenum type);
  321. private:
  322. void initVendor();
  323. void initOpenGLFunctions();
  324. void initMaxValues();
  325. void createDefaultTexture();
  326. bool contextInitialized;
  327. bool pixelShaderHighpSupported;
  328. float maxAnisotropy;
  329. int max2DTextureSize;
  330. int max3DTextureSize;
  331. int maxCubeTextureSize;
  332. int maxTextureArrayLayers;
  333. int maxRenderTargets;
  334. int maxRenderbufferSamples;
  335. int maxTextureUnits;
  336. float maxPointSize;
  337. bool coreProfile;
  338. Vendor vendor;
  339. // Tracked OpenGL state.
  340. struct
  341. {
  342. GLuint boundBuffers[BUFFER_MAX_ENUM];
  343. // Texture unit state (currently bound texture for each texture unit.)
  344. std::vector<GLuint> boundTextures[TEXTURE_MAX_ENUM];
  345. // Currently active texture unit.
  346. int curTextureUnit;
  347. uint32 enabledAttribArrays;
  348. uint32 instancedAttribArrays;
  349. Colorf constantColor;
  350. Colorf lastConstantColor;
  351. Rect viewport;
  352. Rect scissor;
  353. float pointSize;
  354. GLuint boundFramebuffers[2];
  355. bool framebufferSRGBEnabled;
  356. GLuint defaultTexture[TEXTURE_MAX_ENUM];
  357. } state;
  358. }; // OpenGL
  359. // OpenGL class instance singleton.
  360. extern OpenGL gl;
  361. } // opengl
  362. } // graphics
  363. } // love
  364. #endif // LOVE_GRAPHICS_OPENGL_OPENGL_H