PROBLEMS with TEXTURE and .plg files !!!!
Here is the problem..
I call a .plg file and a .bmp file to make a texture.
The problem is that when i put the texture, it doesnt write the little details of the image... Like a car for example.. it doesnt write the windows, or the the door..
Can somebody see what is going wrong with my code.. I dont what else to do!!!!
The problem i think is in the DrawScene function.
####################################################
####################################################
#include <gl\glut.h>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include <dir.h>
#define BUFFERSIZE 100
#define BLACK 0.0, 0.0, 0.0
#define WHITE 1.0, 1.0, 1.0
// ********* Tipos *********
typedef struct _worldPoint {
double x, y, z;
} WorldPoint;
typedef double WorldType;
typedef struct _TPolyDesc
{
int offset;
BYTE vertexes;
} TPolyDesc;
// ********* Globais *********
GLfloat Branca[] = {1.0, 1.0, 1.0, 1.0}; // Cores e Posicao das Luzes
GLfloat Cinza[] = {0.8, 0.8, 0.8, 1.0};
GLfloat PosLuz[] = {0.0, 1.0, 10.0, 1.0};
int VMODE = 0; // grid = 1, textura = 0
int NPOINTS, NPOLY; // numero de pontos, nro de polígonos
WorldPoint V_POINTS[30000];
TPolyDesc V_POLYDESCS[50000]; // offset -> local no array POLYCOORDS onde o polígono inicia,
int V_POLYCOORDS[200000]; // coordenadas dos polígonos
static WorldType FOV = 89, ZN = 1.0, ZF = 1000; // Define a perspectiva
int xsize = 600; // Dimensões da janela do programa
int ysize = 600;
float xMin, yMin, zMin, xMax, yMax, zMax, // da cena
Zoom = -10.0; // Fator de zoom inicial
int ROTX = 270, /* rotacao em x */
ROTZ = 270, /* rotacao em z */
ROTY = 0, /* rotacao em y */
pos_x =0, /* guarda posicao do mouse */
pos_y =0; /* guarda posicao do mouse */
GLuint texture[1]; // ID que o OpenGL da para a textura
struct Image { // Imagem - contem altura, largura, e dado
unsigned long sizeX;
unsigned long sizeY;
char *data;
};
typedef struct Image Image;
static int rotate = 0, saved_x, saved_y;
GLuint filter; // Which Filter To Use
/***********Salva a posição do ponteiro do mouse quando este é clicado********/
//Código baseado no código disponibilizado no site "nehe.gamedev.net"
void salvaposicao(int button, int state, int x, int y) {
switch(button){
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN) {
saved_x = x;
saved_y = y;
rotate = 1;
} else {
rotate = 0;
}
break;
}
}
/********** Calcula o angulo que o objeto rodou desde o ultimo update ************/
//Código baseado no código disponibilizado no site "nehe.gamedev.net"
void rotacao(int x, int y) {
if(rotate){
ROTY = (ROTY + (x - saved_x))%360;
ROTX = (ROTX + (y - saved_y))%360;
saved_x = x;
saved_y = y;
}
glutPostRedisplay();
}
// Carrega bitmap de 24 bits somente
//Código baseado no código disponibilizado no site "nehe.gamedev.net"
int CarregaBmp(char *filename, Image *image) { //LOAD THE BMP FILE
FILE *file;
unsigned long size; // size of the image in bytes.
unsigned long i; // standard counter.
unsigned short int planes; // number of planes in image (must be 1)
unsigned short int bpp; // number of bits per pixel (must be 24)
char temp; // temporary color storage for bgr-rgb conversion.
// Verifica se o arquivo existe
if ((file = fopen(filename, "rb"))==NULL)
{
printf("File Not Found : %s\n",filename);
return 0;
}
fseek(file, 18, SEEK_CUR);
// lendo a largura
if ((i = fread(&image->sizeX, 4, 1, file)) != 1) {
printf("Ocorreu erro lendo a largura do arquivo %s.\n", filename);
return 0;
}
printf("Largura do arquivo %s: %lu\n", filename, image->sizeX);
// lendo a altura
if ((i = fread(&image->sizeY, 4, 1, file)) != 1) {
printf("Ocorreu erro lendo a altura do arquivo %s.\n", filename);
return 0;
}
printf("Altura do arquivo %s: %lu\n", filename, image->sizeY);
// Claculando o tamanho (Assumindo 24 bits ou 3 bytes por pixel).
size = image->sizeX * image->sizeY * 3;
// Lendo os planos
if ((fread(&planes, 2, 1, file)) != 1) {
printf("Ocorreu erro lendo os,planos do arquivo %s.\n", filename);
return 0;
}
if (planes != 1) {
printf("Plano do arquivo %s não é 1: %u\n", filename, planes);
return 0;
}
// Leando o bpp
if ((i = fread(&bpp, 2, 1, file)) != 1) {
printf("Ocorreu erro lendo o bpp do arquivo %s.\n", filename);
return 0;
}
if (bpp != 24) {
printf("Bpp do arquivo %s não é 24: %u\n", filename, bpp);
return 0;
}
fseek(file, 24, SEEK_CUR);
// Le os dados
image->data = (char *) malloc(size);
if (image->data == NULL) {
printf("Ocorreu erro alcando memória para dados da imagem");
return 0;
}
if ((i = fread(image->data, size, 1, file)) != 1) {
printf("Ocoreu erro lendo dados da imagem do arquivo %s.\n", filename);
return 0;
}
for (i=0;i rgb)
temp = image->data;
image->data = image->data[i+2];
image->data[i+2] = temp;
}
// FIM
return 1;
}
// Load Bitmaps And Convert To Textures
/Código baseado no código disponibilizado no site "nehe.gamedev.net"
void CarregaTex() { /LOAD TEXTURE
// Carrega Textura
Image *image1;
// Aloca espaço para textura
image1 = (Image *) malloc(sizeof(Image));
if (image1 == NULL) {
printf("Ocorreu erro alocando espaço para a imagem");
exit(0);
}
if (!CarregaBmp("coisa.BMP", image1)) {
exit(1);
}
// Cria textura
glGenTextures(1, &texture[0]);
glBindTexture(GL_TEXTURE_2D, texture[0]); // 2d textura
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // escala linearmante quando a imagem é maior que a textura
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // escala linearmante quando a imagem é menor que a textura
glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
};
/*========================= DrawScene =====================================*/
void DrawScene (int n, WorldPoint * pts)
{
int i;
int state = 0;
//I THINK THE PROBLEM IS HERE
glBegin(GL_POLYGON);
for(i = 0; i < n; i++)
{
if (i == 0) {
glTexCoord2f (0.0, 0.0);
} else if (i == 1) {
glTexCoord2f (0.0, 1.0);
} else if (i == 2) {
glTexCoord2f (1.0, 0.0);
} else {
glTexCoord2f (1.0, 1.0);
}
glVertex3f(pts.x, pts.y, pts.z);
}
glEnd();
}
/*========================= displayStuff ================================*/
void displayStuff()
{
int i, j;
WorldPoint v_coords[60]; // Pode desenhar polígonos com até 60 vértices
// *********** FIGURA COM GRID ***************
if (VMODE == 1)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_LIGHTING);
}
// ************ FIGURA COM TEXTURA ************
else
{
//ILUMINAÇÃO
glLightfv(GL_LIGHT0, GL_POSITION, PosLuz);
glLightfv(GL_LIGHT0, GL_AMBIENT, Branca);
glLightfv(GL_LIGHT0, GL_DIFFUSE, Cinza);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable( GL_DEPTH_TEST );
}
for (i = 0; i < NPOLY; i++)
{
for (j = 0; j < V_POLYDESCS.vertexes; j ++)
{
v_coords[j] = V_POINTS[V_POLYCOORDS[V_POLYDESCS.offset + j]];
}
glBindTexture(GL_TEXTURE_2D, texture[0]); // Escolhe a textura a ser utilizada
DrawScene(V_POLYDESCS.vertexes, v_coords);
}
}
/*========================= init ========================================*/
void init (void)
{
CarregaTex(); //load texture
glEnable(GL_TEXTURE_2D); // Permite mapeamento de textura
// Fundo cinza
glClearColor(0.4, 0.4, 0.4, 0.0);
glClearDepth(1.0);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
xsize = 512; ysize = 512;
glColor3f(WHITE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(FOV, 1.0, ZN, ZF);
glutMouseFunc(salvaposicao);
glutMotionFunc(rotacao);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Bons cálculos de perspectiva
glEnable(GL_LIGHT1); // Habilita a luz 1
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/*========================= redraw ======================================*/
void redraw ()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1, 1, 1);
glLoadIdentity();
glPushMatrix();
glTranslatef(0.0, 0.0, Zoom); // Aplica o zoom determinado
glRotatef(ROTX, 1.0, 0.0, 0.0); // Realizam a rotacao da cena
glRotatef(ROTY, 0.0, 1.0, 0.0);
glRotatef(ROTZ, 0.0, 0.0, 1.0);
displayStuff();
glPopMatrix();
glutSwapBuffers();
}
/*========================= reshape =====================================*/
void reshape (int w, int h)
{
xsize = w;
ysize = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(FOV, 1.0, ZN, ZF);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/*========================= Exit =============================*/
void Exit (void)
{
exit(0);
}
/*==================================== LeArquivo ===================================*/
// Le os dados do aqruivo *.plg, que deve estar no mesmo diretorio do programa
void LeArquivo(int argc, char *argv[]) //Read plg file
{
FILE *fin;
char buffer [256];
int i;
int pcindex = 0;
int flagMode = 0; // 0 -> Lendo coordenadas, 1 -> Lendo poligonos
int first = 1;
// Erro : arquivo não especificado
if (argc != 2)
{
MessageBox(
0,
"Especifique na linha de comando\no nome do arquivo .plg a ser lido!",
"Erro",
MB_ICONERROR | MB_OK
);
exit(1);
}
fin = fopen(argv[1], "r");
// Erro : arquivo não encontrado, provavelmente (pode ser erro de compartilhamento tb)
if (!fin)
{
MessageBox(0, "Erro ao ler arquivo .plg.\nVerifique se o mesmo existe.", "Erro", MB_ICONERROR | MB_OK);
exit(1);
}
NPOINTS = 0; NPOLY = 0;
// Ler linhas até o fim do arquivo, ignorando linhas que comecem por letras (comentários)
// Primeiramente lê linhas de vértices, ignorando os índices, pois eles são sequenciais,
// até encontrar uma linha em branco, quando entra no "modo" de ler polígonos. Então, vai
// guardando os polígonos lidos numa lista, tomando o cuidado de armazenar em uma outra
// lista a posição de início e o tamanho do polígono, fazendo o programa não ficar limitado
// a triângulos
while (!feof(fin))
{
buffer[0] = 0;
fgets(&buffer[0], 256, fin);
// Linha vazia: parar de ler coordenadas e começar a ler polígonos
if (buffer[0] < 32)
{
flagMode = 1;
continue;
}
// Ignorar comentários
if (((buffer[0] >= ''a'') && (buffer[0] <= ''z'')) || ((buffer[0] >= ''A'') && (buffer[0] <= ''Z'')))
{
continue;
}
// leitura de polígonos
if (flagMode == 1)
{
sscanf(&buffer[0], "%d", &V_POLYDESCS[NPOLY].vertexes); // Nro de vertices
V_POLYDESCS[NPOLY].offset = pcindex; // Índice em que ele inicia
for (i = 0; i < V_POLYDESCS[NPOLY].vertexes; i ++)
{
fscanf(fin, "%d", &V_POLYCOORDS[pcindex]);
V_POLYCOORDS[pcindex] –; // O arquivo é "1 based"
pcindex ++;
}
fgets(&buffer[0], 256, fin);; // Lendo newline e eventuais espaços no fim da linha
NPOLY ++;
}
// leitura de pontos sequencialmente
if (flagMode == 0)
{
// ignorando o índice, pois é sequencial
if (
sscanf(&buffer[0], "%lf %lf %lf",
&V_POINTS[NPOINTS].x, &V_POINTS[NPOINTS].y, &V_POINTS[NPOINTS].z
) == 3
)
{
if (first)
{
xMax = V_POINTS[NPOINTS].x;
yMax = V_POINTS[NPOINTS].y;
zMax = V_POINTS[NPOINTS].z;
xMin = V_POINTS[NPOINTS].x;
yMin = V_POINTS[NPOINTS].y;
zMin = V_POINTS[NPOINTS].z;
first = 0;
}
else
{
// Redefinicao dos limites espaciais da cena
if (V_POINTS[NPOINTS].x > xMax) xMax = V_POINTS[NPOINTS].x;
else if (V_POINTS[NPOINTS].x < xMin) xMin = V_POINTS[NPOINTS].x;
if (V_POINTS[NPOINTS].y > yMax) yMax = V_POINTS[NPOINTS].y;
else if (V_POINTS[NPOINTS].y < yMin) yMin = V_POINTS[NPOINTS].y;
if (V_POINTS[NPOINTS].z > zMax) zMax = V_POINTS[NPOINTS].z;
else if (V_POINTS[NPOINTS].z < zMin) zMin = V_POINTS[NPOINTS].z;
}
NPOINTS ++;
}
}
}
fclose(fin);
}
/*========================= InOut =============================*/
void InOut (int D)
{
if (D)
{
if (Zoom < -1) Zoom += 3;
}
else if (Zoom > -49) Zoom -= 3;
glutPostRedisplay();
}
/*========================= keyboardHandler =============================*/
void keyboardHandler (unsigned char key, int x, int y)
{
int dif = 5;
switch(key)
{
case ''q'' : Exit(); break;
case ''X'' : ROTX = (ROTX + 18) % 360; break;
case ''x'' : ROTX = (ROTX - 18) % 360; break;
case ''Y'' : ROTY = (ROTY + 18) % 360; break;
case ''y'' : ROTY = (ROTY - 18) % 360; break;
case ''Z'' : ROTZ = (ROTZ + 18) % 360; break;
case ''z'' : ROTZ = (ROTZ - 18) % 360; break;
case ''I'' :
case ''i'' : InOut(1); break;
case ''O'' :
case ''o'' : InOut(0); break;
case ''w'' :
case ''W'' : VMODE = (VMODE)? 0 : 1; break;
case ''p'' : PosLuz[0] += 1; break;
case ''u'' : PosLuz[0] -= 1; break;
case ''l'' : PosLuz[1] += 1; break;
case ''k'' : PosLuz[1] -= 1; break;
case ''m'' : PosLuz[2] += 1; break;
case ''n'' : PosLuz[2] -= 1; break;
case ''1'' : ROTX += dif; break; //SPIN
case ''4'' : ROTX -= dif; break; //SPIN
case ''2'' : ROTY += dif; break; //TILT
case ''5'' : ROTY -= dif; break; //TILT
case ''3'' : ROTZ += dif; break; //BACK
case ''6'' : ROTZ -= dif; break; //BACK
}
redraw();
}
/*========================= main ========================================*/
int main (int argc, char *argv[])
{
LeArquivo(argc, argv);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA);
glutInitWindowPosition(0, 0);
glutInitWindowSize(xsize, ysize);
glutCreateWindow("Trabalho III de CompGraf");
init();
glutKeyboardFunc(keyboardHandler);
glutDisplayFunc(redraw);
glutReshapeFunc(reshape);
glutMainLoop();
return (1);
}
####################################################
#################################################### </i>
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement