# include "image.hpp"
# include <stb_image.h>
// these never change so just put them here
float VERTICES [ 24 ] = {
// positions // texCoords
- 1.0f , 1.0f , 0.0f , 1.0f , // top left
- 1.0f , - 1.0f , 0.0f , 0.0f , // bottom left
1.0f , - 1.0f , 1.0f , 0.0f , // bottom right
- 1.0f , 1.0f , 0.0f , 1.0f , // top left
1.0f , - 1.0f , 1.0f , 0.0f , // bottom right
1.0f , 1.0f , 1.0f , 1.0f , // top right
} ;
unsigned int image_to_texture ( unsigned char * data , int width , int height , int nrComponents ) {
unsigned int textureID ;
glGenTextures ( 1 , & textureID ) ;
GLenum format = GL_RGB ;
switch ( nrComponents ) {
case 1 :
format = GL_RED ;
break ;
case 3 :
format = GL_RGB ;
break ;
case 4 :
format = GL_RGBA ;
break ;
default :
dbc : : sentinel ( $ F ( " Impossible nrComponents={} when loading image " , nrComponents ) ) ;
}
glBindTexture ( GL_TEXTURE_2D , textureID ) ;
glTexImage2D ( GL_TEXTURE_2D , 0 , format , width , height , 0 , format , GL_UNSIGNED_BYTE , data ) ;
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_WRAP_S , GL_REPEAT ) ;
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_WRAP_T , GL_REPEAT ) ;
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_LINEAR ) ;
glTexParameteri ( GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_LINEAR ) ;
return textureID ;
}
void Image : : load ( const std : : string & filename ) {
stbi_set_flip_vertically_on_load ( true ) ;
unsigned char * data = stbi_load ( filename . c_str ( ) , & width , & height , & nrComponents , 0 ) ;
dbc : : check ( data ! = NULL , " Failed to stb_load image. " ) ;
texture_id = image_to_texture ( data , width , height , nrComponents ) ;
stbi_image_free ( data ) ;
}
void Image : : render ( ) {
shader . use ( ) ;
shader . setInt ( " texture1 " , texture_id ) ;
glBindVertexArray ( image_vao ) ;
glBindTexture ( GL_TEXTURE_2D , texture_id ) ;
glDrawArrays ( GL_TRIANGLES , 0 , 6 ) ;
}
Image : : Image ( ) {
glGenVertexArrays ( 1 , & image_vao ) ;
glGenBuffers ( 1 , & image_vbo ) ;
glBindVertexArray ( image_vao ) ;
glBindBuffer ( GL_ARRAY_BUFFER , image_vbo ) ;
glBufferData ( GL_ARRAY_BUFFER , sizeof ( VERTICES ) , & VERTICES , GL_STATIC_DRAW ) ;
// position attrib
glVertexAttribPointer ( 0 , 2 , GL_FLOAT , GL_FALSE , 4 * sizeof ( float ) , ( void * ) 0 ) ;
glEnableVertexAttribArray ( 0 ) ;
// color attribute
glVertexAttribPointer ( 1 , 2 , GL_FLOAT , GL_FALSE , 4 * sizeof ( float ) , ( void * ) ( 2 * sizeof ( float ) ) ) ;
glEnableVertexAttribArray ( 1 ) ;
}