1 #include "cgltexture.h"
3 CglTexture::CglTexture(std::string name
)
6 GLuint texture
; // This is a handle to our texture object
7 SDL_Surface
*surface
; // This surface will tell us the details of the image
11 std::string filename
= name
+ ".bmp";
12 surface
= SDL_LoadBMP( filename
.c_str() );
15 // Check that the image's width is a power of 2
16 if ( (surface
->w
& (surface
->w
- 1)) != 0 ) {
17 throw std::runtime_error(filename
+ "'s width is not a power of 2");
20 // Also check if the height is a power of 2
21 if ( (surface
->h
& (surface
->h
- 1)) != 0 ) {
22 throw std::runtime_error(filename
+ "'s height is not a power of 2");
25 // get the number of channels in the SDL surface
26 nOfColors
= surface
->format
->BytesPerPixel
;
27 if (nOfColors
== 4) // contains an alpha channel
29 if (surface
->format
->Rmask
== 0x000000ff)
30 texture_format
= GL_RGBA
;
32 texture_format
= GL_BGRA
;
33 } else if (nOfColors
== 3) // no alpha channel
35 if (surface
->format
->Rmask
== 0x000000ff)
36 texture_format
= GL_RGB
;
38 texture_format
= GL_BGR
;
40 // this error should not go unhandled
41 throw std::runtime_error(filename
+ ": the image is not truecolor");
44 // Have OpenGL generate a texture object handle for us
45 glGenTextures( 1, &texture
);
47 // Bind the texture object
48 glBindTexture( GL_TEXTURE_2D
, texture
);
50 // Set the texture's stretching properties
51 glTexParameteri( GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
52 glTexParameteri( GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
54 // Edit the texture object's image data using the information SDL_Surface gives us
55 glTexImage2D( GL_TEXTURE_2D
, 0, nOfColors
, surface
->w
, surface
->h
, 0,
56 texture_format
, GL_UNSIGNED_BYTE
, surface
->pixels
);
58 throw std::runtime_error("could not load " + filename
);
61 // Free the SDL_Surface only if it was successfully created
63 SDL_FreeSurface( surface
);
69 CglTexture::~CglTexture()