Hi every1!
I’m a n00b w/ OpenGL and what I’m trying to do is just display an image on a window (that comes from a .ppm file), in C++. However, I’m just getting a black screen, and no errors.
I’ve read all posts in here regarding similar issues, and have taken a look at the OpenGL Programming Guide as well, but still I’m confused w/ what could be wrong.
Following the code and the .ppm file. Appreciate any answers!
#include <windows.h>
#include <glut.h>
#include <fstream>
#include <string.h>
using namespace std;
GLbyte *pImage = NULL, *image = NULL;
GLint iWidth, iHeight, iComponents;
GLenum eFormat;
char *getNextToken(ifstream *arq){
char c;
char token[1024];
while((c=arq->get()) == '#'){
arq->getline(token, 1024);
}
token[0]=c;
(*arq)>>&token[1];
arq->get();
char *temp = new char[strlen(token)];
strcpy(temp, token);
return temp;
}
GLbyte* ltLoadPNM(const char *fileName, GLint *width, GLint *height, GLint *components, GLenum *format){
ifstream arq(fileName, ios::binary);
char *header = getNextToken(&arq);
char *swidth = getNextToken(&arq);
char *sheight = getNextToken(&arq);
char *smaxValue = getNextToken(&arq);
*width = atoi(swidth);
*height = atoi(sheight);
*components = GL_RGB8;
*format = GL_RGB8;
int length = *width * *height * 3;
int i=0;
GLbyte *pixels = new GLbyte[length];
GLbyte *pxs[3];
int w = length/3;
pxs[0] = new GLbyte[w];
pxs[1] = new GLbyte[w];
pxs[2] = new GLbyte[w];
int j=0;
if(strcmp(header, "P3") == 0){
while(j < w){
char *num = getNextToken(&arq);
pxs[0][j] = atoi(num);
num = getNextToken(&arq);
pxs[1][j] = atoi(num);
num = getNextToken(&arq);
pxs[2][j] = atoi(num);
j++;
}
} else {
while(j < w){
pxs[0][j] = arq.get();
pxs[1][j] = arq.get();
pxs[2][j] = arq.get();
j++;
}
}
w = *width;
for(int y= *height - 1; y>0; y--){
for(int x=0; x<w; x++){
pixels[i++] = pxs[0][x + y*w];
pixels[i++] = pxs[1][x + y*w];
pixels[i++] = pxs[2][x + y*w];
}
}
return pixels;
}
void ChangeSize(int w, int h){
if(h == 0)
h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0f, (GLfloat) w, 0.0, (GLfloat) h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void init (void){
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
pImage = image = ltLoadPNM("image01.ppm", &iWidth, &iHeight, &iComponents, &eFormat);
}
void finish(void){
if(pImage != image){
free(pImage);
}
free(image);
}
void RenderScene(void){
glClear(GL_COLOR_BUFFER_BIT);
glRasterPos2i(0, 0);
if(image != NULL){
if(pImage == NULL)
pImage = image;
glDrawPixels(iWidth, iHeight, GL_RGB, GL_UNSIGNED_BYTE, pImage);
}
glutSwapBuffers();
}
void restore(){
pImage = NULL;
}
int main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GL_DOUBLE);
glutInitWindowSize(400, 600);
glutCreateWindow("Image Loading Test");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
init();
glutMainLoop();
finish();
return 0;
}