Graphics.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. /**
  2. * Copyright (c) 2006-2012 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. {
  43. currentWindow = love::window::sdl::Window::getSingleton();
  44. resetBoundTexture();
  45. }
  46. Graphics::~Graphics()
  47. {
  48. if (currentFont != 0)
  49. currentFont->release();
  50. currentWindow->release();
  51. }
  52. const char *Graphics::getName() const
  53. {
  54. return "love.graphics.opengl";
  55. }
  56. bool Graphics::checkMode(int width, int height, bool fullscreen)
  57. {
  58. return currentWindow->checkWindowSize(width, height, fullscreen);
  59. }
  60. DisplayState Graphics::saveState()
  61. {
  62. DisplayState s;
  63. s.color = getColor();
  64. s.backgroundColor = getBackgroundColor();
  65. s.blendMode = getBlendMode();
  66. s.colorMode = getColorMode();
  67. //get line style
  68. s.lineStyle = lineStyle;
  69. //get the point size
  70. glGetFloatv(GL_POINT_SIZE, &s.pointSize);
  71. //get point style
  72. s.pointStyle = (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE) ? Graphics::POINT_SMOOTH : Graphics::POINT_ROUGH;
  73. //get scissor status
  74. s.scissor = (glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE);
  75. //do we have scissor, if so, store the box
  76. if (s.scissor)
  77. glGetIntegerv(GL_SCISSOR_BOX, s.scissorBox);
  78. return s;
  79. }
  80. void Graphics::restoreState(const DisplayState &s)
  81. {
  82. setColor(s.color);
  83. setBackgroundColor(s.backgroundColor);
  84. setBlendMode(s.blendMode);
  85. setColorMode(s.colorMode);
  86. setLine(lineWidth, s.lineStyle);
  87. setPoint(s.pointSize, s.pointStyle);
  88. if (s.scissor)
  89. setScissor(s.scissorBox[0], s.scissorBox[1], s.scissorBox[2], s.scissorBox[3]);
  90. else
  91. setScissor();
  92. }
  93. bool Graphics::setMode(int width, int height, WindowFlags *flags)
  94. {
  95. // This operation destroys the OpenGL context, so
  96. // we must save the state.
  97. DisplayState tempState;
  98. if (isCreated())
  99. tempState = saveState();
  100. // Unload all volatile objects. These must be reloaded after
  101. // the display mode change.
  102. Volatile::unloadAll();
  103. bool success = currentWindow->setWindow(width, height, flags);
  104. // Regardless of failure, we'll have to set up OpenGL once again.
  105. width = currentWindow->getWidth();
  106. height = currentWindow->getHeight();
  107. // Okay, setup OpenGL.
  108. // Enable blending
  109. glEnable(GL_BLEND);
  110. // "Normal" blending
  111. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  112. // Enable line/point smoothing.
  113. setLineStyle(LINE_SMOOTH);
  114. glEnable(GL_POINT_SMOOTH);
  115. glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
  116. // Enable textures
  117. glEnable(GL_TEXTURE_2D);
  118. // Set the viewport to top-left corner
  119. glViewport(0, 0, width, height);
  120. // Reset the projection matrix
  121. glMatrixMode(GL_PROJECTION);
  122. glLoadIdentity();
  123. // Set up orthographic view (no depth)
  124. glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
  125. // Reset modelview matrix
  126. glMatrixMode(GL_MODELVIEW);
  127. glLoadIdentity();
  128. // Set pixel row alignment
  129. glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
  130. // Reload all volatile objects.
  131. if (!Volatile::loadAll())
  132. std::cerr << "Could not reload all volatile objects." << std::endl;
  133. // Restore the display state.
  134. restoreState(tempState);
  135. // Get the maximum number of matrices
  136. // subtract a few to give the engine some room.
  137. glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &matrixLimit);
  138. matrixLimit -= 5;
  139. return success;
  140. }
  141. void Graphics::getMode(int &width, int &height, WindowFlags &flags)
  142. {
  143. currentWindow->getWindow(width, height, flags);
  144. }
  145. bool Graphics::toggleFullscreen()
  146. {
  147. int width, height;
  148. WindowFlags flags;
  149. currentWindow->getWindow(width, height, flags);
  150. flags.fullscreen = !flags.fullscreen;
  151. return setMode(width, height, &flags);
  152. }
  153. void Graphics::reset()
  154. {
  155. DisplayState s;
  156. discardStencil();
  157. Canvas::bindDefaultCanvas();
  158. PixelEffect::detach();
  159. restoreState(s);
  160. }
  161. void Graphics::clear()
  162. {
  163. glClear(GL_COLOR_BUFFER_BIT);
  164. glLoadIdentity();
  165. }
  166. void Graphics::present()
  167. {
  168. currentWindow->swapBuffers();
  169. }
  170. void Graphics::setIcon(Image *image)
  171. {
  172. currentWindow->setIcon(image->getData());
  173. }
  174. void Graphics::setCaption(const char *caption)
  175. {
  176. std::string title(caption);
  177. currentWindow->setWindowTitle(title);
  178. }
  179. int Graphics::getCaption(lua_State *L)
  180. {
  181. std::string title = currentWindow->getWindowTitle();
  182. lua_pushstring(L, title.c_str());
  183. return 1;
  184. }
  185. int Graphics::getWidth()
  186. {
  187. return currentWindow->getWidth();
  188. }
  189. int Graphics::getHeight()
  190. {
  191. return currentWindow->getHeight();
  192. }
  193. int Graphics::getRenderHeight()
  194. {
  195. if (Canvas::current)
  196. return Canvas::current->getHeight();
  197. return getHeight();
  198. }
  199. bool Graphics::isCreated()
  200. {
  201. return currentWindow->isCreated();
  202. }
  203. int Graphics::getModes(lua_State *L)
  204. {
  205. int n;
  206. love::window::Window::WindowSize **modes = currentWindow->getFullscreenSizes(n);
  207. if (modes == 0)
  208. return 0;
  209. lua_newtable(L);
  210. for (int i = 0; i < n ; i++)
  211. {
  212. lua_pushinteger(L, i+1);
  213. lua_newtable(L);
  214. // Inner table attribs.
  215. lua_pushstring(L, "width");
  216. lua_pushinteger(L, modes[i]->width);
  217. lua_settable(L, -3);
  218. lua_pushstring(L, "height");
  219. lua_pushinteger(L, modes[i]->height);
  220. lua_settable(L, -3);
  221. // Inner table attribs end.
  222. lua_settable(L, -3);
  223. delete modes[i];
  224. }
  225. delete[] modes;
  226. return 1;
  227. }
  228. void Graphics::setScissor(int x, int y, int width, int height)
  229. {
  230. glEnable(GL_SCISSOR_TEST);
  231. glScissor(x, getRenderHeight() - (y + height), width, height); // Compensates for the fact that our y-coordinate is reverse of OpenGLs.
  232. }
  233. void Graphics::setScissor()
  234. {
  235. glDisable(GL_SCISSOR_TEST);
  236. }
  237. int Graphics::getScissor(lua_State *L)
  238. {
  239. if (glIsEnabled(GL_SCISSOR_TEST) == GL_FALSE)
  240. return 0;
  241. GLint scissor[4];
  242. glGetIntegerv(GL_SCISSOR_BOX, scissor);
  243. lua_pushnumber(L, scissor[0]);
  244. lua_pushnumber(L, getRenderHeight() - (scissor[1] + scissor[3])); // Compensates for the fact that our y-coordinate is reverse of OpenGLs.
  245. lua_pushnumber(L, scissor[2]);
  246. lua_pushnumber(L, scissor[3]);
  247. return 4;
  248. }
  249. void Graphics::defineStencil()
  250. {
  251. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  252. glEnable(GL_STENCIL_TEST);
  253. glClear(GL_STENCIL_BUFFER_BIT);
  254. glStencilFunc(GL_ALWAYS, 1, 1);
  255. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  256. }
  257. void Graphics::useStencil(bool invert)
  258. {
  259. glStencilFunc(GL_EQUAL, (int)(!invert), 1); // invert ? 0 : 1
  260. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  261. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  262. }
  263. void Graphics::discardStencil()
  264. {
  265. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  266. glDisable(GL_STENCIL_TEST);
  267. }
  268. Image *Graphics::newImage(love::image::ImageData *data)
  269. {
  270. // Create the image.
  271. Image *image = new Image(data);
  272. bool success;
  273. try
  274. {
  275. success = image->load();
  276. }
  277. catch(love::Exception &e)
  278. {
  279. image->release();
  280. throw love::Exception(e.what());
  281. }
  282. if (!success)
  283. {
  284. image->release();
  285. return 0;
  286. }
  287. return image;
  288. }
  289. Quad *Graphics::newQuad(float x, float y, float w, float h, float sw, float sh)
  290. {
  291. Quad::Viewport v;
  292. v.x = x;
  293. v.y = y;
  294. v.w = w;
  295. v.h = h;
  296. return new Quad(v, sw, sh);
  297. }
  298. Font *Graphics::newFont(love::font::Rasterizer *r, const Image::Filter &filter)
  299. {
  300. Font *font = new Font(r, filter);
  301. // Load it and check for errors.
  302. if (!font)
  303. {
  304. delete font;
  305. return 0;
  306. }
  307. return font;
  308. }
  309. SpriteBatch *Graphics::newSpriteBatch(Image *image, int size, int usage)
  310. {
  311. SpriteBatch *t = NULL;
  312. try
  313. {
  314. t = new SpriteBatch(image, size, usage);
  315. }
  316. catch(love::Exception &e)
  317. {
  318. if (t) delete t;
  319. throw e;
  320. }
  321. return t;
  322. }
  323. ParticleSystem *Graphics::newParticleSystem(Image *image, int size)
  324. {
  325. return new ParticleSystem(image, size);
  326. }
  327. Canvas *Graphics::newCanvas(int width, int height, Canvas::TextureType texture_type)
  328. {
  329. if (texture_type == Canvas::TYPE_HDR && !Canvas::isHdrSupported())
  330. throw Exception("HDR Canvases are not supported by your OpenGL implementation");
  331. while (GL_NO_ERROR != glGetError())
  332. /* clear opengl error flag */;
  333. Canvas *canvas = new Canvas(width, height, texture_type);
  334. GLenum err = canvas->getStatus();
  335. // everything ok, return canvas (early out)
  336. if (err == GL_FRAMEBUFFER_COMPLETE)
  337. return canvas;
  338. // create error message
  339. std::stringstream error_string;
  340. error_string << "Cannot create canvas: ";
  341. switch (err)
  342. {
  343. case GL_FRAMEBUFFER_UNSUPPORTED:
  344. error_string << "Not supported by your OpenGL implementation.";
  345. break;
  346. // remaining error codes are highly unlikely:
  347. case GL_FRAMEBUFFER_UNDEFINED:
  348. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  349. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  350. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  351. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  352. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  353. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  354. break;
  355. default:
  356. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  357. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  358. // knows.
  359. if (glGetError() == GL_NO_ERROR)
  360. error_string << "May not be supported by your OpenGL implementation.";
  361. // the remaining error is an indication of a serious fuckup since it should
  362. // only be returned if glCheckFramebufferStatus() was called with the wrong
  363. // arguments.
  364. else
  365. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  366. }
  367. canvas->release();
  368. throw Exception(error_string.str().c_str());
  369. return NULL; // never reached
  370. }
  371. PixelEffect *Graphics::newPixelEffect(const std::string &code)
  372. {
  373. PixelEffect *effect = NULL;
  374. try
  375. {
  376. effect = new PixelEffect(code);
  377. }
  378. catch(love::Exception &e)
  379. {
  380. if (effect)
  381. delete effect;
  382. throw(e);
  383. }
  384. return effect;
  385. }
  386. void Graphics::setColor(const Color &c)
  387. {
  388. glColor4ubv(&c.r);
  389. }
  390. Color Graphics::getColor()
  391. {
  392. float c[4];
  393. glGetFloatv(GL_CURRENT_COLOR, c);
  394. Color t;
  395. t.r = (unsigned char)(255.0f*c[0]);
  396. t.g = (unsigned char)(255.0f*c[1]);
  397. t.b = (unsigned char)(255.0f*c[2]);
  398. t.a = (unsigned char)(255.0f*c[3]);
  399. return t;
  400. }
  401. void Graphics::setBackgroundColor(const Color &c)
  402. {
  403. glClearColor((float)c.r/255.0f, (float)c.g/255.0f, (float)c.b/255.0f, (float)c.a/255.0f);
  404. }
  405. Color Graphics::getBackgroundColor()
  406. {
  407. float c[4];
  408. glGetFloatv(GL_COLOR_CLEAR_VALUE, c);
  409. Color t;
  410. t.r = (unsigned char)(255.0f*c[0]);
  411. t.g = (unsigned char)(255.0f*c[1]);
  412. t.b = (unsigned char)(255.0f*c[2]);
  413. t.a = (unsigned char)(255.0f*c[3]);
  414. return t;
  415. }
  416. void Graphics::setFont(Font *font)
  417. {
  418. if (currentFont != 0)
  419. currentFont->release();
  420. currentFont = font;
  421. if (font != 0)
  422. currentFont->retain();
  423. }
  424. Font *Graphics::getFont()
  425. {
  426. return currentFont;
  427. }
  428. void Graphics::setBlendMode(Graphics::BlendMode mode)
  429. {
  430. if (GLEE_VERSION_1_4 || GLEE_ARB_imaging)
  431. {
  432. if (mode == BLEND_SUBTRACTIVE)
  433. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  434. else
  435. glBlendEquation(GL_FUNC_ADD);
  436. }
  437. else if (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract)
  438. {
  439. if (mode == BLEND_SUBTRACTIVE)
  440. glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
  441. else
  442. glBlendEquationEXT(GL_FUNC_ADD_EXT);
  443. }
  444. else
  445. {
  446. if (mode == BLEND_SUBTRACTIVE)
  447. throw Exception("This graphics card does not support the subtract blend mode!");
  448. // GL_FUNC_ADD is the default even without access to glBlendEquation, so that'll still work.
  449. }
  450. if (mode == BLEND_ALPHA)
  451. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  452. else if (mode == BLEND_MULTIPLICATIVE)
  453. glBlendFunc(GL_DST_COLOR, GL_ZERO);
  454. else if (mode == BLEND_PREMULTIPLIED)
  455. glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  456. else // mode == BLEND_ADDITIVE || mode == BLEND_SUBTRACTIVE
  457. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  458. }
  459. void Graphics::setColorMode(Graphics::ColorMode mode)
  460. {
  461. if (mode == COLOR_MODULATE)
  462. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  463. else if (mode == COLOR_COMBINE)
  464. {
  465. glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD_SIGNED);
  466. glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
  467. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
  468. }
  469. else // mode = COLOR_REPLACE
  470. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  471. }
  472. void Graphics::setDefaultImageFilter(const Image::Filter &f)
  473. {
  474. Image::setDefaultFilter(f);
  475. }
  476. Graphics::BlendMode Graphics::getBlendMode()
  477. {
  478. GLint dst, src, equation;
  479. glGetIntegerv(GL_BLEND_DST, &dst);
  480. glGetIntegerv(GL_BLEND_SRC, &src);
  481. glGetIntegerv(GL_BLEND_EQUATION, &equation);
  482. if (equation == GL_FUNC_REVERSE_SUBTRACT) // && src == GL_SRC_ALPHA && dst == GL_ONE
  483. return BLEND_SUBTRACTIVE;
  484. else if (src == GL_SRC_ALPHA && dst == GL_ONE) // && equation == GL_FUNC_ADD
  485. return BLEND_ADDITIVE;
  486. else if (src == GL_SRC_ALPHA && dst == GL_ONE_MINUS_SRC_ALPHA) // && equation == GL_FUNC_ADD
  487. return BLEND_ALPHA;
  488. else if (src == GL_DST_COLOR && dst == GL_ZERO) // && equation == GL_FUNC_ADD
  489. return BLEND_MULTIPLICATIVE;
  490. else if (src == GL_ONE && dst == GL_ONE_MINUS_SRC_ALPHA) // && equation == GL_FUNC_ADD
  491. return BLEND_PREMULTIPLIED;
  492. return BLEND_MAX_ENUM; // Should never be reached.
  493. }
  494. Graphics::ColorMode Graphics::getColorMode()
  495. {
  496. GLint mode;
  497. glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &mode);
  498. if (mode == GL_MODULATE)
  499. return COLOR_MODULATE;
  500. else if (mode == GL_COMBINE)
  501. return COLOR_COMBINE;
  502. else // mode == GL_REPLACE
  503. return COLOR_REPLACE;
  504. }
  505. const Image::Filter &Graphics::getDefaultImageFilter() const
  506. {
  507. return Image::getDefaultFilter();
  508. }
  509. void Graphics::setLineWidth(float width)
  510. {
  511. lineWidth = width;
  512. }
  513. void Graphics::setLineStyle(Graphics::LineStyle style)
  514. {
  515. lineStyle = style;
  516. }
  517. void Graphics::setLine(float width, Graphics::LineStyle style)
  518. {
  519. setLineWidth(width);
  520. if (style == 0)
  521. return;
  522. setLineStyle(style);
  523. }
  524. float Graphics::getLineWidth()
  525. {
  526. return lineWidth;
  527. }
  528. Graphics::LineStyle Graphics::getLineStyle()
  529. {
  530. return lineStyle;
  531. }
  532. void Graphics::setPointSize(float size)
  533. {
  534. glPointSize((GLfloat)size);
  535. }
  536. void Graphics::setPointStyle(Graphics::PointStyle style)
  537. {
  538. if (style == POINT_SMOOTH)
  539. glEnable(GL_POINT_SMOOTH);
  540. else // love::POINT_ROUGH
  541. glDisable(GL_POINT_SMOOTH);
  542. }
  543. void Graphics::setPoint(float size, Graphics::PointStyle style)
  544. {
  545. if (style == POINT_SMOOTH)
  546. glEnable(GL_POINT_SMOOTH);
  547. else // POINT_ROUGH
  548. glDisable(GL_POINT_SMOOTH);
  549. glPointSize((GLfloat)size);
  550. }
  551. float Graphics::getPointSize()
  552. {
  553. GLfloat size;
  554. glGetFloatv(GL_POINT_SIZE, &size);
  555. return (float)size;
  556. }
  557. Graphics::PointStyle Graphics::getPointStyle()
  558. {
  559. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  560. return POINT_SMOOTH;
  561. else
  562. return POINT_ROUGH;
  563. }
  564. int Graphics::getMaxPointSize()
  565. {
  566. GLint max;
  567. glGetIntegerv(GL_POINT_SIZE_MAX, &max);
  568. return (int)max;
  569. }
  570. void Graphics::print(const char *str, float x, float y , float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  571. {
  572. if (currentFont != 0)
  573. {
  574. std::string text(str);
  575. currentFont->print(text, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  576. }
  577. }
  578. void Graphics::printf(const char *str, float x, float y, float wrap, AlignMode align)
  579. {
  580. if (currentFont == 0)
  581. return;
  582. using namespace std;
  583. string text(str);
  584. vector<string> lines_to_draw = currentFont->getWrap(text, wrap);
  585. // now for the actual printing
  586. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  587. float letter_spacing = 0.0f;
  588. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  589. {
  590. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  591. switch (align)
  592. {
  593. case ALIGN_RIGHT:
  594. currentFont->print(*line_iter, ceil(x + wrap - width), ceil(y));
  595. break;
  596. case ALIGN_CENTER:
  597. currentFont->print(*line_iter, ceil(x + (wrap - width) / 2), ceil(y));
  598. break;
  599. case ALIGN_JUSTIFY:
  600. if (line_iter->length() > 1 && (line_iter+1) != line_end)
  601. letter_spacing = (wrap - width) / float(line_iter->length() - 1);
  602. else
  603. letter_spacing = 0.0f;
  604. currentFont->print(*line_iter, ceil(x), ceil(y), letter_spacing);
  605. break;
  606. case ALIGN_LEFT:
  607. default:
  608. currentFont->print(*line_iter, ceil(x), ceil(y));
  609. break;
  610. }
  611. y += currentFont->getHeight() * currentFont->getLineHeight();
  612. }
  613. }
  614. /**
  615. * Primitives
  616. **/
  617. void Graphics::point(float x, float y)
  618. {
  619. glDisable(GL_TEXTURE_2D);
  620. glBegin(GL_POINTS);
  621. glVertex2f(x, y);
  622. glEnd();
  623. glEnable(GL_TEXTURE_2D);
  624. }
  625. // Calculate line boundary points u1 and u2. Sketch:
  626. // u1
  627. // -------------+---...___
  628. // | ```'''-- ---
  629. // p- - - - - - q- - . _ _ | w/2
  630. // | ` ' ' r +
  631. // -------------+---...___ | w/2
  632. // u2 ```'''-- ---
  633. //
  634. // u1 and u2 depend on four things:
  635. // - the half line width w/2
  636. // - the previous line vertex p
  637. // - the current line vertex q
  638. // - the next line vertex r
  639. //
  640. // u1/u2 are the intersection points of the parallel lines to p-q and q-r,
  641. // i.e. the point where
  642. //
  643. // (p + w/2 * n1) + mu * (q - p) = (q + w/2 * n2) + lambda * (r - q) (u1)
  644. // (p - w/2 * n1) + mu * (q - p) = (q - w/2 * n2) + lambda * (r - q) (u2)
  645. //
  646. // with n1,n2 being the normals on the segments p-q and q-r:
  647. //
  648. // n1 = perp(q - p) / |q - p|
  649. // n2 = perp(r - q) / |r - q|
  650. //
  651. // The intersection points can be calculated using cramers rule.
  652. static void pushIntersectionPoints(Vector *vertices, Vector *overdraw,
  653. int pos, int count, float hw, float overdraw_factor,
  654. const Vector &p, const Vector &q, const Vector &r)
  655. {
  656. // calculate line directions
  657. Vector s = (q - p);
  658. Vector t = (r - q);
  659. // calculate vertex displacement vectors
  660. Vector n1 = s.getNormal();
  661. Vector n2 = t.getNormal();
  662. n1.normalize();
  663. n2.normalize();
  664. float det_norm = n1 ^ n2; // will be close to zero if the angle between the normals is sharp
  665. n1 *= hw;
  666. n2 *= hw;
  667. // lines parallel -> assume intersection at displacement points
  668. if (fabs(det_norm) <= .03)
  669. {
  670. vertices[pos] = q - n2;
  671. vertices[pos+1] = q + n2;
  672. }
  673. // real intersection -> calculate boundary intersection points with cramers rule
  674. else
  675. {
  676. float det = s ^ t;
  677. Vector d = n1 - n2;
  678. Vector b = s - d; // s = q - p
  679. Vector c = s + d;
  680. float lambda = (b ^ t) / det;
  681. float mu = (c ^ t) / det;
  682. // ordering for GL_TRIANGLE_STRIP
  683. vertices[pos] = p + s*mu - n1; // u1
  684. vertices[pos+1] = p + s*lambda + n1; // u2
  685. }
  686. if (overdraw)
  687. {
  688. // displacement of the overdraw vertices
  689. Vector x = (vertices[pos] - q) * overdraw_factor;
  690. overdraw[pos] = vertices[pos];
  691. overdraw[pos+1] = vertices[pos] + x;
  692. overdraw[2*count-pos-2] = vertices[pos+1];
  693. overdraw[2*count-pos-1] = vertices[pos+1] - x;
  694. }
  695. }
  696. // precondition:
  697. // glEnableClientState(GL_VERTEX_ARRAY);
  698. static void draw_overdraw(Vector *overdraw, size_t count, float pixel_size, bool looping)
  699. {
  700. // if not looping, the outer overdraw vertices need to be displaced
  701. // to cover the line endings, i.e.:
  702. // +- - - - //- - + +- - - - - //- - - +
  703. // +-------//-----+ : +-------//-----+ :
  704. // | core // line | --> : | core // line | :
  705. // +-----//-------+ : +-----//-------+ :
  706. // +- - //- - - - + +- - - //- - - - - +
  707. if (!looping)
  708. {
  709. Vector s = overdraw[1] - overdraw[3];
  710. s.normalize();
  711. s *= pixel_size;
  712. overdraw[1] += s;
  713. overdraw[2*count-1] += s;
  714. Vector t = overdraw[count-1] - overdraw[count-3];
  715. t.normalize();
  716. t *= pixel_size;
  717. overdraw[count-1] += t;
  718. overdraw[count+1] += t;
  719. // we need to draw two more triangles to close the
  720. // overdraw at the line start.
  721. overdraw[2*count] = overdraw[0];
  722. overdraw[2*count+1] = overdraw[1];
  723. }
  724. // prepare colors:
  725. // even indices in overdraw* point to inner vertices => alpha = current-alpha,
  726. // odd indices point to outer vertices => alpha = 0.
  727. GLfloat c[4];
  728. glGetFloatv(GL_CURRENT_COLOR, c);
  729. Color *colors = new Color[2*count+2];
  730. for (size_t i = 0; i < 2*count+2; ++i)
  731. {
  732. colors[i] = Color(GLubyte(c[0] * 255.f),
  733. GLubyte(c[1] * 255.f),
  734. GLubyte(c[2] * 255.f),
  735. // avoids branching. equiv to if (i%2 == 1) colors[i].a = 0;
  736. GLubyte(c[3] * 255.f) * GLubyte(i%2 == 0));
  737. }
  738. // draw faded out line halos
  739. glEnableClientState(GL_COLOR_ARRAY);
  740. glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
  741. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)overdraw);
  742. glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*count + 2 * int(!looping));
  743. glDisableClientState(GL_COLOR_ARRAY);
  744. // "if GL_COLOR_ARRAY is enabled, the value of the current color is
  745. // undefined after glDrawArrays executes"
  746. glColor4fv(c);
  747. delete[] colors;
  748. }
  749. void Graphics::polyline(const float *coords, size_t count)
  750. {
  751. Vector *vertices = new Vector[count]; // two vertices for every line end-point
  752. Vector *overdraw = NULL;
  753. Vector p,q,r;
  754. bool looping = (coords[0] == coords[count-2]) && (coords[1] == coords[count-1]);
  755. float halfwidth = lineWidth/2.f;
  756. float pixel_size = 1.f;
  757. float overdraw_factor = .0f;
  758. if (lineStyle == LINE_SMOOTH)
  759. {
  760. overdraw = new Vector[2*count+2];
  761. // TODO: is there a better way to get the pixel size at the current scale?
  762. GLfloat m[16];
  763. glGetFloatv(GL_MODELVIEW_MATRIX, m);
  764. float det = m[0]*m[5]*m[10] + m[4]*m[9]*m[2] + m[8]*m[1]*m[6];
  765. det -= m[2]*m[5]*m[8] + m[6]*m[9]*m[0] + m[10]*m[1]*m[4];
  766. pixel_size = 1.f / sqrt(det);
  767. overdraw_factor = pixel_size / halfwidth;
  768. halfwidth = std::max(.0f, halfwidth - .25f*pixel_size);
  769. }
  770. // get line vertex boundaries
  771. // if not looping, extend the line at the beginning, else use last point as `p'
  772. r = Vector(coords[0], coords[1]);
  773. if (!looping)
  774. q = r * 2 - Vector(coords[2], coords[3]);
  775. else
  776. q = Vector(coords[count-4], coords[count-3]);
  777. for (size_t i = 0; i+3 < count; i += 2)
  778. {
  779. p = q;
  780. q = r;
  781. r = Vector(coords[i+2], coords[i+3]);
  782. pushIntersectionPoints(vertices, overdraw, i, count, halfwidth, overdraw_factor, p,q,r);
  783. }
  784. // if not looping, extend the line at the end, else use first point as `r'
  785. p = q;
  786. q = r;
  787. if (!looping)
  788. r += q - p;
  789. else
  790. r = Vector(coords[2], coords[3]);
  791. pushIntersectionPoints(vertices, overdraw, count-2, count, halfwidth, overdraw_factor, p,q,r);
  792. // end get line vertex boundaries
  793. // draw the core line
  794. glDisable(GL_TEXTURE_2D);
  795. glEnableClientState(GL_VERTEX_ARRAY);
  796. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)vertices);
  797. glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
  798. // draw the line halo (antialiasing)
  799. if (lineStyle == LINE_SMOOTH)
  800. draw_overdraw(overdraw, count, pixel_size, looping);
  801. glDisableClientState(GL_VERTEX_ARRAY);
  802. glEnable(GL_TEXTURE_2D);
  803. // cleanup
  804. delete[] vertices;
  805. if (lineStyle == LINE_SMOOTH)
  806. delete[] overdraw;
  807. }
  808. void Graphics::triangle(DrawMode mode, float x1, float y1, float x2, float y2, float x3, float y3)
  809. {
  810. float coords[] = { x1,y1, x2,y2, x3,y3, x1,y1 };
  811. polygon(mode, coords, 4 * 2);
  812. }
  813. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  814. {
  815. quad(mode, x,y, x,y+h, x+w,y+h, x+w,y);
  816. }
  817. void Graphics::quad(DrawMode mode, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
  818. {
  819. float coords[] = { x1,y1, x2,y2, x3,y3, x4,y4, x1,y1 };
  820. polygon(mode, coords, 5 * 2);
  821. }
  822. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  823. {
  824. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  825. if (points <= 0) points = 1;
  826. float angle_shift = (two_pi / points);
  827. float phi = .0f;
  828. float *coords = new float[2 * (points + 1)];
  829. for (int i = 0; i < points; ++i, phi += angle_shift)
  830. {
  831. coords[2*i] = x + radius * cos(phi);
  832. coords[2*i+1] = y + radius * sin(phi);
  833. }
  834. coords[2*points] = coords[0];
  835. coords[2*points+1] = coords[1];
  836. polygon(mode, coords, (points + 1) * 2);
  837. delete[] coords;
  838. }
  839. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  840. {
  841. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  842. if (points <= 0 || angle1 == angle2)
  843. return;
  844. // Oh, you want to draw a circle?
  845. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  846. {
  847. circle(mode, x, y, radius, points);
  848. return;
  849. }
  850. float angle_shift = (angle2 - angle1) / points;
  851. // Bail on precision issues.
  852. if (angle_shift == 0.0)
  853. return;
  854. float phi = angle1;
  855. int num_coords = (points + 3) * 2;
  856. float *coords = new float[num_coords];
  857. coords[0] = coords[num_coords - 2] = x;
  858. coords[1] = coords[num_coords - 1] = y;
  859. for (int i = 0; i <= points; ++i, phi += angle_shift)
  860. {
  861. coords[2 * (i+1)] = x + radius * cos(phi);
  862. coords[2 * (i+1) + 1] = y + radius * sin(phi);
  863. }
  864. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  865. if (mode == DRAW_LINE)
  866. {
  867. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  868. }
  869. else
  870. {
  871. glDisable(GL_TEXTURE_2D);
  872. glEnableClientState(GL_VERTEX_ARRAY);
  873. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  874. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  875. glDisableClientState(GL_VERTEX_ARRAY);
  876. glEnable(GL_TEXTURE_2D);
  877. }
  878. delete[] coords;
  879. }
  880. /// @param mode the draw mode
  881. /// @param coords the coordinate array
  882. /// @param count the number of coordinates/size of the array
  883. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  884. {
  885. // coords is an array of a closed loop of vertices, i.e.
  886. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  887. if (mode == DRAW_LINE)
  888. {
  889. polyline(coords, count);
  890. }
  891. else
  892. {
  893. glDisable(GL_TEXTURE_2D);
  894. glEnableClientState(GL_VERTEX_ARRAY);
  895. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  896. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  897. glDisableClientState(GL_VERTEX_ARRAY);
  898. glEnable(GL_TEXTURE_2D);
  899. }
  900. }
  901. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image)
  902. {
  903. int w = getWidth();
  904. int h = getHeight();
  905. int row = 4*w;
  906. int size = row*h;
  907. GLubyte *pixels = new GLubyte[size];
  908. GLubyte *screenshot = new GLubyte[size];
  909. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  910. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  911. GLubyte *src = pixels - row, *dst = screenshot + size;
  912. for (int i = 0; i < h; ++i)
  913. {
  914. memcpy(dst-=row, src+=row, row);
  915. }
  916. love::image::ImageData *img = image->newImageData(w, h, (void *)screenshot);
  917. delete [] pixels;
  918. delete [] screenshot;
  919. return img;
  920. }
  921. void Graphics::push()
  922. {
  923. if (userMatrices == matrixLimit)
  924. throw Exception("Maximum stack depth reached.");
  925. glPushMatrix();
  926. ++userMatrices;
  927. }
  928. void Graphics::pop()
  929. {
  930. if (userMatrices < 1)
  931. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  932. glPopMatrix();
  933. --userMatrices;
  934. }
  935. void Graphics::rotate(float r)
  936. {
  937. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  938. }
  939. void Graphics::scale(float x, float y)
  940. {
  941. glScalef(x, y, 1);
  942. }
  943. void Graphics::translate(float x, float y)
  944. {
  945. glTranslatef(x, y, 0);
  946. }
  947. void Graphics::shear(float kx, float ky)
  948. {
  949. Matrix t;
  950. t.setShear(kx, ky);
  951. glMultMatrixf((const GLfloat *)t.getElements());
  952. }
  953. void Graphics::drawTest(Image *image, float x, float y, float a, float sx, float sy, float ox, float oy)
  954. {
  955. image->bind();
  956. // Buffer for transforming the image.
  957. vertex buf[4];
  958. Matrix t;
  959. t.translate(x, y);
  960. t.rotate(a);
  961. t.scale(sx, sy);
  962. t.translate(ox, oy);
  963. t.transform(buf, image->getVertices(), 4);
  964. const vertex *vertices = image->getVertices();
  965. glEnableClientState(GL_VERTEX_ARRAY);
  966. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  967. glVertexPointer(2, GL_FLOAT, sizeof(vertex), (GLvoid *)&buf[0].x);
  968. glTexCoordPointer(2, GL_FLOAT, sizeof(vertex), (GLvoid *)&vertices[0].s);
  969. glDrawArrays(GL_QUADS, 0, 4);
  970. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  971. glDisableClientState(GL_VERTEX_ARRAY);
  972. }
  973. bool Graphics::hasFocus()
  974. {
  975. return currentWindow->hasFocus();
  976. }
  977. } // opengl
  978. } // graphics
  979. } // love