PDA

View Full Version : Trouble creating chessboard with textures.



thealmightyone
03-30-2009, 07:12 AM
I'm trying to draw a black and white chessboard, with data stored in an array; however, when the square is actually drawn, it is most definitely not black and white. I'm not sure where I'm going wrong though, so am asking for help.


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>

#define nRows 64
#define nCols 64


void Display(void)
{
glClear(GL_COLOR_BUFFER_BIT);

glPushMatrix();
glTranslatef(0.0, 0.0, -10.0);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex2f(-1.0, -1.0);

glTexCoord2f(0.0, 1.0);
glVertex2f(-1.0, 1.0);

glTexCoord2f(1.0, 1.0);
glVertex2f(1.0, 1.0);

glTexCoord2f(1.0, 0.0);
glVertex2f(1.0, -1.0);
glEnd();
glPopMatrix();

glutSwapBuffers();
}


void Reshape(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 6.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


void Chess(void)
{
GLubyte TexBits [nRows][nCols][4];
int i, j, flag = 0;

for (i = 0; i < nRows; i++)
{
for (j = 0; j < nCols; j++)
{
if (j == 0)
flag = !flag;
flag = !flag;

TexBits[i][j][0] = flag*255;
TexBits[i][j][1] = flag*255;
TexBits[i][j][2] = flag*255;
TexBits[i][j][3] = 255;
}
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, nCols, nRows, 0, GL_RGB, GL_UNSIGNED_BYTE, TexBits);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glEnable(GL_TEXTURE_2D);
}


int main(int argc, char *argv[])
{
glutInit(&amp;argc, argv);
glutInitWindowSize(500, 500);

glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);

glutCreateWindow(argv[0]);

Chess();
glutReshapeFunc(Reshape);
glutDisplayFunc(Display);

glutMainLoop();

return 0;
}

ZbuffeR
03-30-2009, 07:46 AM
it is most definitely not black and white -> this is most definitely not very precise.

Anyway the problematic part can be this :
GLubyte TexBits [nRows][nCols][4]; // not guaranteed to be countinuous

Instead you have to declare a 1D array :
GLubyte TexBits [nRows*nCols*4];
And access line, column, color by hand, ie. TexBits[(i + j*nCols)*4 + 1] = 255;// "green part of i,j texel";

Maybe the row/column has to be reversed, but its does not matter for a square chessboard.


EDIT: thinking about this, your original code should work, not sure what can be the problem ...

ZbuffeR
03-30-2009, 08:05 AM
silly me :
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, nCols, nRows, 0, GL_RGB, GL_UNSIGNED_BYTE, TexBits);

you define a RGBA texture, so you should do :
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, nCols, nRows, 0, GL_RGBA, GL_UNSIGNED_BYTE, TexBits);