elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Librería sobre SDL
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Librería sobre SDL  (Leído 2,023 veces)
Kropt32

Desconectado Desconectado

Mensajes: 34


Ver Perfil
Librería sobre SDL
« en: 6 Octubre 2010, 18:05 pm »

Bueno, aquí dejo una parte de una librería sobre SDL para acelerar el proceso de crear una aplicación con SDL. Es un poco patatera y no tiene demasiadas cosas. Espero que sirva de algo y de pie a seguirla.

SVideo.h
Código
  1.  
  2. /**
  3. SVideo.h
  4. **/
  5.  
  6. #ifndef __S_VIDEO_H__
  7. #define __S_VIDEO_H__
  8.  
  9. #define SVIDEO_DEBUG
  10.  
  11. #include <SDL/SDL.h>
  12. #include <SDL/SDL_image.h>
  13. #include <SDL/SDL_ttf.h>
  14.  
  15. #ifdef SVIDEO_DEBUG
  16. #include <iostream>
  17. #endif
  18.  
  19. #include <vector>
  20. #include <string>
  21.  
  22. class SVideo
  23. {
  24. public :
  25. SVideo(int width, int height, int depth, bool fullscreen, bool initialize = true);
  26. ~SVideo();
  27.  
  28. // Gestión de fuentes
  29. int CreateFont(std::string font, int size);
  30. static int GetWidth(TTF_Font *font, std::string text);
  31. static int GetHeight(TTF_Font *font, std::string text);
  32. void DrawText(TTF_Font *font, std::string text, SDL_Color color, int x, int y);
  33. TTF_Font *GetFont(unsigned int index);
  34.  
  35. // Gestión de superficies
  36. int CreateSurface(std::string image);
  37. void DrawSurface(SDL_Surface *surface, int x, int y);
  38. void DrawSurface(SDL_Surface *surface, SDL_Rect rect);
  39. SDL_Surface *GetSurface(unsigned int index);
  40.  
  41. // Gestión del sistema de video
  42. void FlipScreen();
  43. void Wait(int milliseconds);
  44. void CleanScreen(SDL_Color color);
  45. int Initialize(int width, int height, int depth, bool fullscreen);
  46.  
  47. bool IsInitialized() const;
  48. SDL_Surface *GetScreen();
  49.  
  50. private :
  51. SDL_Surface *m_screen;
  52. SDL_Rect m_rectScreen;
  53. bool m_initialized;
  54.  
  55. // Fuentes
  56. std::vector<TTF_Font *> m_font;
  57.  
  58. // Superficies
  59. std::vector<SDL_Surface *> m_surface;
  60. };
  61.  
  62. #endif /* __S_VIDEO_H__ */
  63.  
  64.  

SVideo.cpp
Código
  1.  
  2. #include "SVideo.h"
  3.  
  4. SVideo::SVideo(int width, int height, int depth, bool fullscreen, bool initialize /*= true*/)
  5. : m_screen(NULL)
  6. , m_initialized(false)
  7. {
  8. if ( initialize )
  9. {
  10. if ( Initialize(width, height, depth, fullscreen) < 0 )
  11. {
  12. #ifdef SVIDEO_DEBUG
  13. std::cerr << "SVideo::SVideo() -> SDL Error: " << SDL_GetError() << "." << std::endl;
  14. #endif
  15.  
  16. return;
  17. }
  18. }
  19. }
  20.  
  21. SVideo::~SVideo()
  22. {
  23. for ( unsigned int i = 0; i < m_font.size(); i++ )
  24. {
  25. if ( m_font[i] )
  26. {
  27. TTF_CloseFont( m_font[i] );
  28. }
  29. }
  30.  
  31. for ( unsigned int i = 0; i < m_surface.size(); i++ )
  32. {
  33. if ( m_surface[i] )
  34. {
  35. SDL_FreeSurface( m_surface[i] );
  36. }
  37. }
  38.  
  39. if ( m_screen )
  40. {
  41. SDL_FreeSurface(m_screen);
  42. }
  43. }
  44.  
  45. /**
  46. A partir de una cadena que indica el nombre de la fuente
  47. y el tamaño, crea un TTF_Font en la clase SVideo.
  48. Devuelve el índice de la fuente guardada en el vector.
  49. Devuelve -1 si a habido un error.
  50. @font: Cadena de la ruta de la fuente.
  51. @size: Tamaño de la fuente.
  52. **/
  53. int SVideo::CreateFont(std::string font, int size)
  54. {
  55. m_font.push_back(TTF_OpenFont(font.c_str(), size));
  56.  
  57. unsigned int index = m_font.size() - 1;
  58.  
  59. if ( m_font[index] == NULL )
  60. {
  61. // No se creó bien, se borra y devuelve error.
  62. #ifdef SVIDEO_DEBUG
  63. std::cerr << "SVideo::CreateFont() -> SDL Error: " << SDL_GetError() << "." << std::endl;
  64. #endif
  65. m_font.erase(m_font.begin() + index);
  66. return -1;
  67. }
  68.  
  69. // Si se crea bien, se devuelve su índice.
  70. return index;
  71. }
  72.  
  73. /**
  74. Devuelve el ancho en píxeles de un texto.
  75. @font: Fuente de tipo TTF_Font.
  76. @text: Texto que se quiere medir.
  77. **/
  78. int SVideo::GetWidth(TTF_Font *font, std::string text)
  79. {
  80. if ( font == NULL )
  81. {
  82. return -1;
  83. }
  84.  
  85. int w, h;
  86. TTF_SizeUTF8(font, text.c_str(), &w, &h);
  87.  
  88. return w;
  89. }
  90.  
  91. /**
  92. Devuelve el alto en píxeles de un texto.
  93. Devuelve -1 si hay fallo.
  94. @font: Fuente de tipo TTF_Font.
  95. @text: Texto que se quiere medir.
  96. **/
  97. int SVideo::GetHeight(TTF_Font *font, std::string text)
  98. {
  99. if ( font == NULL )
  100. {
  101. return -1;
  102. }
  103.  
  104. int w, h;
  105. TTF_SizeUTF8(font, text.c_str(), &w, &h);
  106.  
  107. return h;
  108. }
  109.  
  110. /**
  111. Dibuja un texto.
  112. @font: Fuente de tipo TTF_Font.
  113. @text: Texto que se quiere escribir.
  114. @color: Color del texto
  115. @x: Posición horizontal.
  116. @y: Posición vertical.
  117. **/
  118. void SVideo::DrawText(TTF_Font *font, std::string text, SDL_Color color, int x, int y)
  119. {
  120. if ( font == NULL )
  121. {
  122. return;
  123. }
  124.  
  125. SDL_Surface *textSurface;
  126.  
  127. textSurface = TTF_RenderText_Blended(font, text.c_str(), color);
  128.  
  129. SDL_Rect dest;
  130.  
  131. dest.x = x;
  132. dest.y = y;
  133. dest.h = textSurface->h;
  134. dest.w = textSurface->w;
  135.  
  136. if (SDL_BlitSurface(textSurface, NULL, m_screen, &dest) < 0 )
  137. {
  138. #ifdef SVIDEO_DEBUG
  139. std::cerr << "SVideo::DrawText() -> SDL Error: " << SDL_GetError() << "." << std::endl;
  140. #endif
  141. return;
  142. }
  143.  
  144. SDL_FreeSurface(textSurface);
  145. }
  146.  
  147. /**
  148. Devuelve una fuente guardada en el vector.
  149. @index: Índice de la fuente en el vector.
  150. **/
  151. TTF_Font *SVideo::GetFont(unsigned int index)
  152. {
  153. if ( index < m_font.size() )
  154. {
  155. return m_font[index];
  156. }
  157.  
  158. return NULL;
  159. }
  160.  
  161. /**
  162. crea una superficie en el vector de superficies.
  163. Devuelve el índice de la superficie.
  164. @image: Ruta de la imagen.
  165. **/
  166. int SVideo::CreateSurface(std::string image)
  167. {
  168. m_surface.push_back(IMG_Load(image.c_str()));
  169.  
  170. unsigned int index = m_surface.size() - 1;
  171.  
  172. if ( m_surface[index] == NULL )
  173. {
  174. // No se creó bien, se borra y devuelve error.
  175. #ifdef SVIDEO_DEBUG
  176. std::cerr << "SVideo::CreateSurface() -> SDL Error: " << SDL_GetError() << "." << std::endl;
  177. #endif
  178. m_surface.erase(m_surface.begin() + index);
  179. return -1;
  180. }
  181.  
  182. // Si se crea bien, se devuelve su índice.
  183. return index;
  184. }
  185.  
  186. /**
  187. Dibuja una superficie en la pantalla principal.
  188. @surface: Superficie a dibujar.
  189. @x: Posición horizontal.
  190. @y: Posición vertical.
  191. **/
  192. void SVideo::DrawSurface(SDL_Surface *surface, int x, int y)
  193. {
  194. SDL_Rect _rect = { x, y, surface->w, surface->h };
  195. SDL_BlitSurface(surface, NULL, m_screen, &_rect);
  196. }
  197.  
  198. /**
  199. Dibuja una superficie en la pantalla principal.
  200. @surface: Superficie a dibujar.
  201. @rect: Rectángulo
  202. **/
  203. void SVideo::DrawSurface(SDL_Surface *surface, SDL_Rect rect)
  204. {
  205. SDL_BlitSurface(surface, NULL, m_screen, &rect);
  206. }
  207.  
  208. /**
  209. Devuelve una superficie creada.
  210. @index: Índice de la superficie en el vector.
  211. **/
  212. SDL_Surface *SVideo::GetSurface(unsigned int index)
  213. {
  214. if ( index < m_surface.size() )
  215. {
  216. return m_surface[index];
  217. }
  218.  
  219. return NULL;
  220. }
  221.  
  222. /**
  223. Muestra el buffer escondido.
  224. **/
  225. void SVideo::FlipScreen()
  226. {
  227. SDL_Flip(m_screen);
  228. }
  229.  
  230. /**
  231. Hace una pausa.
  232. @milliseconds: Milisegundos de pausa.
  233. **/
  234. void SVideo::Wait(int milliseconds)
  235. {
  236. SDL_Delay(milliseconds);
  237. }
  238.  
  239. /**
  240. Limpia la pantalla con un color.
  241. @color: Color de borrado.
  242. **/
  243. void SVideo::CleanScreen(SDL_Color color)
  244. {
  245. SDL_FillRect(m_screen, &m_rectScreen, SDL_MapRGB(m_screen->format, color.r, color.g, color.b));
  246. }
  247.  
  248. /**
  249. Inicia todo el sistema de video.
  250.  
  251. Devuelve:
  252. < 0 Si hay error.
  253. 0 Si ha ido bien.
  254. **/
  255. int SVideo::Initialize(int width, int height, int depth, bool fullscreen)
  256. {
  257. m_initialized = false;
  258.  
  259. /** Video **/
  260. if ( SDL_Init(SDL_INIT_VIDEO) == -1 )
  261. {
  262. return -1;
  263. }
  264. atexit(SDL_Quit);
  265.  
  266. if ( fullscreen ) m_screen = SDL_SetVideoMode(width, height, depth, SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
  267. else m_screen = SDL_SetVideoMode(width, height, depth, SDL_SWSURFACE | SDL_DOUBLEBUF);
  268.  
  269. if (m_screen == NULL)
  270. {
  271. return -2;
  272. }
  273.  
  274. m_rectScreen.x = 0;
  275. m_rectScreen.y = 0;
  276. m_rectScreen.w = width;
  277. m_rectScreen.h = height;
  278.  
  279. /** Textos **/
  280. if (TTF_Init() == -1)
  281. {
  282. return -3;
  283. }
  284. atexit(TTF_Quit);
  285.  
  286. m_initialized = true;
  287.  
  288. return 0;
  289. }
  290.  
  291. /**
  292. Devuelve si el sistema está inicializado.
  293. **/
  294. bool SVideo::IsInitialized() const
  295. {
  296. return ( m_screen != NULL && m_initialized );
  297. }
  298.  
  299. /**
  300. Devuelve la pantalla principal.
  301. **/
  302. SDL_Surface *SVideo::GetScreen()
  303. {
  304. return m_screen;
  305. }
  306.  
  307.  

Por supuesto le falta infinidad de cosas. Sugerencias, etc.

Aplicación con SDL pura.
Código
  1.  
  2. #include <SDL/SDL.h>
  3. #include <SDL/SDL_image.h>
  4. #include <SDL/SDL_ttf.h>
  5.  
  6. using namespace std;
  7.  
  8. int main(int arc, char *argv[])
  9. {
  10. SDL_Event evento;
  11. bool salida = false;
  12. SDL_Rect rectPantalla;
  13. SDL_Surface *pantalla;
  14.  
  15. SDL_Color _blanco = { 255, 255, 255 };
  16. SDL_Color _negro = { 0, 0, 0 };
  17.  
  18. if ( SDL_Init(SDL_INIT_VIDEO) == -1 )
  19. {
  20. return -1;
  21. }
  22. atexit(SDL_Quit);
  23.  
  24. if ((pantalla = SDL_SetVideoMode(600, 200, 16, SDL_SWSURFACE | SDL_DOUBLEBUF)) == NULL)
  25. {
  26. return -1;
  27. }
  28.  
  29. rectPantalla.x = 0;
  30. rectPantalla.y = 0;
  31. rectPantalla.w = 600;
  32. rectPantalla.h = 200;
  33.  
  34. if (TTF_Init() == -1)
  35. {
  36. return -1;
  37. }
  38. atexit(TTF_Quit);
  39.  
  40. TTF_Font *miFuente = TTF_OpenFont("verdana.ttf", 50);
  41. if ( miFuente == NULL )
  42. {
  43. return -1;
  44. }
  45.  
  46. SDL_Surface *miGrafico = IMG_Load("grafico.png");
  47. if ( miGrafico == NULL )
  48. {
  49. return -1;
  50. }
  51.  
  52. while ( !salida )
  53. {
  54. while (SDL_PollEvent(&evento))
  55. {
  56. if ( evento.type == SDL_QUIT ) salida = true;
  57. }
  58.  
  59. int w, h;
  60. TTF_SizeUTF8(miFuente, "Mi Texto.", &w, &h);
  61.  
  62. SDL_Surface *textoSurface = TTF_RenderText_Blended(miFuente, "Mi Texto.", _blanco);
  63.  
  64. SDL_Rect rectTexto;
  65.  
  66. rectTexto.x = 600 / 2 - w / 2;
  67. rectTexto.y = 20;
  68. rectTexto.h = textoSurface->h;
  69. rectTexto.w = textoSurface->w;
  70.  
  71. SDL_BlitSurface(textoSurface, NULL, pantalla, &rectTexto);
  72. SDL_FreeSurface(textoSurface);
  73.  
  74. SDL_Rect rectGrafico;
  75. rectGrafico.x = 3;
  76. rectGrafico.y = 3;
  77. rectGrafico.w = miGrafico->w;
  78. rectGrafico.h = miGrafico->h;
  79.  
  80. SDL_BlitSurface(miGrafico, NULL, pantalla, &rectGrafico);
  81.  
  82. SDL_Flip(pantalla);
  83. SDL_Delay(30);
  84. }
  85.  
  86. TTF_CloseFont(miFuente);
  87. SDL_FreeSurface(miGrafico);
  88. SDL_FreeSurface(pantalla);
  89.  
  90. return EXIT_SUCCESS;
  91.  
  92.  


Aplicación con SVideo
Código
  1.  
  2. #include "SVideo.h"
  3.  
  4. using namespace std;
  5. typedef int FUENTE;
  6. typedef int GRAFICO;
  7.  
  8. int main(int arc, char *argv[])
  9. {
  10. SDL_Event evento;
  11. bool salida = false;
  12.  
  13. SDL_Color _blanco = { 255, 255, 255 };
  14. SDL_Color _negro = { 0, 0, 0 };
  15.  
  16. SVideo *video = new SVideo(600, 200, 16, false);
  17.  
  18. if ( !video->IsInitialized() )
  19. {
  20. std::cout << "Error iniciando." << std::endl;
  21. return -1;
  22. }
  23.  
  24. FUENTE miFuente;
  25. if ((miFuente = video->CreateFont("verdana.ttf", 50)) == -1)
  26. {
  27. std::cout << "Error creando fuente." << std::endl;
  28. delete video;
  29. return -1;
  30. }
  31.  
  32. GRAFICO miGrafico;
  33. if ((miGrafico = video->CreateSurface("grafico.png")) == -1)
  34. {
  35. std::cout << "Error creando gráfico." << std::endl;
  36. delete video;
  37. return -1;
  38. }
  39.  
  40. while ( !salida )
  41. {
  42. while (SDL_PollEvent(&evento))
  43. {
  44. if ( evento.type == SDL_QUIT ) salida = true;
  45. }
  46.  
  47. video->DrawText(video->GetFont(miFuente), "Mi Texto.", _blanco, (600 / 2)-(video->GetWidth(video->GetFont(miFuente), "Mi Texto.") / 2), 20);
  48. video->DrawSurface(video->GetSurface(miGrafico), 3, 3);
  49. video->FlipScreen();
  50. video->Wait(30);
  51. }
  52.  
  53. delete video;
  54.  
  55. return EXIT_SUCCESS;
  56. }
  57.  
  58.  


« Última modificación: 6 Octubre 2010, 23:33 pm por Kropt32 » En línea

En las pistolas, fíjense, a cada disparo el cañon recula, como asustado por lo que acaba de hacer.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
duda sobre libreria VorbisDotNet
.NET (C#, VB.NET, ASP)
CH4ØZ 4 2,696 Último mensaje 25 Septiembre 2011, 07:31 am
por CH4ØZ
(Petición) Tutorial sobre la librería LWJGL3
Java
Seyro97 4 3,136 Último mensaje 2 Abril 2015, 04:12 am
por Seyro97
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines