Graphics.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. /**
  2. * Copyright (c) 2006-2013 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. #include "common/config.h"
  21. #include "common/math.h"
  22. #include "common/Vector.h"
  23. #include "Graphics.h"
  24. #include "window/sdl/Window.h"
  25. #include <vector>
  26. #include <sstream>
  27. #include <algorithm>
  28. #include <iterator>
  29. using love::window::WindowFlags;
  30. namespace love
  31. {
  32. namespace graphics
  33. {
  34. namespace opengl
  35. {
  36. Graphics::Graphics()
  37. : currentFont(0)
  38. , lineStyle(LINE_SMOOTH)
  39. , lineWidth(1)
  40. , matrixLimit(0)
  41. , userMatrices(0)
  42. , colorMask()
  43. , width(0)
  44. , height(0)
  45. , created(false)
  46. , savedState()
  47. {
  48. currentWindow = love::window::sdl::Window::getSingleton();
  49. if (currentWindow->isCreated())
  50. setMode(currentWindow->getWidth(), currentWindow->getHeight());
  51. }
  52. Graphics::~Graphics()
  53. {
  54. if (currentFont != 0)
  55. currentFont->release();
  56. currentWindow->release();
  57. }
  58. const char *Graphics::getName() const
  59. {
  60. return "love.graphics.opengl";
  61. }
  62. DisplayState Graphics::saveState()
  63. {
  64. DisplayState s;
  65. s.color = getColor();
  66. s.backgroundColor = getBackgroundColor();
  67. s.blendMode = getBlendMode();
  68. //get line style
  69. s.lineStyle = lineStyle;
  70. //get the point size
  71. glGetFloatv(GL_POINT_SIZE, &s.pointSize);
  72. //get point style
  73. s.pointStyle = (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE) ? Graphics::POINT_SMOOTH : Graphics::POINT_ROUGH;
  74. // get alpha test status
  75. s.alphaTest = isAlphaTestEnabled();
  76. if (s.alphaTest)
  77. {
  78. // if alpha testing is enabled, store mode and reference alpha
  79. s.alphaTestMode = getAlphaTestMode();
  80. s.alphaTestRef = getAlphaTestRef();
  81. }
  82. //get scissor status
  83. s.scissor = (glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE);
  84. //do we have scissor, if so, store the box
  85. if (s.scissor)
  86. s.scissorBox = gl.getScissor();
  87. for (int i = 0; i < 4; i++)
  88. s.colorMask[i] = colorMask[i];
  89. return s;
  90. }
  91. void Graphics::restoreState(const DisplayState &s)
  92. {
  93. setColor(s.color);
  94. setBackgroundColor(s.backgroundColor);
  95. setBlendMode(s.blendMode);
  96. setLine(lineWidth, s.lineStyle);
  97. setPoint(s.pointSize, s.pointStyle);
  98. if (s.alphaTest)
  99. setAlphaTest(s.alphaTestMode, s.alphaTestRef);
  100. else
  101. setAlphaTest();
  102. if (s.scissor)
  103. setScissor(s.scissorBox.x, s.scissorBox.y, s.scissorBox.w, s.scissorBox.h);
  104. else
  105. setScissor();
  106. setColorMask(s.colorMask[0], s.colorMask[1], s.colorMask[2], s.colorMask[3]);
  107. }
  108. bool Graphics::setMode(int width, int height)
  109. {
  110. this->width = width;
  111. this->height = height;
  112. // Okay, setup OpenGL.
  113. gl.initContext();
  114. // Make sure antialiasing works when set elsewhere
  115. if (GLEE_VERSION_1_3 || GLEE_ARB_multisample)
  116. glEnable(GL_MULTISAMPLE);
  117. // Enable blending
  118. glEnable(GL_BLEND);
  119. // "Normal" blending
  120. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  121. // Enable all color component writes.
  122. setColorMask(true, true, true, true);
  123. // Enable line/point smoothing.
  124. setLineStyle(LINE_SMOOTH);
  125. glEnable(GL_POINT_SMOOTH);
  126. glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
  127. // Auto-generated mipmaps should be the best quality possible
  128. if (GLEE_VERSION_1_4 || GLEE_SGIS_generate_mipmap)
  129. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  130. // Set default alpha test mode and value
  131. glAlphaFunc(GL_GREATER, 0.0f);
  132. setAlphaTest();
  133. // Enable textures
  134. glEnable(GL_TEXTURE_2D);
  135. gl.setActiveTextureUnit(0);
  136. // Set the viewport to top-left corner
  137. gl.setViewport(OpenGL::Viewport(0, 0, width, height));
  138. // Reset the projection matrix
  139. glMatrixMode(GL_PROJECTION);
  140. glLoadIdentity();
  141. // Set up orthographic view (no depth)
  142. glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
  143. // Reset modelview matrix
  144. glMatrixMode(GL_MODELVIEW);
  145. glLoadIdentity();
  146. // Set pixel row alignment
  147. glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
  148. // Reload all volatile objects.
  149. if (!Volatile::loadAll())
  150. std::cerr << "Could not reload all volatile objects." << std::endl;
  151. // Restore the display state.
  152. restoreState(savedState);
  153. pixel_size_stack.clear();
  154. pixel_size_stack.reserve(5);
  155. pixel_size_stack.push_back(1);
  156. // Get the maximum number of matrices
  157. // subtract a few to give the engine some room.
  158. glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &matrixLimit);
  159. matrixLimit -= 5;
  160. created = true;
  161. return true;
  162. }
  163. void Graphics::unSetMode()
  164. {
  165. // Window re-creation may destroy the GL context, so we must save the state.
  166. if (isCreated())
  167. savedState = saveState();
  168. // Unload all volatile objects. These must be reloaded after the display
  169. // mode change.
  170. Volatile::unloadAll();
  171. gl.deInitContext();
  172. }
  173. void Graphics::reset()
  174. {
  175. DisplayState s;
  176. discardStencil();
  177. Canvas::bindDefaultCanvas();
  178. Shader::detach();
  179. restoreState(s);
  180. pixel_size_stack.clear();
  181. pixel_size_stack.reserve(5);
  182. pixel_size_stack.push_back(1);
  183. }
  184. void Graphics::clear()
  185. {
  186. glClear(GL_COLOR_BUFFER_BIT);
  187. }
  188. void Graphics::present()
  189. {
  190. currentWindow->swapBuffers();
  191. }
  192. int Graphics::getWidth() const
  193. {
  194. return width;
  195. }
  196. int Graphics::getHeight() const
  197. {
  198. return height;
  199. }
  200. int Graphics::getRenderWidth() const
  201. {
  202. if (Canvas::current)
  203. return Canvas::current->getWidth();
  204. return getWidth();
  205. }
  206. int Graphics::getRenderHeight() const
  207. {
  208. if (Canvas::current)
  209. return Canvas::current->getHeight();
  210. return getHeight();
  211. }
  212. bool Graphics::isCreated() const
  213. {
  214. return created;
  215. }
  216. void Graphics::setScissor(int x, int y, int width, int height)
  217. {
  218. glEnable(GL_SCISSOR_TEST);
  219. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  220. gl.setScissor(OpenGL::Viewport(x, y, width, height));
  221. }
  222. void Graphics::setScissor()
  223. {
  224. glDisable(GL_SCISSOR_TEST);
  225. }
  226. int Graphics::getScissor(lua_State *L) const
  227. {
  228. if (glIsEnabled(GL_SCISSOR_TEST) == GL_FALSE)
  229. return 0;
  230. OpenGL::Viewport scissor = gl.getScissor();
  231. lua_pushinteger(L, scissor.x);
  232. lua_pushinteger(L, scissor.y);
  233. lua_pushinteger(L, scissor.w);
  234. lua_pushinteger(L, scissor.h);
  235. return 4;
  236. }
  237. void Graphics::defineStencil()
  238. {
  239. // Make sure the active canvas has a stencil buffer.
  240. if (Canvas::current)
  241. Canvas::current->checkCreateStencil();
  242. // Disable color writes but don't save the mask values.
  243. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  244. glClear(GL_STENCIL_BUFFER_BIT);
  245. glEnable(GL_STENCIL_TEST);
  246. glStencilFunc(GL_ALWAYS, 1, 1);
  247. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  248. }
  249. void Graphics::useStencil(bool invert)
  250. {
  251. glStencilFunc(GL_EQUAL, (GLint)(!invert), 1); // invert ? 0 : 1
  252. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  253. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  254. }
  255. void Graphics::discardStencil()
  256. {
  257. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  258. glDisable(GL_STENCIL_TEST);
  259. }
  260. void Graphics::setAlphaTest(Graphics::AlphaTestMode mode, unsigned char refalpha)
  261. {
  262. GLclampf ref = refalpha / 255.0f;
  263. glEnable(GL_ALPHA_TEST);
  264. switch (mode)
  265. {
  266. case ALPHATEST_LESS:
  267. glAlphaFunc(GL_LESS, ref);
  268. break;
  269. case ALPHATEST_LEQUAL:
  270. glAlphaFunc(GL_LEQUAL, ref);
  271. break;
  272. case ALPHATEST_EQUAL:
  273. glAlphaFunc(GL_EQUAL, ref);
  274. break;
  275. case ALPHATEST_NOTEQUAL:
  276. glAlphaFunc(GL_NOTEQUAL, ref);
  277. break;
  278. case ALPHATEST_GEQUAL:
  279. glAlphaFunc(GL_GEQUAL, ref);
  280. break;
  281. case ALPHATEST_GREATER:
  282. glAlphaFunc(GL_GREATER, ref);
  283. break;
  284. default:
  285. glDisable(GL_ALPHA_TEST);
  286. break;
  287. }
  288. }
  289. void Graphics::setAlphaTest()
  290. {
  291. glDisable(GL_ALPHA_TEST);
  292. }
  293. bool Graphics::isAlphaTestEnabled()
  294. {
  295. return glIsEnabled(GL_ALPHA_TEST) == GL_TRUE;
  296. }
  297. Graphics::AlphaTestMode Graphics::getAlphaTestMode()
  298. {
  299. GLint func;
  300. glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
  301. switch (func)
  302. {
  303. case GL_LESS:
  304. return ALPHATEST_LESS;
  305. case GL_LEQUAL:
  306. return ALPHATEST_LEQUAL;
  307. case GL_EQUAL:
  308. return ALPHATEST_EQUAL;
  309. case GL_NOTEQUAL:
  310. return ALPHATEST_NOTEQUAL;
  311. case GL_GEQUAL:
  312. return ALPHATEST_GEQUAL;
  313. case GL_GREATER:
  314. return ALPHATEST_GREATER;
  315. default:
  316. return ALPHATEST_MAX_ENUM;
  317. }
  318. }
  319. unsigned char Graphics::getAlphaTestRef()
  320. {
  321. GLfloat ref;
  322. glGetFloatv(GL_ALPHA_TEST_REF, &ref);
  323. return ref * 255;
  324. }
  325. Image *Graphics::newImage(love::image::ImageData *data)
  326. {
  327. // Create the image.
  328. Image *image = new Image(data);
  329. bool success;
  330. try
  331. {
  332. success = image->load();
  333. }
  334. catch(love::Exception &)
  335. {
  336. image->release();
  337. throw;
  338. }
  339. if (!success)
  340. {
  341. image->release();
  342. return 0;
  343. }
  344. return image;
  345. }
  346. Image *Graphics::newImage(love::image::CompressedData *cdata)
  347. {
  348. // Create the image.
  349. Image *image = new Image(cdata);
  350. bool success;
  351. try
  352. {
  353. success = image->load();
  354. }
  355. catch(love::Exception &)
  356. {
  357. image->release();
  358. throw;
  359. }
  360. if (!success)
  361. {
  362. image->release();
  363. return 0;
  364. }
  365. return image;
  366. }
  367. Geometry *Graphics::newGeometry(const std::vector<vertex> &vertices)
  368. {
  369. return new Geometry(vertices);
  370. }
  371. Geometry *Graphics::newQuad(float x, float y, float w, float h, float sw, float sh)
  372. {
  373. return new Geometry(x, y, w, h, sw, sh);
  374. }
  375. Font *Graphics::newFont(love::font::Rasterizer *r, const Image::Filter &filter)
  376. {
  377. return new Font(r, filter);
  378. }
  379. SpriteBatch *Graphics::newSpriteBatch(Image *image, int size, int usage)
  380. {
  381. return new SpriteBatch(image, size, usage);
  382. }
  383. ParticleSystem *Graphics::newParticleSystem(Image *image, int size)
  384. {
  385. return new ParticleSystem(image, size);
  386. }
  387. Canvas *Graphics::newCanvas(int width, int height, Canvas::TextureType texture_type)
  388. {
  389. if (texture_type == Canvas::TYPE_HDR && !Canvas::isHDRSupported())
  390. throw Exception("HDR Canvases are not supported by your OpenGL implementation");
  391. while (GL_NO_ERROR != glGetError())
  392. /* clear opengl error flag */;
  393. Canvas *canvas = new Canvas(width, height, texture_type);
  394. GLenum err = canvas->getStatus();
  395. // everything ok, return canvas (early out)
  396. if (err == GL_FRAMEBUFFER_COMPLETE)
  397. return canvas;
  398. // create error message
  399. std::stringstream error_string;
  400. error_string << "Cannot create canvas: ";
  401. switch (err)
  402. {
  403. case GL_FRAMEBUFFER_UNSUPPORTED:
  404. error_string << "Not supported by your OpenGL implementation.";
  405. break;
  406. // remaining error codes are highly unlikely:
  407. case GL_FRAMEBUFFER_UNDEFINED:
  408. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  409. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  410. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  411. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  412. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  413. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  414. break;
  415. default:
  416. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  417. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  418. // knows.
  419. if (glGetError() == GL_NO_ERROR)
  420. error_string << "May not be supported by your OpenGL implementation.";
  421. // the remaining error is an indication of a serious fuckup since it should
  422. // only be returned if glCheckFramebufferStatus() was called with the wrong
  423. // arguments.
  424. else
  425. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  426. }
  427. canvas->release();
  428. throw Exception(error_string.str().c_str());
  429. return NULL; // never reached
  430. }
  431. Shader *Graphics::newShader(const Shader::ShaderSources &sources)
  432. {
  433. return new Shader(sources);
  434. }
  435. void Graphics::setColor(const Color &c)
  436. {
  437. gl.setColor(c);
  438. }
  439. Color Graphics::getColor() const
  440. {
  441. return gl.getColor();
  442. }
  443. void Graphics::setBackgroundColor(const Color &c)
  444. {
  445. gl.setClearColor(c);
  446. }
  447. Color Graphics::getBackgroundColor() const
  448. {
  449. return gl.getClearColor();
  450. }
  451. void Graphics::setFont(Font *font)
  452. {
  453. if (currentFont != 0)
  454. currentFont->release();
  455. currentFont = font;
  456. if (font != 0)
  457. currentFont->retain();
  458. }
  459. Font *Graphics::getFont() const
  460. {
  461. return currentFont;
  462. }
  463. void Graphics::setColorMask(bool r, bool g, bool b, bool a)
  464. {
  465. colorMask[0] = r;
  466. colorMask[1] = g;
  467. colorMask[2] = b;
  468. colorMask[3] = a;
  469. glColorMask((GLboolean) r, (GLboolean) g, (GLboolean) b, (GLboolean) a);
  470. }
  471. const bool *Graphics::getColorMask() const
  472. {
  473. return colorMask;
  474. }
  475. void Graphics::setBlendMode(Graphics::BlendMode mode)
  476. {
  477. const int gl_1_4 = GLEE_VERSION_1_4;
  478. GLenum func = GL_FUNC_ADD;
  479. GLenum src_rgb = GL_ONE;
  480. GLenum src_a = GL_ONE;
  481. GLenum dst_rgb = GL_ZERO;
  482. GLenum dst_a = GL_ZERO;
  483. switch (mode)
  484. {
  485. case BLEND_ALPHA:
  486. if (gl_1_4 || GLEE_EXT_blend_func_separate)
  487. {
  488. src_rgb = GL_SRC_ALPHA;
  489. src_a = GL_ONE;
  490. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  491. }
  492. else
  493. {
  494. // Fallback for OpenGL implementations without support for separate blend functions.
  495. // This will most likely only be used for the Microsoft software renderer and
  496. // since it's still stuck with OpenGL 1.1, the only expected difference is a
  497. // different alpha value when reading back the default framebuffer (newScreenshot).
  498. src_rgb = src_a = GL_SRC_ALPHA;
  499. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  500. }
  501. break;
  502. case BLEND_MULTIPLICATIVE:
  503. src_rgb = src_a = GL_DST_COLOR;
  504. dst_rgb = dst_a = GL_ZERO;
  505. break;
  506. case BLEND_PREMULTIPLIED:
  507. src_rgb = src_a = GL_ONE;
  508. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  509. break;
  510. case BLEND_SUBTRACTIVE:
  511. func = GL_FUNC_REVERSE_SUBTRACT;
  512. case BLEND_ADDITIVE:
  513. src_rgb = src_a = GL_SRC_ALPHA;
  514. dst_rgb = dst_a = GL_ONE;
  515. break;
  516. case BLEND_REPLACE:
  517. default:
  518. src_rgb = src_a = GL_ONE;
  519. dst_rgb = dst_a = GL_ZERO;
  520. break;
  521. }
  522. if (gl_1_4 || GLEE_ARB_imaging)
  523. glBlendEquation(func);
  524. else if (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract)
  525. glBlendEquationEXT(func);
  526. else
  527. {
  528. if (func == GL_FUNC_REVERSE_SUBTRACT)
  529. throw Exception("This graphics card does not support the subtractive blend mode!");
  530. // GL_FUNC_ADD is the default even without access to glBlendEquation, so that'll still work.
  531. }
  532. if (src_rgb == src_a && dst_rgb == dst_a)
  533. glBlendFunc(src_rgb, dst_rgb);
  534. else
  535. {
  536. if (gl_1_4)
  537. glBlendFuncSeparate(src_rgb, dst_rgb, src_a, dst_a);
  538. else if (GLEE_EXT_blend_func_separate)
  539. glBlendFuncSeparateEXT(src_rgb, dst_rgb, src_a, dst_a);
  540. else
  541. throw Exception("This graphics card does not support separated rgb and alpha blend functions!");
  542. }
  543. }
  544. Graphics::BlendMode Graphics::getBlendMode() const
  545. {
  546. const int gl_1_4 = GLEE_VERSION_1_4;
  547. GLint src_rgb, src_a, dst_rgb, dst_a;
  548. GLint equation = GL_FUNC_ADD;
  549. if (gl_1_4 || GLEE_EXT_blend_func_separate)
  550. {
  551. glGetIntegerv(GL_BLEND_SRC_RGB, &src_rgb);
  552. glGetIntegerv(GL_BLEND_SRC_ALPHA, &src_a);
  553. glGetIntegerv(GL_BLEND_DST_RGB, &dst_rgb);
  554. glGetIntegerv(GL_BLEND_DST_ALPHA, &dst_a);
  555. }
  556. else
  557. {
  558. glGetIntegerv(GL_BLEND_SRC, &src_rgb);
  559. glGetIntegerv(GL_BLEND_DST, &dst_rgb);
  560. src_a = src_rgb;
  561. dst_a = dst_rgb;
  562. }
  563. if (gl_1_4 || GLEE_ARB_imaging || (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract))
  564. glGetIntegerv(GL_BLEND_EQUATION, &equation);
  565. if (equation == GL_FUNC_REVERSE_SUBTRACT) // && src == GL_SRC_ALPHA && dst == GL_ONE
  566. return BLEND_SUBTRACTIVE;
  567. // Everything else has equation == GL_FUNC_ADD.
  568. else if (src_rgb == src_a && dst_rgb == dst_a)
  569. {
  570. if (src_rgb == GL_SRC_ALPHA && dst_rgb == GL_ONE)
  571. return BLEND_ADDITIVE;
  572. else if (src_rgb == GL_SRC_ALPHA && dst_rgb == GL_ONE_MINUS_SRC_ALPHA)
  573. return BLEND_ALPHA; // alpha blend mode fallback for very old OpenGL versions.
  574. else if (src_rgb == GL_DST_COLOR && dst_rgb == GL_ZERO)
  575. return BLEND_MULTIPLICATIVE;
  576. else if (src_rgb == GL_ONE && dst_rgb == GL_ONE_MINUS_SRC_ALPHA)
  577. return BLEND_PREMULTIPLIED;
  578. else if (src_rgb == GL_ONE && dst_rgb == GL_ZERO)
  579. return BLEND_REPLACE;
  580. }
  581. else if (src_rgb == GL_SRC_ALPHA && src_a == GL_ONE &&
  582. dst_rgb == GL_ONE_MINUS_SRC_ALPHA && dst_a == GL_ONE_MINUS_SRC_ALPHA)
  583. return BLEND_ALPHA;
  584. throw Exception("Unknown blend mode");
  585. }
  586. void Graphics::setDefaultFilter(const Image::Filter &f)
  587. {
  588. Image::setDefaultFilter(f);
  589. }
  590. const Image::Filter &Graphics::getDefaultFilter() const
  591. {
  592. return Image::getDefaultFilter();
  593. }
  594. void Graphics::setDefaultMipmapFilter(Image::FilterMode filter, float sharpness)
  595. {
  596. Image::setDefaultMipmapFilter(filter);
  597. Image::setDefaultMipmapSharpness(sharpness);
  598. }
  599. void Graphics::getDefaultMipmapFilter(Image::FilterMode *filter, float *sharpness) const
  600. {
  601. *filter = Image::getDefaultMipmapFilter();
  602. *sharpness = Image::getDefaultMipmapSharpness();
  603. }
  604. void Graphics::setLineWidth(float width)
  605. {
  606. lineWidth = width;
  607. }
  608. void Graphics::setLineStyle(Graphics::LineStyle style)
  609. {
  610. lineStyle = style;
  611. }
  612. void Graphics::setLine(float width, Graphics::LineStyle style)
  613. {
  614. setLineWidth(width);
  615. if (style == 0)
  616. return;
  617. setLineStyle(style);
  618. }
  619. float Graphics::getLineWidth() const
  620. {
  621. return lineWidth;
  622. }
  623. Graphics::LineStyle Graphics::getLineStyle() const
  624. {
  625. return lineStyle;
  626. }
  627. void Graphics::setPointSize(float size)
  628. {
  629. glPointSize((GLfloat)size);
  630. }
  631. void Graphics::setPointStyle(Graphics::PointStyle style)
  632. {
  633. if (style == POINT_SMOOTH)
  634. glEnable(GL_POINT_SMOOTH);
  635. else // love::POINT_ROUGH
  636. glDisable(GL_POINT_SMOOTH);
  637. }
  638. void Graphics::setPoint(float size, Graphics::PointStyle style)
  639. {
  640. if (style == POINT_SMOOTH)
  641. glEnable(GL_POINT_SMOOTH);
  642. else // POINT_ROUGH
  643. glDisable(GL_POINT_SMOOTH);
  644. glPointSize((GLfloat)size);
  645. }
  646. float Graphics::getPointSize() const
  647. {
  648. GLfloat size;
  649. glGetFloatv(GL_POINT_SIZE, &size);
  650. return (float)size;
  651. }
  652. Graphics::PointStyle Graphics::getPointStyle() const
  653. {
  654. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  655. return POINT_SMOOTH;
  656. else
  657. return POINT_ROUGH;
  658. }
  659. int Graphics::getMaxPointSize() const
  660. {
  661. GLint max;
  662. glGetIntegerv(GL_POINT_SIZE_MAX, &max);
  663. return (int)max;
  664. }
  665. void Graphics::print(const char *str, float x, float y , float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  666. {
  667. if (currentFont != 0)
  668. {
  669. std::string text(str);
  670. currentFont->print(text, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  671. }
  672. }
  673. void Graphics::printf(const char *str, float x, float y, float wrap, AlignMode align, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  674. {
  675. if (currentFont == 0)
  676. return;
  677. using std::string;
  678. using std::vector;
  679. string text(str);
  680. vector<string> lines_to_draw = currentFont->getWrap(text, wrap);
  681. glPushMatrix();
  682. static Matrix t;
  683. t.setTransformation(ceil(x), ceil(y), angle, sx, sy, ox, oy, kx, ky);
  684. glMultMatrixf((const GLfloat *)t.getElements());
  685. x = y = 0.0f;
  686. try
  687. {
  688. // now for the actual printing
  689. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  690. float letter_spacing = 0.0f;
  691. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  692. {
  693. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  694. switch (align)
  695. {
  696. case ALIGN_RIGHT:
  697. currentFont->print(*line_iter, ceil(x + (wrap - width)), ceil(y), 0.0f);
  698. break;
  699. case ALIGN_CENTER:
  700. currentFont->print(*line_iter, ceil(x + (wrap - width) / 2), ceil(y), 0.0f);
  701. break;
  702. case ALIGN_JUSTIFY:
  703. if (line_iter->length() > 1 && (line_iter+1) != line_end)
  704. letter_spacing = (wrap - width) / float(line_iter->length() - 1);
  705. else
  706. letter_spacing = 0.0f;
  707. currentFont->print(*line_iter, ceil(x), ceil(y), letter_spacing);
  708. break;
  709. case ALIGN_LEFT:
  710. default:
  711. currentFont->print(*line_iter, ceil(x), ceil(y), 0.0f);
  712. break;
  713. }
  714. y += currentFont->getHeight() * currentFont->getLineHeight();
  715. }
  716. }
  717. catch (love::Exception &)
  718. {
  719. glPopMatrix();
  720. throw;
  721. }
  722. glPopMatrix();
  723. }
  724. /**
  725. * Primitives
  726. **/
  727. void Graphics::point(float x, float y)
  728. {
  729. gl.bindTexture(0);
  730. glBegin(GL_POINTS);
  731. glVertex2f(x, y);
  732. glEnd();
  733. }
  734. // Calculate line boundary points u1 and u2. Sketch:
  735. // u1
  736. // -------------+---...___
  737. // | ```'''-- ---
  738. // p- - - - - - q- - . _ _ | w/2
  739. // | ` ' ' r +
  740. // -------------+---...___ | w/2
  741. // u2 ```'''-- ---
  742. //
  743. // u1 and u2 depend on four things:
  744. // - the half line width w/2
  745. // - the previous line vertex p
  746. // - the current line vertex q
  747. // - the next line vertex r
  748. //
  749. // u1/u2 are the intersection points of the parallel lines to p-q and q-r,
  750. // i.e. the point where
  751. //
  752. // (p + w/2 * n1) + mu * (q - p) = (q + w/2 * n2) + lambda * (r - q) (u1)
  753. // (p - w/2 * n1) + mu * (q - p) = (q - w/2 * n2) + lambda * (r - q) (u2)
  754. //
  755. // with n1,n2 being the normals on the segments p-q and q-r:
  756. //
  757. // n1 = perp(q - p) / |q - p|
  758. // n2 = perp(r - q) / |r - q|
  759. //
  760. // The intersection points can be calculated using cramers rule.
  761. static void pushIntersectionPoints(Vector *vertices, Vector *overdraw,
  762. int pos, int count, float hw, float overdraw_factor,
  763. const Vector &p, const Vector &q, const Vector &r)
  764. {
  765. // calculate line directions
  766. Vector s = (q - p);
  767. Vector t = (r - q);
  768. // calculate vertex displacement vectors
  769. Vector n1 = s.getNormal();
  770. Vector n2 = t.getNormal();
  771. n1.normalize();
  772. n2.normalize();
  773. float det_norm = n1 ^ n2; // will be close to zero if the angle between the normals is sharp
  774. n1 *= hw;
  775. n2 *= hw;
  776. // lines parallel -> assume intersection at displacement points
  777. if (fabs(det_norm) <= .03)
  778. {
  779. vertices[pos] = q - n2;
  780. vertices[pos+1] = q + n2;
  781. }
  782. // real intersection -> calculate boundary intersection points with cramers rule
  783. else
  784. {
  785. float det = s ^ t;
  786. Vector d = n1 - n2;
  787. Vector b = s - d; // s = q - p
  788. Vector c = s + d;
  789. float lambda = (b ^ t) / det;
  790. float mu = (c ^ t) / det;
  791. // ordering for GL_TRIANGLE_STRIP
  792. vertices[pos] = p + s*mu - n1; // u1
  793. vertices[pos+1] = p + s*lambda + n1; // u2
  794. }
  795. if (overdraw)
  796. {
  797. // displacement of the overdraw vertices
  798. Vector x = (vertices[pos] - q) * overdraw_factor;
  799. overdraw[pos] = vertices[pos];
  800. overdraw[pos+1] = vertices[pos] + x;
  801. overdraw[2*count-pos-2] = vertices[pos+1];
  802. overdraw[2*count-pos-1] = vertices[pos+1] - x;
  803. }
  804. }
  805. // precondition:
  806. // glEnableClientState(GL_VERTEX_ARRAY);
  807. static void draw_overdraw(Vector *overdraw, size_t count, float pixel_size, bool looping)
  808. {
  809. // if not looping, the outer overdraw vertices need to be displaced
  810. // to cover the line endings, i.e.:
  811. // +- - - - //- - + +- - - - - //- - - +
  812. // +-------//-----+ : +-------//-----+ :
  813. // | core // line | --> : | core // line | :
  814. // +-----//-------+ : +-----//-------+ :
  815. // +- - //- - - - + +- - - //- - - - - +
  816. if (!looping)
  817. {
  818. Vector s = overdraw[1] - overdraw[3];
  819. s.normalize();
  820. s *= pixel_size;
  821. overdraw[1] += s;
  822. overdraw[2*count-1] += s;
  823. Vector t = overdraw[count-1] - overdraw[count-3];
  824. t.normalize();
  825. t *= pixel_size;
  826. overdraw[count-1] += t;
  827. overdraw[count+1] += t;
  828. // we need to draw two more triangles to close the
  829. // overdraw at the line start.
  830. overdraw[2*count] = overdraw[0];
  831. overdraw[2*count+1] = overdraw[1];
  832. }
  833. // prepare colors:
  834. // even indices in overdraw* point to inner vertices => alpha = current-alpha,
  835. // odd indices point to outer vertices => alpha = 0.
  836. Color c = gl.getColor();
  837. Color *colors = new Color[2*count+2];
  838. for (size_t i = 0; i < 2*count+2; ++i)
  839. {
  840. colors[i] = c;
  841. // avoids branching. equiv to if (i%2 == 1) colors[i].a = 0;
  842. colors[i].a *= GLubyte(i % 2 == 0);
  843. }
  844. // draw faded out line halos
  845. glEnableClientState(GL_COLOR_ARRAY);
  846. glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
  847. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)overdraw);
  848. glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*count + 2 * int(!looping));
  849. glDisableClientState(GL_COLOR_ARRAY);
  850. // "if GL_COLOR_ARRAY is enabled, the value of the current color is
  851. // undefined after glDrawArrays executes"
  852. gl.setColor(c);
  853. delete[] colors;
  854. }
  855. void Graphics::polyline(const float *coords, size_t count)
  856. {
  857. Vector *vertices = new Vector[count]; // two vertices for every line end-point
  858. Vector *overdraw = NULL;
  859. Vector p,q,r;
  860. bool looping = (coords[0] == coords[count-2]) && (coords[1] == coords[count-1]);
  861. float halfwidth = lineWidth/2.f;
  862. float pixel_size = pixel_size_stack.back();
  863. float overdraw_factor = .0f;
  864. if (lineStyle == LINE_SMOOTH)
  865. {
  866. overdraw = new Vector[2*count+2];
  867. overdraw_factor = pixel_size / halfwidth;
  868. halfwidth = std::max(.0f, halfwidth - .25f*pixel_size);
  869. }
  870. // get line vertex boundaries
  871. // if not looping, extend the line at the beginning, else use last point as `p'
  872. r = Vector(coords[0], coords[1]);
  873. if (!looping)
  874. q = r * 2 - Vector(coords[2], coords[3]);
  875. else
  876. q = Vector(coords[count-4], coords[count-3]);
  877. for (size_t i = 0; i+3 < count; i += 2)
  878. {
  879. p = q;
  880. q = r;
  881. r = Vector(coords[i+2], coords[i+3]);
  882. pushIntersectionPoints(vertices, overdraw, i, count, halfwidth, overdraw_factor, p,q,r);
  883. }
  884. // if not looping, extend the line at the end, else use first point as `r'
  885. p = q;
  886. q = r;
  887. if (!looping)
  888. r += q - p;
  889. else
  890. r = Vector(coords[2], coords[3]);
  891. pushIntersectionPoints(vertices, overdraw, count-2, count, halfwidth, overdraw_factor, p,q,r);
  892. // end get line vertex boundaries
  893. // draw the core line
  894. gl.bindTexture(0);
  895. glEnableClientState(GL_VERTEX_ARRAY);
  896. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)vertices);
  897. glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
  898. // draw the line halo (antialiasing)
  899. if (lineStyle == LINE_SMOOTH)
  900. draw_overdraw(overdraw, count, pixel_size, looping);
  901. glDisableClientState(GL_VERTEX_ARRAY);
  902. // cleanup
  903. delete[] vertices;
  904. if (lineStyle == LINE_SMOOTH)
  905. delete[] overdraw;
  906. }
  907. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  908. {
  909. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  910. polygon(mode, coords, 5 * 2);
  911. }
  912. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  913. {
  914. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  915. if (points <= 0) points = 1;
  916. float angle_shift = (two_pi / points);
  917. float phi = .0f;
  918. float *coords = new float[2 * (points + 1)];
  919. for (int i = 0; i < points; ++i, phi += angle_shift)
  920. {
  921. coords[2*i] = x + radius * cosf(phi);
  922. coords[2*i+1] = y + radius * sinf(phi);
  923. }
  924. coords[2*points] = coords[0];
  925. coords[2*points+1] = coords[1];
  926. polygon(mode, coords, (points + 1) * 2);
  927. delete[] coords;
  928. }
  929. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  930. {
  931. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  932. if (points <= 0 || angle1 == angle2)
  933. return;
  934. // Oh, you want to draw a circle?
  935. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  936. {
  937. circle(mode, x, y, radius, points);
  938. return;
  939. }
  940. float angle_shift = (angle2 - angle1) / points;
  941. // Bail on precision issues.
  942. if (angle_shift == 0.0)
  943. return;
  944. float phi = angle1;
  945. int num_coords = (points + 3) * 2;
  946. float *coords = new float[num_coords];
  947. coords[0] = coords[num_coords - 2] = x;
  948. coords[1] = coords[num_coords - 1] = y;
  949. for (int i = 0; i <= points; ++i, phi += angle_shift)
  950. {
  951. coords[2 * (i+1)] = x + radius * cosf(phi);
  952. coords[2 * (i+1) + 1] = y + radius * sinf(phi);
  953. }
  954. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  955. if (mode == DRAW_LINE)
  956. {
  957. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  958. }
  959. else
  960. {
  961. gl.bindTexture(0);
  962. glEnableClientState(GL_VERTEX_ARRAY);
  963. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  964. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  965. glDisableClientState(GL_VERTEX_ARRAY);
  966. }
  967. delete[] coords;
  968. }
  969. /// @param mode the draw mode
  970. /// @param coords the coordinate array
  971. /// @param count the number of coordinates/size of the array
  972. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  973. {
  974. // coords is an array of a closed loop of vertices, i.e.
  975. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  976. if (mode == DRAW_LINE)
  977. {
  978. polyline(coords, count);
  979. }
  980. else
  981. {
  982. gl.bindTexture(0);
  983. glEnableClientState(GL_VERTEX_ARRAY);
  984. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  985. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  986. glDisableClientState(GL_VERTEX_ARRAY);
  987. }
  988. }
  989. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  990. {
  991. // Temporarily unbind the currently active canvas (glReadPixels reads the
  992. // active framebuffer, not the main one.)
  993. Canvas *curcanvas = Canvas::current;
  994. if (curcanvas)
  995. Canvas::bindDefaultCanvas();
  996. int w = getWidth();
  997. int h = getHeight();
  998. int row = 4*w;
  999. int size = row*h;
  1000. GLubyte *pixels = 0;
  1001. GLubyte *screenshot = 0;
  1002. try
  1003. {
  1004. pixels = new GLubyte[size];
  1005. screenshot = new GLubyte[size];
  1006. }
  1007. catch (std::exception &)
  1008. {
  1009. delete[] pixels;
  1010. delete[] screenshot;
  1011. if (curcanvas)
  1012. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1013. throw love::Exception("Out of memory.");
  1014. }
  1015. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1016. if (!copyAlpha)
  1017. {
  1018. // Replace alpha values with full opacity.
  1019. for (int i = 3; i < size; i += 4)
  1020. pixels[i] = 255;
  1021. }
  1022. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1023. GLubyte *src = pixels - row, *dst = screenshot + size;
  1024. for (int i = 0; i < h; ++i)
  1025. memcpy(dst-=row, src+=row, row);
  1026. delete[] pixels;
  1027. love::image::ImageData *img = 0;
  1028. try
  1029. {
  1030. img = image->newImageData(w, h, (void *) screenshot);
  1031. }
  1032. catch (love::Exception &)
  1033. {
  1034. delete[] screenshot;
  1035. if (curcanvas)
  1036. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1037. throw;
  1038. }
  1039. delete[] screenshot;
  1040. // Re-bind the active canvas, if necessary.
  1041. if (curcanvas)
  1042. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1043. return img;
  1044. }
  1045. std::string Graphics::getRendererInfo(Graphics::RendererInfo infotype) const
  1046. {
  1047. const char *infostr = 0;
  1048. switch (infotype)
  1049. {
  1050. case Graphics::RENDERER_INFO_NAME:
  1051. default:
  1052. infostr = "OpenGL";
  1053. break;
  1054. case Graphics::RENDERER_INFO_VERSION:
  1055. infostr = (const char *) glGetString(GL_VERSION);
  1056. break;
  1057. case Graphics::RENDERER_INFO_VENDOR:
  1058. infostr = (const char *) glGetString(GL_VENDOR);
  1059. break;
  1060. case Graphics::RENDERER_INFO_DEVICE:
  1061. infostr = (const char *) glGetString(GL_RENDERER);
  1062. break;
  1063. }
  1064. if (!infostr)
  1065. throw love::Exception("Cannot retrieve renderer information.");
  1066. return std::string(infostr);
  1067. }
  1068. void Graphics::push()
  1069. {
  1070. if (userMatrices == matrixLimit)
  1071. throw Exception("Maximum stack depth reached. (More pushes than pops?)");
  1072. glPushMatrix();
  1073. ++userMatrices;
  1074. pixel_size_stack.push_back(pixel_size_stack.back());
  1075. }
  1076. void Graphics::pop()
  1077. {
  1078. if (userMatrices < 1)
  1079. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  1080. glPopMatrix();
  1081. --userMatrices;
  1082. pixel_size_stack.pop_back();
  1083. }
  1084. void Graphics::rotate(float r)
  1085. {
  1086. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  1087. }
  1088. void Graphics::scale(float x, float y)
  1089. {
  1090. glScalef(x, y, 1);
  1091. pixel_size_stack.back() *= 2. / double(x + y);
  1092. }
  1093. void Graphics::translate(float x, float y)
  1094. {
  1095. glTranslatef(x, y, 0);
  1096. }
  1097. void Graphics::shear(float kx, float ky)
  1098. {
  1099. Matrix t;
  1100. t.setShear(kx, ky);
  1101. glMultMatrixf((const GLfloat *)t.getElements());
  1102. }
  1103. void Graphics::origin()
  1104. {
  1105. glLoadIdentity();
  1106. pixel_size_stack.back() = 1;
  1107. }
  1108. } // opengl
  1109. } // graphics
  1110. } // love