Graphics.cpp 28 KB

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