martes, 30 de octubre de 2007

Reporte Práctica 8

2.- Tome el código del programa Mano y modifiquelo para que :
-Incorpore dos gestos más a la mano.

#include
#include

#define ANTEBRAZO_ALTO 8.0
#define ANTEBRAZO_ANCHO 1.0

#define PALMA_ALTO 5.0
#define PALMA_ANCHO 4.0

#define PULGAR_ALTO1F 2.0
#define PULGAR_ANCHO1F 0.5

#define MENIQUE_ALTO1F 1.5
#define MENIQUE_ALTO2F 0.5
#define MENIQUE_ALTO3F 0.5
#define MENIQUE_ANCHO1F 0.5
#define MENIQUE_ANCHO2F 0.45
#define MENIQUE_ANCHO3F 0.4

#define INDICE_ALTO1F 2.0
#define INDICE_ALTO2F 1.0
#define INDICE_ALTO3F 1.0
#define INDICE_ANCHO1F 0.5
#define INDICE_ANCHO2F 0.49
#define INDICE_ANCHO3F 0.48

#define MEDIO_ALTO1F 2.5
#define MEDIO_ALTO2F 1.0
#define MEDIO_ALTO3F 1.0
#define MEDIO_ANCHO1F 0.5
#define MEDIO_ANCHO2F 0.49
#define MEDIO_ANCHO3F 0.48

#define ANULAR_ALTO1F 2.0
#define ANULAR_ALTO2F 1.0
#define ANULAR_ALTO3F 1.0
#define ANULAR_ANCHO1F 0.5
#define ANULAR_ANCHO2F 0.49
#define ANULAR_ANCHO3F 0.48

#define PALMA_VOLUMEN 1.0

typedef float point[3];

static GLfloat theta[14] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};

static GLfloat theta_amorypaz[14] = { 30.0, 15.0, 0.0, -15.0, 80.0, 80.0, 0.0, 0.0, 0.0, 0.0, 145.0, 20.0, 145.0, 20.0};
static GLfloat theta_spiderman[14] = {-65.0, -10.0, 100.0, -55.0, 0.0, 0.0, 0.0, 0.0, 145.0, 20.0, 145.0, 20.0, 0.0, 0.0};
static GLint angle = 0;
static GLint direccion = 1;

GLUquadricObj *ab, *p1f, *p2f,*m1f, *m2f, *m3f, *i1f,*i2f, *i3f, *a1f, *a2f, *a3f, *md1f,*md2f, *md3f;

double size=1.0;

void antebrazo()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(ab,ANTEBRAZO_ANCHO,ANTEBRAZO_ANCHO,ANTEBRAZO_ALTO,10,10);
glPopMatrix();
}

void palma()
{
glPushMatrix();
glTranslatef(0.0,PALMA_ALTO/2,0.0);
glScalef(PALMA_ANCHO,PALMA_ALTO,PALMA_VOLUMEN);
glutSolidCube(1.0);
glPopMatrix();
}

void pulgar1f()
{
glPushMatrix();
glRotatef(-80.0,1.0,1.0,0.0);
gluCylinder(p1f,PULGAR_ANCHO1F,PULGAR_ANCHO1F,PULGAR_ALTO1F,10,10);
glPopMatrix();
}

void pulgar2f()
{
glPushMatrix();
glRotatef(-90.1,0.0,1.0,0.0);
gluCylinder(p2f,PULGAR_ANCHO1F,PULGAR_ANCHO1F,PULGAR_ALTO1F,10,10);
glPopMatrix();
}

void menique1f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(m1f,MENIQUE_ANCHO1F,MENIQUE_ANCHO1F,MENIQUE_ALTO1F,10,10);
glPopMatrix();
}

void menique2f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(m2f,MENIQUE_ANCHO2F,MENIQUE_ANCHO2F,MENIQUE_ALTO2F,10,10);
glPopMatrix();
}

void menique3f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(m3f,MENIQUE_ANCHO3F,MENIQUE_ANCHO3F,MENIQUE_ALTO3F,10,10);
glPopMatrix();
}

void indice1f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(i1f,INDICE_ANCHO1F,INDICE_ANCHO1F,INDICE_ALTO1F,10,10);
glPopMatrix();
}

void indice2f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(i2f,INDICE_ANCHO2F,INDICE_ANCHO2F,INDICE_ALTO2F,10,10);
glPopMatrix();
}

void indice3f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(i3f,INDICE_ANCHO3F,INDICE_ANCHO3F,INDICE_ALTO3F,10,10);
glPopMatrix();
}


void medio1f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(md1f,MEDIO_ANCHO1F,MEDIO_ANCHO1F,MEDIO_ALTO1F,10,10);
glPopMatrix();
}

void medio2f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(md2f,MEDIO_ANCHO2F,MEDIO_ANCHO2F,MEDIO_ALTO2F,10,10);
glPopMatrix();
}

void medio3f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(md3f,MEDIO_ANCHO3F,MEDIO_ANCHO3F,MEDIO_ALTO3F,10,10);
glPopMatrix();
}

void anular1f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(a1f,ANULAR_ANCHO1F,ANULAR_ANCHO1F,ANULAR_ALTO1F,10,10);
glPopMatrix();
}

void anular2f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(a2f,ANULAR_ANCHO2F,ANULAR_ANCHO2F,ANULAR_ALTO2F,10,10);
glPopMatrix();
}

void anular3f()
{
glPushMatrix();
glRotatef(-90.0,1.0,0.0,0.0);
gluCylinder(a3f,ANULAR_ANCHO3F,ANULAR_ANCHO3F,ANULAR_ALTO3F,10,10);
glPopMatrix();
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(1.0,0.0,0.0);
glTranslatef(-4.5, -ANTEBRAZO_ALTO,0.0);
glRotatef(theta[0],0.0,1.0,0.0);
glRotatef(theta[1],1.0,0.0,0.0);
antebrazo();
glTranslatef(0.0, ANTEBRAZO_ALTO,0.0);
glPushMatrix();
glRotatef(theta[2],0.0,1.0,0.0);
glRotatef(theta[3],1.0,0.0,0.0);
palma();
glPushMatrix();
glTranslatef(-PULGAR_ALTO1F/2-0.5,PULGAR_ALTO1F/2+1,0.0);
glRotatef(theta[4],0.0,1.0,0.0);
glTranslatef(0.0,-PULGAR_ALTO1F/2,0.0);
pulgar1f();
glTranslatef(-PULGAR_ALTO1F/2-0.5,PULGAR_ALTO1F+0.5,0.0);
glRotatef(theta[5],0.0,1.0,0.0);
glTranslatef(0.0,-PULGAR_ALTO1F/2,0.0);
pulgar2f();
glPopMatrix();
glPushMatrix();
glTranslatef(-PALMA_ANCHO/2+0.5, PALMA_ALTO,0.0);
glRotatef(theta[6],1.0,0.0,0.0);
indice1f();
glTranslatef(0.0,INDICE_ALTO1F,0.0);
glRotatef(theta[7],1.0,0.0,0.0);
indice2f();
glTranslatef(0.0,INDICE_ALTO2F,0.0);
glRotatef(theta[7],1.0,0.0,0.0);
indice3f();
glPopMatrix();
glPushMatrix();
glTranslatef(-PALMA_ANCHO/2+1.5,PALMA_ALTO,0.0);
glRotatef(theta[8],1.0,0.0,0.0);
medio1f();
glTranslatef(0.0,MEDIO_ALTO1F,0.0);
glRotatef(theta[9],1.0,0.0,0.0);
medio2f();
glTranslatef(0.0,MEDIO_ALTO2F,0.0);
glRotatef(theta[9],1.0,0.0,0.0);
medio3f();
glPopMatrix();
glPushMatrix();
glTranslatef(PALMA_ANCHO/2-1.5,PALMA_ALTO,0.0);
glRotatef(theta[10],1.0,0.0,0.0);
anular1f();
glTranslatef(0.0,ANULAR_ALTO1F,0.0);
glRotatef(theta[11],1.0,0.0,0.0);
anular2f();
glTranslatef(0.0,ANULAR_ALTO2F,0.0);
glRotatef(theta[11],1.0,0.0,0.0);
anular3f();
glPopMatrix();
glPushMatrix();
glTranslatef(PALMA_ANCHO/2-0.5,PALMA_ALTO,0.0);
glRotatef(theta[12],1.0,0.0,0.0);
menique1f();
glTranslatef(0.0,MENIQUE_ALTO1F,0.0);
glRotatef(theta[13],1.0,0.0,0.0);
menique2f();
glTranslatef(0.0,MENIQUE_ALTO2F,0.0);
glRotatef(theta[13],1.0,0.0,0.0);
menique3f();
glPopMatrix();
glPopMatrix();
glFlush();
glutSwapBuffers();
}

void mouse(int btn, int state, int x, int y)
{
GLfloat mintope;
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
if (angle <=3 ) mintope = -180.0;
else mintope = 0.0;
theta[angle]+=5.0;
if( theta[angle] > 150.0) theta[angle] = 150.0;
display();
}
display();

}
void animacion_amorypaz(void)
{
int i,j;
int mueve=1;
do
{
for(i = 0; i <=13 ; i++)
{
if (theta[i]!=theta_amorypaz[i])
{
if (theta[i] {
if((((int)(theta_amorypaz[i]-theta[i]))%5)==0)
theta[i]+=5.0;
else
theta[i]+=(GLfloat)(((int)(theta_amorypaz[i]-theta[i]))%5);
}
else
{
if((((int)(theta[i]-theta_amorypaz[i]))%5)==0)
theta[i]-=5.0;
else
theta[i]-=(GLfloat)(((int)(theta[i]-theta_amorypaz[i]))%5);
}
}
}
j=13;
for(i = 0; i <=13 ; i++)
{
if(theta[i]==theta_amorypaz[i]) j--;
}
if (j<=0) mueve=0;
display();
}
while(mueve);
}

void animacion_spiderman(void)
{
int i,j;
int mueve=1;
do
{
for(i = 0; i <=13 ; i++)
{
if (theta[i]!=theta_spiderman[i])
{
if (theta[i] {
if((((int)(theta_spiderman[i]-theta[i]))%5)==0)
theta[i]+=5.0;
else
theta[i]+=(GLfloat)(((int)(theta_spiderman[i]-theta[i]))%5);
}
else
{
if((((int)(theta[i]-theta_spiderman[i]))%5)==0)
theta[i]-=5.0;
else
theta[i]-=(GLfloat)(((int)(theta[i]-theta_spiderman[i]))%5);
}
}
}
j=13;
for(i = 0; i <=13 ; i++)
{
if(theta[i]==theta_spiderman[i]) j--;
}
if (j<=0) mueve=0;
display();
}
while(mueve);
}

void animacion_restituye(void)
{
int i,j;
int mueve=1;
do
{
for(i = 0; i <=13 ; i++)
{
if (theta[i]!=0.0)
{
if (theta[i]<0.0)
{
if(((int)theta[i]%5)==0)
theta[i]+=5.0;
else
theta[i]+=(GLfloat)(((int)theta[i])%5);
}
else
{
if(((int)theta[i]%5)==0)
theta[i]-=5.0;
else
theta[i]-=(GLfloat)(((int)theta[i])%5);
}
}
}
j=13;
for(i = 0; i <=13 ; i++)
{
if(theta[i]==0.0) j--;
}
if (j<=0) mueve=0;
display();
}
while(mueve);
}

void menu(int id)
{
if(id <= 1) direccion = id;
else if(id <= 15 ) angle=id-2;
else if(id <= 18 )
{
switch (id)
{
case 16:
animacion_amorypaz();
break;
case 17:
animacion_spiderman();
break; }
display();
}
else if(id == 19) exit(0);
else if(id == 20) animacion_restituye();
}

void myReshape(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w<=h)
glOrtho(-10.0,10.0,-10.0 * (GLfloat) h / (GLfloat) w,10.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0);
else
glOrtho(-10.0 * (GLfloat) w / (GLfloat) h,10.0 * (GLfloat) w / (GLfloat) h, 0.0, 10.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void myinit()
{
GLfloat mat_specular[] ={1.0,1.0,1.0,1.0};
GLfloat mat_diffuse[] ={1.0,1.0,1.0,1.0};
GLfloat mat_ambient[] ={1.0,1.0,1.0,1.0};
GLfloat mat_shininess[] ={100.0};
GLfloat light_ambient[] ={0.0,0.0,0.0,1.0};
GLfloat light_diffuse[] ={1.0,0.0,0.0,1.0};
GLfloat light_specular[]={1.0,1.0,1.0,1.0};
GLfloat light_position[]={10.0,10.0,10.0,0.0};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glEnable(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
ab=gluNewQuadric();
gluQuadricDrawStyle(ab,GLU_FILL);
p1f=gluNewQuadric();
gluQuadricDrawStyle(p1f,GLU_FILL);
p2f=gluNewQuadric();
gluQuadricDrawStyle(p2f,GLU_FILL);
m1f=gluNewQuadric();
gluQuadricDrawStyle(m1f,GLU_FILL);
m2f=gluNewQuadric();
gluQuadricDrawStyle(m2f,GLU_FILL);
m3f=gluNewQuadric();
gluQuadricDrawStyle(m3f,GLU_FILL);
i1f=gluNewQuadric();
gluQuadricDrawStyle(i1f,GLU_FILL);
i2f=gluNewQuadric();
gluQuadricDrawStyle(i2f,GLU_FILL);
i3f=gluNewQuadric();
gluQuadricDrawStyle(i3f,GLU_FILL);
md1f=gluNewQuadric();
gluQuadricDrawStyle(md1f,GLU_FILL);
md2f=gluNewQuadric();
gluQuadricDrawStyle(md2f,GLU_FILL);
md3f=gluNewQuadric();
gluQuadricDrawStyle(md3f,GLU_FILL);
a1f=gluNewQuadric();
gluQuadricDrawStyle(a1f,GLU_FILL);
a2f=gluNewQuadric();
gluQuadricDrawStyle(a2f,GLU_FILL);
a3f=gluNewQuadric();
gluQuadricDrawStyle(a3f,GLU_FILL);
}

void main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutInitWindowPosition(400,100);
glutCreateWindow("Mano");
myinit();
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutCreateMenu(menu);
glutAddMenuEntry("",1);
glutAddMenuEntry("",0);
glutAddMenuEntry("Girar Brazo",2);
glutAddMenuEntry("Doblar Brazo",3);
glutAddMenuEntry("Girar Palma",4);
glutAddMenuEntry("Doblar Palma",5);
glutAddMenuEntry("Pulgar 1ª falange",6);
glutAddMenuEntry("Pulgar 2ª falange",7);
glutAddMenuEntry("Indice 1ª falange",8);
glutAddMenuEntry("Indice 2ª y 3ª falanges",9);
glutAddMenuEntry("Medio 1ª falange",10);
glutAddMenuEntry("Medio 2ª y 3ª falanges",11);
glutAddMenuEntry("Anular 1ª falange",12);
glutAddMenuEntry("Anular 2ª y 3ª falanges",13);
glutAddMenuEntry("Meñique 1ª falange",14);
glutAddMenuEntry("Meñique 2ª y 3ª falanges",15);
glutAddMenuEntry("Gestos - AMOR Y PAZ",16);
glutAddMenuEntry("Gestos - SPIDERMAN",17);
glutAddMenuEntry("RESTITUIR",20);
glutAddMenuEntry("",19);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
}


Previo Práctica 8

Reporte Práctica 7

martes, 2 de octubre de 2007

Previo Práctica 7

1.¿Que es "shading" (sombreado) en términos de computación gráfica?
¿Qué es y cómo se declara y usa en OpenGL/GLUT
-Una fuente de luz?
-Un material?
-Una textura?
¿Cuales son los atributos/caracteristicas que se pueden declarar en OpenGL/GLUT para manejo de:
-Luces
-Materiales
-Texturas
y con que funciones se hace esto?


En OpenGL se pueden definir tres formas de luz distintas, estas son: AMBIENTE, DIFUSA y ESPECULAR

AMBIENTE.- la luz llega de todas las direcciones de forma distribuida y es reflejada de igual forma por los polígonos de la escena.

DIFUSA.- la luz llega de una fuente puntual en particular y toca la superficie con una intensidad que depende de la cara hacia la cual llega la luz, este tipo de iluminación es la que mejor define el contorno en los objetos 3D

ESPECULAR.- es la luz emitida desde el objeto de forma distribuida en todas direcciones.

La luz tiene las propiedades de color, posición y dirección. El color que las luces tendrán esta determinado por las tres componentes de color que maneja OpenGL, rojo, verde y azul. El comando utilizado para especificar todas las propiedades de la luz es glLiht(), este comando tiene tres argumentos para identificar la luz que se está utilizando, la propiedad y el valor deseado para la propiedad.

Después de definir las características de las luces se encienden con el comando glEnable(nombre de la fuente de luz a activar). También existe una función para desactivar la iluminación, que es glDisable y desactiva la luz especificada.

Las características de la luz por default para glLight son: GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_POSITION, GL_SPOT_DIRECTION, GL_SPOT_EXPONENT, GL_SPOT_CUTOFF, GL_CONSTANT_ATTENUATION, GL_LINEAR_ATTENUATION, GL_QUADRATIC_ATTENUATION.

GL_DIFFUSE Y GL_ESPECULAR sólo se usan con la primera fuente de luz.

GL_AMBIENT: Define los valores de la luz ambiental. Valor RGBA, su valor por defecto es (0.0,0.0,0.0,1.0)
GL_DIFFUSE: Define los valores de la luz difusa. Valor RGBA. su valor por defecto es (1.0,1.0,1.0,1.0)
GL_SPECULAR: Define los valores de la luz especular. Valor RGBA. Su valor por defecto es (1.0,1.0,1.0,1.0)
GL_POSITION: Posición de la luz, en coordenadas { x, y, z, w }, su valor por defecto es (0.0,0.0,1.0,0.0)
GL_SPOT_DIRECTION: Vector de dirección de la luz, en coordenadas { x, y, z }, su valor por defecto es (0.0,0.0,-1.0)
GL_SPOT_EXPONENT: Representa la concentración de la intensidad de la luz. Valor escalar, por defecto 0.
GL_SPOT_CUTOFF: Ángulo del cono de luz. Valor escalar, por defecto 180.
GL_CONSTANT_ATTENUATION: Atenuación constante a aplicar a la luz según la distancia. Valor escalar, por defecto 1
GL_LINEAR_ATTENUATION: Atenuación lineal a aplicar a la luz según la distancia. Valor escalar, por defecto 0
GL_QUADRATIC_ATTENUATION: Atenuación cuadrática a aplicar a la luz según la distancia. Valor escalar, por defecto 0


La luz es un punto focal el cual ilumina los objetos en un cierto rango, es un punto muy definido y fácil de encontrar, en cambio la iluminación da una intensidad de luz en un rango más amplio dando la sensación de que no hay un punto focal donde la luz es emitida, la iluminación es un tipo de luz la cual no incide directamente en los objetos.

Para habilitar y deshabilitar a uno de los puntos de iluminación se utilizan los comandos glEnable(nombre_iluminación) y glDisable(nombre_iluminación). La fuente de luz es creada con glLightfv (GL_LIGHT0, GL_AMBIENT, luz ambiental);


Dependiendo de las propiedades de los materiales la luz tiene un efecto distinto sobre ellos.

Estas propiedades se definen con glMaterial:
void glMaterial(GLenum cara, GLenum nombre, TYPOparam);
El argumento cara, determina la cara del objeto en la que aplicamos las propiedades, tiene los siguientes valores:
GL_FRONT,GL_BACK,GL_FRONT_AND_BACK.
El siguiente indica la propiedad que va utilizarse para dicha cara, puede ser:
GL_AMBIENT, GL_DIFFUSE, GL_AMBIENT_AND_DIFFUSE, GL_SPECULAR, GL_SHININESS, GL_EMISSION, GL_COLOR_INDEXES.
El ultimo parámetro especifica un puntero al valor o valores que el parámetro nombre tomara.
· GL_AMBIENT .- color ambiente del material, sus valores por defecto son (0.2, 0.2, 0.2, 1.0).
· GL_DIFFUSE .- color difuso del material, sus valores por defecto son (0.8, 0.8, 0.8, 1.0).
· GL_AMBIENT_AND_DIFFUSE .- color ambiente y difuso del material
· GL_SHININESS.- exponente especular, su valor por defecto es 0.
· GL_EMISSION.- el color de emisión del material, sus valores por defecto son (0.0, 0.0, 0.0, 1.0).
· GL_COLOR_INDEXES.- índice de color ambiente, difuso y especular, sus valores por defecto son (0, 1, 1).


TEXTURAS
Cargando texturas en memoria
El proceso de cargar la textura en memoria, no es propio de OpenGL. Se tiene que realizar una funcion externa. Existen algunas limitaciones que la librería impone. Las dimensiones de todas las texturas que carguentienen que ser potencias de 2, como por ejemplo 64x64, 128x64, etc.
Se tiene que tener en cuenta que si sedebe estar dibujando en RGB, sin color indexado, o bien cargando texturas en formato RGB. Si se carga una imagen GIF, que tiene color indexado, se tiene que programar una función extra para convertirla a RGB.. Sea cuál sea el método, al final se tendrá un puntero a un segmento de memoria que contiene la imagen:
unsigned char *textura;
Es importante también guardar las propiedades de la textura, en concreto sus dimensiones de ancho y alto, así como su profundidad en bits. Si estamos trabajando en RGB, la profundidad será 24bits.
Los pasos a seguir son:
· Determinamos el tamaño
· Calculamos la memoria que será necesaria
· Reservamos memoria
· Generación de archivo TGA el cual viene en formato RGB. Si no está en este formato se deberá realizar la conversión.
Una vez tenemos la imagen cargada en memoria, los pasos a seguir son:
· Generar la referencia para la textura. [glGenTextures (1, &textura);] Con el GLuint textura referenciaremos a "esa textura". Si se quiere tener más, se debe crear un array de GLuint. El 1 significa que sólo generamos una textura.
· Referenciamos esa textura: [glBindTexture (GL_TEXTURE_2D, textura);]. Esta función dice que ahora en adelante, todas las operaciones que afecten al manejo de texturas se aplicarán sobre esa textura. En este caso es una etextura 2D
· Especificamos los filtros para esa textura:
o glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
· OpenGL puede aplicar filtros a las texturas para mejorar su visualización. La primer línea especifica el filtro a utilizar en caso de que las textura se vea más grande de lo que en realidad es (Aumento). La segunda, especifica el filtro para el caso de que la textura se vea más pequeña de lo que en realidad es. Aquí utilizamos un filtro LINEAR para el 1er caso y del segundo hablaremos más adelante. Otro valor que podríamos haber utilizado es el GL_NEAREST, que es un filtro peor pero más rápido
· Creamos la textura por medio de MIPMAPS para mejor rendimiento, en vez de filtrar las textura dinámicamente, al crear un mipmap, creamos varias texturas de diferentes tamaños (del original hacia más pequeño). OpenGL, decidirá en función de lo lejano que esté el objeto con esa textura, de qué mipmap utilizar.
· Por ultimo, sólo hace falta habilitar el empleo de texturas con:glEnable(GL_TEXTURE_2D);En la función init_gl.


MAPEO DE TEXTURAS PARA TEXTURAS 1D
•Para definir la textura:
• void glTexImage1D (GLenum objetivo, GLint nivel, • GLint componentes, GLsizei ancho, GLint borde, GLenum formato, GLenum tipo, const GLvoid *pixels)
•donde:
–objetivo vale siempre GL_TEXTURE_1D
–nivel indica el nivel de detalle (0 para texturas individuales)
–componentes vale 1 (modo índice), 3 (RGB) ó 4 (RGBA)
–ancho indica el ancho en pixel del mapa de textura (debe ser potencia de 2)
–borde indica el número de pixels que forman el borde de la textura (0, 1 ó 2)
–formato indica el formato de los pixels: GL_RED, GL_RGB, GL_LUMINANCE
–tipo indica el tipo de dato de los pixels: GL_UNSIGNED_INT, GL_FLOAT
–pixels es un puntero a los pixels de la textura

MAPEO PARA TEXTURAS 2D
•Para definir la textura:
• void glTexImage2D (GLenum objetivo, GLint nivel, • GLint componentes, GLsizei ancho, GLsizei alto, • GLint borde, GLenum formato, GLenum tipo, • const GLvoid *pixels)
•donde:
–objetivo vale siempre GL_TEXTURE_2D
–nivel indica el nivel de detalle (0 para texturas individuales)
–componentes vale 1 (modo índice o luminancia), 3 (RGB) ó 4 (RGBA)
–ancho indica el ancho en pixels del mapa de textura (debe ser potencia de 2)
–alto indica el alto en pixels del mapa de textura (debe ser potencia de 2)
–borde indica el número de pixels que forman el borde de la textura (0, 1 ó 2)
–formato indica el formato de los pixels: GL_RED, GL_RGB, GL_LUMINANCE
–tipo indica el tipo de dato de los pixels: GL_UNSIGNED_INT, GL_FLOAT
–pixels es un puntero a los pixels de la textura



MAPEO DE TEXTURAS EN UNA SUPERFICIE
•Al mapear la imagen de textura sobre una superficie, los texels no se van a corresponder exactamente con los pixels
Magnificación : Si la superficie es mayor que la textura, cada pixel se corresponderá con un trozo pequeño de texel

Minificación : Si la superficie es menor que la textura, cada pixel se corresponderá con una conjunto de texels contiguos•
Texels

Pixeles

Modos de mapeo
•Para establecer el modo de mapeo:
• glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GLint valor)
• donde valor puede tomar 3 valores:
–GL_DECAL: el valor del texel se copia directamente al pixel
–GL_MODULATE: el valor del texel se escala por el color del objeto
–GL_BLEND: el valor del texel se usa para interpolar entre el color del objeto y un color constante definido para la textura, mediante la función
• glTexEnvfv(GL_TEXTURE_ENV,GL_TEXTURE_ENV_COLOR,GLfloat color[4])


MODOS DE APLICACIÓN DE TEXTURAS

GL TEXTURE WRAP S
Establece el parámetro wrap para la coordenada de textura s a GL_CLAMP, GL_CLAMP_TO_EDGE, o GL_REPEAT. GL_CLAMP causa que las coordenadas s estén limitadas al rango [0,1] y es útil para prevenir artefactos de envoltura (compresión?) cuando se mapea una única imagen en un objeto. GL_CLAMP_TO_EDGE causa que las coordenadas s se limiten al rango [1/2n, 1-(1/2n)i], donde n es el tamaño de la textura en la dirección del límite. GL_REPEAT causa que la parte entera de s se ignore; el GL utiliza solo la parte fraccionaria, creando por lo tanto un patrón repetitivo. Los elementos de textura de borde son accesados solo si la envoltura se establece a GL_CLAMP. Inicialmente, GL_TEXTURE­_WRAP_S se establece a GL_REPEAT.

GL TEXTURE WRAP T
Establece el parámetro wrap para la coordenada de textura t a GL_CLAMP, GL_CLAMP_TO_EDGE, o GL_REPEAT (véase arriba). Inicialmente, GL_TEXTURE_WRAP_T se establece a GL_REPEAT.


2.- Escriba un programa donde:

-Dibuje un cubo y asigne caracteristicas de material que lo hagan verse como de madera.
-Aplique una textura de madera al cubo(bitmap).
-Aplique como textura su fotografia.
El cambio de modo se hará con click del mouse.

4.Escriba un programa donde:
-Dibuje un cubo y asigne caracteristicas de material que lo hagan verse como de madera.
-Aplique una textura de madera al cubo(bitmap).
-Aplique como textura su fotografia.
El cambio de modo se hará con click del mouse.

#include
#include
#include "TEXTURA.h"

int x1=2,z1=0;
bool botDer=true,botIzq=false;
GLfloat no_mat[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat mat_ambient[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_diffuse_none[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat no_shininess[] = { 0.0 };

float muevete=0;
static GLuint textureName[6];
char* filenameArray[6] = {
"cara1.bmp",
"cara2.bmp",
"cara3.bmp",
"cara4.bmp",
"cara5.bmp",
"cara6.bmp"
};

void loadTextureFromFile(char *filename)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);

RgbImage theTexMap( filename );

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_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB,
theTexMap.GetNumCols(), theTexMap.GetNumRows(),
GL_RGB, GL_UNSIGNED_BYTE, theTexMap.ImageData() );

}

void myinit(char* filenames[]){
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHTING);

GLfloat light_ambient[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_diffuse[] = { 0.0, 0.0, 1.0, 1.0 };
GLfloat light_specular[] = { 0.0, 0.8, 0.0, 1.0 };
GLfloat light_position[] = { 1, 0.0, 5.0, 1.0 };
GLfloat spot_direction[] = { 0.0, 0.0, -1.0 };

glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction);

GLfloat light1_ambient[] = { 0.6, 0.5, 0.4, 1.0 };
GLfloat light1_diffuse[] = { 1.0, 0.0, 0.0, 1.0 };
GLfloat light1_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat spot1_direction[] = { 0.0, -1.0, 1.0 };

glLightfv(GL_LIGHT1, GL_AMBIENT, light1_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, light1_specular);
glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 45.0);
glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, spot1_direction);

glClearColor(0.0, 0.0, 0.0, 0.0);
glGenTextures( 6, textureName );
for ( int i=0; i<6; i++ ){
glBindTexture(GL_TEXTURE_2D, textureName[i]);
loadTextureFromFile( filenames[i] );
}
}

void initFour( char* filenames[] )
{
glGenTextures( 6, textureName );
for ( int i=0; i<6; i++ ) {
glBindTexture(GL_TEXTURE_2D, textureName[i]);
loadTextureFromFile( filenames[i] );
}
}

void drawQuad(void) {
glBegin(GL_QUADS);
glVertex3f(-1.0, -1.0, 0.0);
glVertex3f(-1.0, 1.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(1.0, -1.0, 0.0);
glEnd();
}

void drawTextureQuad( int i ) {
glBindTexture(GL_TEXTURE_2D, textureName[i]);

glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex3f(-2.0, -2.0, 1.0);

glTexCoord2f(0.0, 1.0);
glVertex3f(-2.0, 2.0, 1.0);

glTexCoord2f(1.0, 1.0);
glVertex3f(2.0, 2.0, 1.0);

glTexCoord2f(1.0, 0.0);
glVertex3f(2.0, -2.0, 1.0);

glEnd();

}

void drawSolidQuad( int i ) {

glBindTexture(GL_TEXTURE_2D,i);

glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex3f(-1.0, -1.0, 0.0);

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

glTexCoord2f(1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);

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

glEnd();

}

void display(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

GLfloat light1_position[] = { x1, 3.0, -z1, 1.0 };

glLightfv(GL_LIGHT1, GL_POSITION, light1_position);

if(botDer == true){
glEnable(GL_LIGHT0);
}else{
glDisable(GL_LIGHT0);
}

if(botIzq == true){
glEnable(GL_LIGHT1);
}else{
glDisable(GL_LIGHT1);
}

GLfloat mrojo[4]= {1,0,0,1};
GLfloat mverde[4]={0,1,0,1};

GLfloat zExtent, xExtent, xLocal, zLocal;
int loopX, loopZ;

glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode( GL_MODELVIEW_MATRIX );
glLoadIdentity();
glTranslatef(0.0,0.0,0.0);


glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse_none);

glRotatef(-muevete,0.5,0,0.5);

glPushMatrix();
glPushMatrix();
glTranslatef( 0, 0, 1 );
drawTextureQuad ( 4 );
glPopMatrix();

glPushMatrix();
glTranslatef( 0, 0, -1 );
glRotatef( 180, 0, 1, 0 );
drawTextureQuad ( 3 );
glPopMatrix();

glPushMatrix();
glTranslatef( 1, 0, 0 );
glRotatef( 90, 0, 1, 0 );
drawTextureQuad ( 2 );
glPopMatrix();

glPushMatrix();
glTranslatef( -1, 0, 0 );
glRotatef( -90, 0, 1, 0 );
drawTextureQuad ( 1 );
glPopMatrix();

glPushMatrix();
glTranslatef( 0, 1, 0 );
glRotatef( -90, 1, 0, 0 );
drawTextureQuad ( 5 );
glPopMatrix();

glPushMatrix();
glTranslatef( 0, -1, 0 );
glRotatef( 90, 1, 0, 0 );
drawTextureQuad ( 0 );
glPopMatrix();
glPopMatrix();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glFlush();
glutSwapBuffers();
}

void idle(void){
muevete+=0.1;
display();
}



void Ratoncito(int boton, int estado, int x, int y) {
if(estado == GLUT_DOWN) {
if(boton == GLUT_LEFT_BUTTON) {
botIzq=!botIzq;
}else{
if(boton == GLUT_RIGHT_BUTTON){
botDer=!botDer;
}
}
}
}

void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,1.0*w/h,1,1000);
gluLookAt (0, 0, 10, 0, 0, 0, 0, 1, 0);
glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (300, 300);
glutInitWindowPosition(400, 100);
glutCreateWindow("Cubo con Texturas");
myinit(filenameArray);
glutMouseFunc(Ratoncito);
glutReshapeFunc(myReshape);
glutIdleFunc(idle);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Reporte Práctica 6

#include

void reshape(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-4,4,-4,4,-4,4);
glMatrixMode(GL_MODELVIEW);
}
float escala = 1.0f;
float transZ = -10.0f;

void display(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glScalef(0.003,0.003,0.003);
glTranslatef(-400,transZ,0);
glScalef(escala,escala,escala);
glColor3f(0.8,0.8,0.8);
glutStrokeCharacter(GLUT_STROKE_ROMAN, ' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, ' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'A');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'D');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'R');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'I');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'A');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'N');
glTranslatef(-600,-200,0);
glColor3f(0.8,0.8,0.8);
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'Q');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'U');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'I');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'N');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'T');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'A');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'N');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'A');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'R');
glTranslatef(-750,-200,0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'M');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'O');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'N');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'D');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'R');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'A');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'G');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'O');
glutStrokeCharacter(GLUT_STROKE_ROMAN, 'N');
glFlush();
glutSwapBuffers();
}
void init(){
glClearColor(0.3f, 0.3f, 0.3f, 1.0f );
glEnable(GL_DEPTH_TEST);

}

void teclado(unsigned char key, int x, int y){

switch(key)
{
//Tecla para salir
case 27:
exit(0);
case 'a':
transZ= transZ + 50.0f;
escala-= 0.03;
break;
case 'b':
transZ= transZ + 200.0f;
break;
case 'c':
transZ -= 0.1f;
break;
default:
break;
}
glutPostRedisplay();
}

int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(300, 600);
glutInitWindowPosition(500, 100);
glutCreateWindow("Letras al estilo Stars Wars");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(teclado);
glutMainLoop();
return 0;
}


Práctica 6

1.Escriba un programa que:
-Dibuje en pantalla su número de cuenta.
-Rotelo 45º al apretar la barra espaciadora
-Escale en un factor de 0.5 cuando apriete el boton izquierdo del mouse.
-Traslade sobre (0.1,0.1,0) al apretar el botón derecho del mouse.
-Restaure todo a condiciones iniciales al apretar "R" o "r".
#include "GL/glut.h"
#include "string.h"
char etiqueta[80];

static int ang=180,ang2=180;
static float scalx=0.2,scaly=0.2;
static int transx=250, transy=250;

void reshape(int w, int h){
if (!h)
return;
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, 0, h);
glScalef(1, -1, 1);
glTranslatef(0, -h, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void Dibuja (char *cadena)
{
unsigned int Nletras;
for (Nletras=0; Nletras glutStrokeCharacter(GLUT_STROKE_ROMAN, cadena[Nletras]);
}
void display(void)
{
char *nombre="301212735";
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode( GL_MODELVIEW_MATRIX );
glLoadIdentity();
glColor3f(1.0, 1.0, 0.0);
glTranslatef(200,200,0);
glScalef(scalx,scaly,0);
glRotatef(ang,0,0,0);
glRotatef(ang,0,0,1);
glRotatef(180,1,0,0);
sprintf(etiqueta,"%s", nombre);
Dibuja(etiqueta);
glFlush();
}

void keyboard (unsigned char key, int x, int y){
switch (key){
case ' ':
ang=ang-45;
printf("%d\n",ang);
glutPostRedisplay();
break;
case 'r':
ang=180;
ang2=180;
transx=250;
transy=250;
scalx=0.5;
scaly=0.5;
glutPostRedisplay();
break;
case 'R':
ang=180;
ang2=180;
transx=250;
transy=250;
scalx=0.5;
scaly=0.5;
glutPostRedisplay();
break;
}}

void mouse(int button,int state,int x,int y){
if(state == GLUT_DOWN)
{
switch(button){
case GLUT_LEFT_BUTTON:
scalx=scalx/2;
scaly=scaly/2;
break;

case GLUT_RIGHT_BUTTON:
transx=transx+20;
transy=transy+20;
break;
}
}
glutPostRedisplay();
}
void init(void){
glClearColor(0.4,0.2,0.8,1.0);
}

int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
glutInitWindowSize(550,300);
glutInitWindowPosition(400, 100);
glutCreateWindow("Número de cuenta");
glutDisplayFunc(display);
init();
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}