comparison Renderer/Engine/texture.cc @ 0:04e28d8d3c6f

first commit
author Daiki KINJYO <e085722@ie.u-ryukyu.ac.jp>
date Mon, 08 Nov 2010 01:23:25 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:04e28d8d3c6f
1 #include <iostream>
2 #include <SDL.h>
3 #include <SDL_opengl.h>
4 #include <SDL_image.h>
5 #include <libxml/parser.h>
6 using namespace std;
7
8 int power_of_two(int input)
9 {
10 int value = 1;
11
12 while ( value < input )
13 {
14 value <<= 1;
15 }
16 return value;
17 }
18
19 GLuint SDL_GL_LoadTexture(SDL_Surface *surface)
20 {
21 GLuint texture;
22 GLfloat texcoord[4];
23 int w, h;
24 SDL_Surface *image;
25 SDL_Rect area;
26 Uint32 saved_flags;
27 Uint8 saved_alpha;
28
29 /* Use the surface width and height expanded to powers of 2 */
30 w = power_of_two(surface->w);
31 h = power_of_two(surface->h);
32 texcoord[0] = 0.0f; /* Min X */
33 texcoord[1] = 0.0f; /* Min Y */
34 texcoord[2] = (GLfloat)surface->w / w; /* Max X */
35 texcoord[3] = (GLfloat)surface->h / h; /* Max Y */
36
37 image = SDL_CreateRGBSurface(
38 SDL_SWSURFACE,
39 w, h,
40 32,
41 #if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
42 0x000000FF,
43 0x0000FF00,
44 0x00FF0000,
45 0xFF000000
46 #else
47 0xFF000000,
48 0x00FF0000,
49 0x0000FF00,
50 0x000000FF
51 #endif
52 );
53 if ( image == NULL )
54 {
55 return 0;
56 }
57
58 /* Save the alpha blending attributes */
59 saved_flags = surface->flags&(SDL_SRCALPHA|SDL_RLEACCELOK);
60 saved_alpha = surface->format->alpha;
61 if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA )
62 {
63 SDL_SetAlpha(surface, 0, 0);
64 }
65 /* Copy the surface into the GL texture image */
66 area.x = 0;
67 area.y = 0;
68 area.w = surface->w;
69 area.h = surface->h;
70 SDL_BlitSurface(surface, &area, image, &area);
71
72 /* Restore the alpha blending attributes */
73 if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA )
74 {
75 SDL_SetAlpha(surface, saved_flags, saved_alpha);
76 }
77
78 /* Create an OpenGL texture for the image */
79 glGenTextures(1, &texture);
80 glBindTexture(GL_TEXTURE_2D, texture);
81 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
82 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
83 glTexImage2D(GL_TEXTURE_2D,
84 0,
85 GL_RGBA,
86 w, h,
87 0,
88 GL_RGBA,
89 GL_UNSIGNED_BYTE,
90 image->pixels);
91 SDL_FreeSurface(image); /* No longer needed */
92
93 return texture;
94 }