Graphics.cpp 28 KB

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