OpenGL.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /**
  2. * Copyright (c) 2006-2016 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 "graphics/Color.h"
  26. #include "graphics/Texture.h"
  27. #include "common/Matrix.h"
  28. // GLAD
  29. #include "libraries/glad/gladfuncs.hpp"
  30. // C++
  31. #include <vector>
  32. #include <stack>
  33. // The last argument to AttribPointer takes a buffer offset casted to a pointer.
  34. #define BUFFER_OFFSET(i) ((char *) NULL + (i))
  35. namespace love
  36. {
  37. namespace graphics
  38. {
  39. namespace opengl
  40. {
  41. // Awful, but the library uses the namespace in order to use the functions sanely
  42. // with proper autocomplete in IDEs while having name mangling safety -
  43. // no clashes with other GL libraries when linking, etc.
  44. using namespace glad;
  45. // Vertex attribute indices used in shaders by LOVE. The values map to OpenGL
  46. // generic vertex attribute indices.
  47. enum VertexAttribID
  48. {
  49. ATTRIB_POS = 0,
  50. ATTRIB_TEXCOORD,
  51. ATTRIB_COLOR,
  52. ATTRIB_CONSTANTCOLOR,
  53. ATTRIB_MAX_ENUM
  54. };
  55. enum VertexAttribFlags
  56. {
  57. ATTRIBFLAG_POS = 1 << ATTRIB_POS,
  58. ATTRIBFLAG_TEXCOORD = 1 << ATTRIB_TEXCOORD,
  59. ATTRIBFLAG_COLOR = 1 << ATTRIB_COLOR,
  60. ATTRIBFLAG_CONSTANTCOLOR = 1 << ATTRIB_CONSTANTCOLOR
  61. };
  62. enum BufferType
  63. {
  64. BUFFER_VERTEX = 0,
  65. BUFFER_INDEX,
  66. BUFFER_MAX_ENUM
  67. };
  68. /**
  69. * Thin layer between OpenGL and the rest of the program.
  70. * Internally shadows some OpenGL context state for improved efficiency and
  71. * accuracy (compared to glGet etc.)
  72. * A class is more convenient and readable than plain namespaced functions, but
  73. * typically only one OpenGL object should be used (singleton.)
  74. **/
  75. class OpenGL
  76. {
  77. public:
  78. // OpenGL GPU vendors.
  79. enum Vendor
  80. {
  81. VENDOR_AMD,
  82. VENDOR_NVIDIA,
  83. VENDOR_INTEL,
  84. VENDOR_MESA_SOFT, // Software renderer.
  85. VENDOR_APPLE, // Software renderer on desktops.
  86. VENDOR_MICROSOFT, // Software renderer.
  87. VENDOR_IMGTEC,
  88. VENDOR_ARM,
  89. VENDOR_QUALCOMM,
  90. VENDOR_BROADCOM,
  91. VENDOR_VIVANTE,
  92. VENDOR_UNKNOWN
  93. };
  94. enum FramebufferTarget
  95. {
  96. FRAMEBUFFER_READ = (1 << 0),
  97. FRAMEBUFFER_DRAW = (1 << 1),
  98. FRAMEBUFFER_ALL = (FRAMEBUFFER_READ | FRAMEBUFFER_DRAW),
  99. };
  100. // A rectangle representing an OpenGL viewport or a scissor box.
  101. struct Viewport
  102. {
  103. int x, y;
  104. int w, h;
  105. bool operator == (const Viewport &rhs) const
  106. {
  107. return x == rhs.x && y == rhs.y && w == rhs.w && h == rhs.h;
  108. }
  109. };
  110. struct
  111. {
  112. std::vector<Matrix4> transform;
  113. Matrix4 projection;
  114. } matrices;
  115. class TempTransform
  116. {
  117. public:
  118. TempTransform(OpenGL &gl)
  119. : gl(gl)
  120. {
  121. gl.pushTransform();
  122. }
  123. ~TempTransform()
  124. {
  125. gl.popTransform();
  126. }
  127. Matrix4 &get()
  128. {
  129. return gl.getTransform();
  130. }
  131. private:
  132. OpenGL &gl;
  133. };
  134. class TempDebugGroup
  135. {
  136. public:
  137. #if defined(LOVE_IOS)
  138. TempDebugGroup(const char *name)
  139. {
  140. if (GLAD_EXT_debug_marker)
  141. glPushGroupMarkerEXT(0, (const GLchar *) name);
  142. }
  143. #else
  144. TempDebugGroup(const char *) {}
  145. #endif
  146. #if defined(LOVE_IOS)
  147. ~TempDebugGroup()
  148. {
  149. if (GLAD_EXT_debug_marker)
  150. glPopGroupMarkerEXT();
  151. }
  152. #endif
  153. };
  154. struct Stats
  155. {
  156. size_t textureMemory;
  157. int drawCalls;
  158. int shaderSwitches;
  159. } stats;
  160. struct Bugs
  161. {
  162. /**
  163. * On AMD's Windows (and probably Linux) drivers,
  164. * glBindFramebuffer + glClear + glBindFramebuffer + draw(fbo_tex) won't
  165. * work unless there's some kind of draw or state change which causes
  166. * the driver to update the texture's contents (just drawing the texture
  167. * won't always do it, with this driver bug).
  168. * Activating shader program 0 and then activating the actual program
  169. * seems to always 'fix' it for me.
  170. * Bug observed January 2016 with multiple AMD GPUs and driver versions.
  171. * https://love2d.org/forums/viewtopic.php?f=4&t=81496
  172. **/
  173. bool clearRequiresDriverTextureStateUpdate;
  174. /**
  175. * AMD's Windows drivers don't always properly generate mipmaps unless
  176. * glEnable(GL_TEXTURE_2D) is called directly before glGenerateMipmap.
  177. * This only applies to legacy and Compatibility Profile contexts, of
  178. * course.
  179. * https://www.opengl.org/wiki/Common_Mistakes#Automatic_mipmap_generation
  180. **/
  181. bool generateMipmapsRequiresTexture2DEnable;
  182. /**
  183. * Other bugs which have workarounds that don't use conditional code at
  184. * the moment:
  185. *
  186. * Kepler nvidia GPUs in at least OS X 10.10 and 10.11 fail to render
  187. * geometry with glDrawElements if index data comes from a Buffer Object
  188. * and vertex data doesn't. One workaround is to use a CPU-side index
  189. * array when there's also a CPU-side vertex array.
  190. * https://love2d.org/forums/viewtopic.php?f=4&t=81401&start=10
  191. *
  192. * Some android drivers don't seem to initialize the sampler index
  193. * values of sampler uniforms in shaders to 0 (which is required by the
  194. * GLSL ES specification) when linking the shader program. One
  195. * workaround is to always set the values of said sampler uniforms to 0
  196. * just after linking the shader program.
  197. * https://love2d.org/forums/viewtopic.php?f=4&t=81458
  198. **/
  199. } bugs;
  200. OpenGL();
  201. /**
  202. * Initializes the active OpenGL context.
  203. **/
  204. bool initContext();
  205. /**
  206. * Sets up some required context state based on current and default OpenGL
  207. * state. Call this directly after initializing an OpenGL context!
  208. **/
  209. void setupContext();
  210. /**
  211. * Marks current context state as invalid and deletes OpenGL objects owned
  212. * by this class instance. Call this directly before potentially deleting
  213. * an OpenGL context!
  214. **/
  215. void deInitContext();
  216. void pushTransform();
  217. void popTransform();
  218. Matrix4 &getTransform();
  219. /**
  220. * Set up necessary state (LOVE-provided shader uniforms, etc.) for drawing.
  221. * This *MUST* be called directly before OpenGL drawing functions.
  222. **/
  223. void prepareDraw();
  224. /**
  225. * State-tracked glBindBuffer.
  226. * NOTE: This does not account for multiple VAOs being used! Index buffer
  227. * bindings are per-VAO in OpenGL, but this doesn't know about that.
  228. **/
  229. void bindBuffer(BufferType type, GLuint buffer);
  230. /**
  231. * glDeleteBuffers which updates our shadowed state.
  232. **/
  233. void deleteBuffer(GLuint buffer);
  234. /**
  235. * glDrawArrays and glDrawElements which increment the draw-call counter by
  236. * themselves.
  237. **/
  238. void drawArrays(GLenum mode, GLint first, GLsizei count);
  239. void drawElements(GLenum mode, GLsizei count, GLenum type, const void *indices);
  240. /**
  241. * Sets the enabled vertex attribute arrays based on the specified attribute
  242. * bits. Each bit in the uint32 represents an enabled attribute array index.
  243. * For example, useVertexAttribArrays(1 << 0) will enable attribute index 0.
  244. * See the VertexAttribFlags enum for the standard vertex attributes.
  245. * This function *must* be used instead of glEnable/DisableVertexAttribArray.
  246. **/
  247. void useVertexAttribArrays(uint32 arraybits);
  248. /**
  249. * Sets the OpenGL rendering viewport to the specified rectangle.
  250. * The y-coordinate starts at the top.
  251. **/
  252. void setViewport(const Viewport &v, bool canvasActive);
  253. /**
  254. * Gets the current OpenGL rendering viewport rectangle.
  255. **/
  256. Viewport getViewport() const;
  257. /**
  258. * Sets the scissor box to the specified rectangle.
  259. * The y-coordinate starts at the top and is flipped internally.
  260. **/
  261. void setScissor(const Viewport &v, bool canvasActive);
  262. /**
  263. * Gets the current scissor box (regardless of whether scissoring is enabled.)
  264. **/
  265. Viewport getScissor() const;
  266. /**
  267. * Sets the global point size.
  268. **/
  269. void setPointSize(float size);
  270. /**
  271. * Gets the global point size.
  272. **/
  273. float getPointSize() const;
  274. /**
  275. * Calls glEnable/glDisable(GL_FRAMEBUFFER_SRGB).
  276. **/
  277. void setFramebufferSRGB(bool enable);
  278. /**
  279. * Equivalent to glIsEnabled(GL_FRAMEBUFFER_SRGB).
  280. **/
  281. bool hasFramebufferSRGB() const;
  282. /**
  283. * Binds a Framebuffer Object to the specified target.
  284. **/
  285. void bindFramebuffer(FramebufferTarget target, GLuint framebuffer);
  286. GLuint getFramebuffer(FramebufferTarget target) const;
  287. void deleteFramebuffer(GLuint framebuffer);
  288. /**
  289. * Calls glUseProgram.
  290. **/
  291. void useProgram(GLuint program);
  292. /**
  293. * This will usually be 0 (system drawable), but some platforms require a
  294. * non-zero FBO for rendering.
  295. **/
  296. GLuint getDefaultFBO() const;
  297. /**
  298. * Gets the ID for love's default texture (used for "untextured" primitives.)
  299. **/
  300. GLuint getDefaultTexture() const;
  301. /**
  302. * Helper for setting the active texture unit.
  303. *
  304. * @param textureunit Index in the range of [0, maxtextureunits-1]
  305. **/
  306. void setTextureUnit(int textureunit);
  307. /**
  308. * Helper for binding a texture to a specific texture unit.
  309. *
  310. * @param textureunit Index in the range of [0, maxtextureunits-1]
  311. * @param restoreprev Restore previously bound texture unit when done.
  312. **/
  313. void bindTextureToUnit(GLuint texture, int textureunit, bool restoreprev);
  314. /**
  315. * Helper for deleting an OpenGL texture.
  316. * Cleans up if the texture is currently bound.
  317. **/
  318. void deleteTexture(GLuint texture);
  319. /**
  320. * Sets the texture filter mode for the currently bound texture.
  321. * The anisotropy parameter of the argument is set to the actual amount of
  322. * anisotropy that was used.
  323. **/
  324. void setTextureFilter(graphics::Texture::Filter &f);
  325. /**
  326. * Sets the texture wrap mode for the currently bound texture.
  327. **/
  328. void setTextureWrap(const graphics::Texture::Wrap &w);
  329. bool isClampZeroTextureWrapSupported() const;
  330. /**
  331. * Returns the maximum supported width or height of a texture.
  332. **/
  333. int getMaxTextureSize() const;
  334. /**
  335. * Returns the maximum supported number of simultaneous render targets.
  336. **/
  337. int getMaxRenderTargets() const;
  338. /**
  339. * Returns the maximum supported number of MSAA samples for renderbuffers.
  340. **/
  341. int getMaxRenderbufferSamples() const;
  342. /**
  343. * Returns the maximum number of accessible texture units.
  344. **/
  345. int getMaxTextureUnits() const;
  346. /**
  347. * Returns the maximum point size.
  348. **/
  349. float getMaxPointSize() const;
  350. void updateTextureMemorySize(size_t oldsize, size_t newsize);
  351. /**
  352. * Get the GPU vendor of this OpenGL context.
  353. **/
  354. Vendor getVendor() const;
  355. static GLenum getGLBufferType(BufferType type);
  356. static GLint getGLWrapMode(Texture::WrapMode wmode);
  357. static const char *errorString(GLenum errorcode);
  358. static const char *framebufferStatusString(GLenum status);
  359. // Get human-readable strings for debug info.
  360. static const char *debugSeverityString(GLenum severity);
  361. static const char *debugSourceString(GLenum source);
  362. static const char *debugTypeString(GLenum type);
  363. private:
  364. void initVendor();
  365. void initOpenGLFunctions();
  366. void initMaxValues();
  367. void initMatrices();
  368. void createDefaultTexture();
  369. bool contextInitialized;
  370. float maxAnisotropy;
  371. int maxTextureSize;
  372. int maxRenderTargets;
  373. int maxRenderbufferSamples;
  374. int maxTextureUnits;
  375. float maxPointSize;
  376. Vendor vendor;
  377. // Tracked OpenGL state.
  378. struct
  379. {
  380. GLuint boundBuffers[BUFFER_MAX_ENUM];
  381. // Texture unit state (currently bound texture for each texture unit.)
  382. std::vector<GLuint> boundTextures;
  383. // Currently active texture unit.
  384. int curTextureUnit;
  385. uint32 enabledAttribArrays;
  386. Viewport viewport;
  387. Viewport scissor;
  388. float pointSize;
  389. GLuint boundFramebuffers[2];
  390. bool framebufferSRGBEnabled;
  391. GLuint defaultTexture;
  392. Matrix4 lastProjectionMatrix;
  393. Matrix4 lastTransformMatrix;
  394. } state;
  395. }; // OpenGL
  396. // OpenGL class instance singleton.
  397. extern OpenGL gl;
  398. } // opengl
  399. } // graphics
  400. } // love
  401. #endif // LOVE_GRAPHICS_OPENGL_OPENGL_H